-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgspostgresrasterprovider.cpp
2394 lines (2115 loc) · 86.4 KB
/
qgspostgresrasterprovider.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgspostgresrasterprovider.cpp - QgsPostgresRasterProvider
---------------------
begin : 20.12.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 <cstring>
#include "qgspostgresrasterprovider.h"
#include "qgspostgrestransaction.h"
#include "qgsmessagelog.h"
#include "qgsrectangle.h"
#include "qgspolygon.h"
#include "qgspostgresprovider.h"
#include "qgsgdalutils.h"
#include "qgsstringutils.h"
const QString QgsPostgresRasterProvider::PG_RASTER_PROVIDER_KEY = QStringLiteral( "postgresraster" );
const QString QgsPostgresRasterProvider::PG_RASTER_PROVIDER_DESCRIPTION = QStringLiteral( "Postgres raster provider" );
QgsPostgresRasterProvider::QgsPostgresRasterProvider( const QString &uri, const QgsDataProvider::ProviderOptions &providerOptions, QgsDataProvider::ReadFlags flags )
: QgsRasterDataProvider( uri, providerOptions, flags )
, mShared( new QgsPostgresRasterSharedData )
{
mUri = uri;
// populate members from the uri structure
mSchemaName = mUri.schema();
if ( mSchemaName.isEmpty() )
{
mSchemaName = QStringLiteral( "public" );
}
mTableName = mUri.table();
mRasterColumn = mUri.geometryColumn();
mSqlWhereClause = mUri.sql();
mRequestedSrid = mUri.srid();
/* do not support queries for now
if ( mSchemaName.isEmpty() && mTableName.startsWith( '(' ) && mTableName.endsWith( ')' ) )
{
mIsQuery = true;
mQuery = mTableName;
mTableName.clear();
}
else
*/
{
mIsQuery = false;
if ( !mSchemaName.isEmpty() )
{
mQuery += quotedIdentifier( mSchemaName ) + '.';
}
if ( !mTableName.isEmpty() )
{
mQuery += quotedIdentifier( mTableName );
}
}
// TODO: for now always true
// mUseEstimatedMetadata = mUri.useEstimatedMetadata();
QgsDebugMsgLevel( QStringLiteral( "Connection info is %1" ).arg( mUri.connectionInfo( false ) ), 4 );
QgsDebugMsgLevel( QStringLiteral( "Schema is: %1" ).arg( mSchemaName ), 4 );
QgsDebugMsgLevel( QStringLiteral( "Table name is: %1" ).arg( mTableName ), 4 );
QgsDebugMsgLevel( QStringLiteral( "Query is: %1" ).arg( mQuery ), 4 );
QgsDebugMsgLevel( QStringLiteral( "Where clause is: %1" ).arg( mSqlWhereClause ), 4 );
// no table/query passed, the provider could be used to get tables
if ( mQuery.isEmpty() )
{
return;
}
mConnectionRO = QgsPostgresConn::connectDb( mUri.connectionInfo( false ), true );
if ( !mConnectionRO )
{
return;
}
if ( !hasSufficientPermsAndCapabilities() ) // check permissions and set capabilities
{
disconnectDb();
return;
}
if ( !init() ) // gets srid and data type
{
// the table is not a raster table
QgsMessageLog::logMessage( tr( "Invalid PostgreSQL raster layer" ), tr( "PostGIS" ) );
disconnectDb();
return;
}
// Check if requested srid and detected srid match
if ( ! mDetectedSrid.isEmpty() && ! mRequestedSrid.isEmpty() && mRequestedSrid != mDetectedSrid )
{
QgsMessageLog::logMessage( tr( "Requested SRID (%1) and detected SRID (%2) differ" )
.arg( mRequestedSrid )
.arg( mDetectedSrid ),
QStringLiteral( "PostGIS" ), Qgis::Warning );
}
mLayerMetadata.setType( QStringLiteral( "dataset" ) );
mLayerMetadata.setCrs( crs() );
mValid = true;
}
QgsPostgresRasterProvider::QgsPostgresRasterProvider( const QgsPostgresRasterProvider &other, const QgsDataProvider::ProviderOptions &providerOptions, QgsDataProvider::ReadFlags flags )
: QgsRasterDataProvider( other.dataSourceUri(), providerOptions, flags )
, mValid( other.mValid )
, mCrs( other.mCrs )
, mUri( other.mUri )
, mIsQuery( other.mIsQuery )
, mTableName( other.mTableName )
, mQuery( other.mQuery )
, mRasterColumn( other.mRasterColumn )
, mSchemaName( other.mSchemaName )
, mSqlWhereClause( other.mSqlWhereClause )
, mExtent( other.mExtent )
, mUseEstimatedMetadata( other.mUseEstimatedMetadata )
, mDataTypes( other.mDataTypes )
, mDataSizes( other.mDataSizes )
, mOverViews( other.mOverViews )
, mBandCount( other.mBandCount )
, mIsTiled( other.mIsTiled )
, mIsOutOfDb( other.mIsOutOfDb )
, mHasSpatialIndex( other.mHasSpatialIndex )
, mWidth( other.mWidth )
, mHeight( other.mHeight )
, mTileWidth( other.mTileWidth )
, mTileHeight( other.mTileHeight )
, mScaleX( other.mScaleX )
, mScaleY( other.mScaleY )
, mTemporalFieldIndex( other.mTemporalFieldIndex )
, mTemporalDefaultTime( other.mTemporalDefaultTime )
, mAttributeFields( other.mAttributeFields )
, mIdentityFields( other.mIdentityFields )
, mDefaultValues( other.mDefaultValues )
, mDataComment( other.mDataComment )
, mDetectedSrid( other.mDetectedSrid )
, mRequestedSrid( other.mRequestedSrid )
, mConnectionRO( other.mConnectionRO )
, mConnectionRW( other.mConnectionRW )
, mPrimaryKeyType( other.mPrimaryKeyType )
, mPrimaryKeyAttrs( other.mPrimaryKeyAttrs )
, mShared( other.mShared )
{
}
bool QgsPostgresRasterProvider::hasSufficientPermsAndCapabilities()
{
QgsDebugMsgLevel( QStringLiteral( "Checking for permissions on the relation" ), 4 );
QgsPostgresResult testAccess;
if ( !mIsQuery )
{
// Check that we can read from the table (i.e., we have select permission).
QString sql = QStringLiteral( "SELECT * FROM %1 LIMIT 1" ).arg( mQuery );
QgsPostgresResult testAccess( connectionRO()->PQexec( sql ) );
if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK )
{
QgsMessageLog::logMessage( tr( "Unable to access the %1 relation.\nThe error message from the database was:\n%2.\nSQL: %3" )
.arg( mQuery,
testAccess.PQresultErrorMessage(),
sql ), tr( "PostGIS" ) );
return false;
}
if ( connectionRO()->pgVersion() >= 90000 )
{
testAccess = connectionRO()->PQexec( QStringLiteral( "SELECT pg_is_in_recovery()" ) );
if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK || testAccess.PQgetvalue( 0, 0 ) == QLatin1String( "t" ) )
{
QgsMessageLog::logMessage( tr( "PostgreSQL is still in recovery after a database crash\n(or you are connected to a (read-only) standby server).\nWrite accesses will be denied." ), tr( "PostGIS" ) );
}
}
}
return true;
}
QgsCoordinateReferenceSystem QgsPostgresRasterProvider::crs() const
{
return mCrs;
}
QgsRectangle QgsPostgresRasterProvider::extent() const
{
return mExtent;
}
bool QgsPostgresRasterProvider::isValid() const
{
return mValid;
}
QString QgsPostgresRasterProvider::name() const
{
return QgsPostgresRasterProvider::PG_RASTER_PROVIDER_KEY;
}
QString QgsPostgresRasterProvider::description() const
{
return QgsPostgresRasterProvider::PG_RASTER_PROVIDER_DESCRIPTION;
}
bool QgsPostgresRasterProvider::readBlock( int bandNo, const QgsRectangle &viewExtent, int width, int height, void *data, QgsRasterBlockFeedback * )
{
if ( bandNo > mBandCount )
{
QgsMessageLog::logMessage( tr( "Invalid band number '%1" ).arg( bandNo ), QStringLiteral( "PostGIS" ), Qgis::Critical );
return false;
}
const QgsRectangle rasterExtent = viewExtent.intersect( mExtent );
if ( rasterExtent.isEmpty() )
{
QgsMessageLog::logMessage( tr( "Requested extent is not valid" ), QStringLiteral( "PostGIS" ), Qgis::Critical );
return false;
}
const bool isSingleValue { width == 1 && height == 1 };
QString tableToQuery { mQuery };
QString whereAnd { subsetStringWithTemporalRange() };
if ( ! whereAnd.isEmpty() )
{
whereAnd = whereAnd.append( QStringLiteral( " AND " ) );
}
// Identify
if ( isSingleValue )
{
QString sql;
sql = QStringLiteral( "SELECT ST_Value( ST_Band( %1, %2), ST_GeomFromText( %3, %4 ), FALSE ) "
"FROM %5 "
"WHERE %6 %1 && ST_GeomFromText( %3, %4 )" )
.arg( quotedIdentifier( mRasterColumn ) )
.arg( bandNo )
.arg( quotedValue( viewExtent.center().asWkt() ) )
.arg( mCrs.postgisSrid() )
.arg( mQuery )
.arg( whereAnd );
QgsPostgresResult result( connectionRO()->PQexec( sql ) );
if ( result.PQresultStatus() != PGRES_TUPLES_OK )
{
QgsMessageLog::logMessage( tr( "Unable to access the %1 relation.\nThe error message from the database was:\n%2.\nSQL: %3" )
.arg( mQuery,
result.PQresultErrorMessage(),
sql ), tr( "PostGIS" ) );
return false;
}
bool ok;
const QString val { result.PQgetvalue( 0, 0 ) };
const Qgis::DataType dataType { mDataTypes[ static_cast<unsigned int>( bandNo - 1 ) ] };
switch ( dataType )
{
case Qgis::DataType::Byte:
{
const unsigned short byte { val.toUShort( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to byte" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &byte, sizeof( unsigned short ) );
break;
}
case Qgis::DataType::UInt16:
{
const unsigned int uint { val.toUInt( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to unsigned int" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &uint, sizeof( unsigned int ) );
break;
}
case Qgis::DataType::UInt32:
{
const unsigned long ulong { val.toULong( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to unsigned long" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &ulong, sizeof( unsigned long ) );
break;
}
case Qgis::DataType::Int16:
{
const int intVal { val.toInt( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to int" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &intVal, sizeof( int ) );
break;
}
case Qgis::DataType::Int32:
{
const long longVal { val.toLong( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to long" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &longVal, sizeof( long ) );
break;
}
case Qgis::DataType::Float32:
{
const float floatVal { val.toFloat( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to float" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &floatVal, sizeof( float ) );
break;
}
case Qgis::DataType::Float64:
{
const double doubleVal { val.toDouble( &ok ) };
if ( ! ok )
{
QgsMessageLog::logMessage( tr( "Cannot convert identified value to double" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
std::memcpy( data, &doubleVal, sizeof( double ) );
break;
}
default:
{
QgsMessageLog::logMessage( tr( "Unknown identified data type" ), QStringLiteral( "PostGIS" ), Qgis::Warning );
return false;
}
}
}
else // Fetch block
{
const double xRes = viewExtent.width() / width;
const double yRes = viewExtent.height() / height;
// Find overview
const int minPixelSize { static_cast<int>( std::min( xRes, yRes ) ) };
// TODO: round?
const unsigned int desiredOverviewFactor { static_cast<unsigned int>( minPixelSize / std::max( std::abs( mScaleX ), std::abs( mScaleY ) ) ) };
unsigned int overviewFactor { 1 }; // no overview
// Cannot use overviews if there is a where condition
if ( whereAnd.isEmpty() )
{
const auto ovKeys { mOverViews.keys( ) };
QList<unsigned int>::const_reverse_iterator rit { ovKeys.rbegin() };
for ( ; rit != ovKeys.rend(); ++rit )
{
if ( *rit <= desiredOverviewFactor )
{
tableToQuery = mOverViews[ *rit ];
overviewFactor = *rit;
QgsDebugMsgLevel( QStringLiteral( "Using overview for block read: %1" ).arg( tableToQuery ), 3 );
break;
}
}
}
//qDebug() << "Overview desired: " << desiredOverviewFactor << "found:" << overviewFactor << tableToQuery;
//qDebug() << "View extent" << viewExtent.toString( 1 ) << width << height << minPixelSize;
// Get the the tiles we need to build the block
const QgsPostgresRasterSharedData::TilesRequest tilesRequest
{
bandNo,
rasterExtent,
overviewFactor,
pkSql(), // already quoted
quotedIdentifier( mRasterColumn ),
tableToQuery,
QString::number( mCrs.postgisSrid() ),
whereAnd,
connectionRO()
};
const QgsPostgresRasterSharedData::TilesResponse tileResponse
{
mShared->tiles( tilesRequest )
};
if ( tileResponse.tiles.isEmpty() )
{
QgsMessageLog::logMessage( tr( "No tiles available in table %1 for the requested extent: %2" )
.arg( tableToQuery, rasterExtent.toString( ) ), tr( "PostGIS" ), Qgis::Critical );
return false;
}
// Finally merge the tiles
// We must have at least one tile at this point (we checked for that before)
const QgsRectangle &tilesExtent { tileResponse.extent };
// Prepare tmp output raster
const int tmpWidth = static_cast<int>( std::round( tilesExtent.width() / tileResponse.tiles.first().scaleX ) );
const int tmpHeight = static_cast<int>( std::round( tilesExtent.height() / std::fabs( tileResponse.tiles.first().scaleY ) ) );
GDALDataType gdalDataType { static_cast<GDALDataType>( sourceDataType( bandNo ) ) };
//qDebug() << "Creating output raster: " << tilesExtent.toString() << tmpWidth << tmpHeight;
gdal::dataset_unique_ptr tmpDS { QgsGdalUtils::createSingleBandMemoryDataset(
gdalDataType, tilesExtent, tmpWidth, tmpHeight, mCrs ) };
if ( ! tmpDS )
{
{
QgsMessageLog::logMessage( tr( "Unable to create temporary raster for tiles from %1" )
.arg( tableToQuery ), tr( "PostGIS" ), Qgis::Critical );
return false;
}
}
// Write tiles to the temporary raster
CPLErrorReset();
for ( auto &tile : qgis::as_const( tileResponse.tiles ) )
{
// Offset in px from the base raster
const int xOff { static_cast<int>( std::round( ( tile.upperLeftX - tilesExtent.xMinimum() ) / tile.scaleX ) ) };
const int yOff { static_cast<int>( std::round( ( tilesExtent.yMaximum() - tile.extent.yMaximum() ) / std::fabs( tile.scaleY ) ) )};
//qDebug() << "Merging tile output raster: " << tile.tileId << xOff << yOff << tile.width << tile.height ;
CPLErr err = GDALRasterIO( GDALGetRasterBand( tmpDS.get(), 1 ),
GF_Write,
xOff,
yOff,
static_cast<int>( tile.width ),
static_cast<int>( tile.height ),
( void * )( tile.data.constData() ), // old-style because of const
static_cast<int>( tile.width ),
static_cast<int>( tile.height ),
gdalDataType,
0,
0 );
if ( err != CE_None )
{
const QString lastError = QString::fromUtf8( CPLGetLastErrorMsg() ) ;
QgsMessageLog::logMessage( tr( "Unable to write tile to temporary raster from %1: %2" )
.arg( tableToQuery, lastError ), tr( "PostGIS" ), Qgis::Critical );
return false;
}
}
#if 0
// Debug output raster content
double pdfMin;
double pdfMax;
double pdfMean;
double pdfStdDev;
GDALGetRasterStatistics( GDALGetRasterBand( tmpDS.get(), 1 ), 0, 1, &pdfMin, &pdfMax, &pdfMean, &pdfStdDev );
qDebug() << pdfMin << pdfMax << pdfMean << pdfStdDev;
#endif
// Write data to the output block
gdal::dataset_unique_ptr dstDS { QgsGdalUtils::createSingleBandMemoryDataset(
gdalDataType, viewExtent, width, height, mCrs ) };
if ( ! dstDS )
{
const QString lastError = QString::fromUtf8( CPLGetLastErrorMsg() ) ;
QgsMessageLog::logMessage( tr( "Unable to create destination raster for tiles from %1: %2" )
.arg( tableToQuery, lastError ), tr( "PostGIS" ), Qgis::Critical );
return false;
}
// Resample the raster to the final bounds and resolution
QgsGdalUtils::resampleSingleBandRaster( tmpDS.get(), dstDS.get(), GDALResampleAlg::GRA_NearestNeighbour );
// Copy to result buffer
CPLErrorReset();
CPLErr err = GDALRasterIO( GDALGetRasterBand( dstDS.get(), 1 ),
GF_Read,
0,
0,
width,
height,
data,
width,
height,
gdalDataType,
0,
0 );
if ( err != CE_None )
{
const QString lastError = QString::fromUtf8( CPLGetLastErrorMsg() ) ;
QgsMessageLog::logMessage( tr( "Unable to write raster to block from %1: %2" )
.arg( mQuery, lastError ), tr( "PostGIS" ), Qgis::Critical );
return false;
}
#if 0
GDALGetRasterStatistics( GDALGetRasterBand( dstDS.get(), 1 ), 0, 1, &pdfMin, &pdfMax, &pdfMean, &pdfStdDev );
qDebug() << pdfMin << pdfMax << pdfMean << pdfStdDev;
// Spit it out float 32 data
for ( int i = 0; i < width * height; ++i )
{
qDebug() << reinterpret_cast<const float *>( data )[ i * 4 ];
}
#endif
}
return true;
}
QgsPostgresRasterProviderMetadata::QgsPostgresRasterProviderMetadata()
: QgsProviderMetadata( QgsPostgresRasterProvider::PG_RASTER_PROVIDER_KEY, QgsPostgresRasterProvider::PG_RASTER_PROVIDER_DESCRIPTION )
{
}
QVariantMap QgsPostgresRasterProviderMetadata::decodeUri( const QString &uri )
{
const QgsDataSourceUri dsUri { uri };
QVariantMap decoded;
if ( ! dsUri.database().isEmpty() )
{
decoded[ QStringLiteral( "dbname" ) ] = dsUri.database();
}
if ( ! dsUri.host().isEmpty() )
{
decoded[ QStringLiteral( "host" ) ] = dsUri.host();
}
if ( ! dsUri.port().isEmpty() )
{
decoded[ QStringLiteral( "port" ) ] = dsUri.port();
}
if ( ! dsUri.service().isEmpty() )
{
decoded[ QStringLiteral( "service" ) ] = dsUri.service();
}
if ( ! dsUri.username().isEmpty() )
{
decoded[ QStringLiteral( "username" ) ] = dsUri.username();
}
if ( ! dsUri.password().isEmpty() )
{
decoded[ QStringLiteral( "password" ) ] = dsUri.password();
}
if ( ! dsUri.authConfigId().isEmpty() )
{
decoded[ QStringLiteral( "authcfg" ) ] = dsUri.authConfigId();
}
if ( ! dsUri.schema().isEmpty() )
{
decoded[ QStringLiteral( "schema" ) ] = dsUri.schema();
}
if ( ! dsUri.table().isEmpty() )
{
decoded[ QStringLiteral( "table" ) ] = dsUri.table();
}
if ( ! dsUri.keyColumn().isEmpty() )
{
decoded[ QStringLiteral( "key" ) ] = dsUri.keyColumn();
}
if ( ! dsUri.srid().isEmpty() )
{
decoded[ QStringLiteral( "srid" ) ] = dsUri.srid();
}
if ( uri.contains( QStringLiteral( "estimatedmetadata=" ), Qt::CaseSensitivity::CaseInsensitive ) )
{
decoded[ QStringLiteral( "estimatedmetadata" ) ] = dsUri.useEstimatedMetadata();
}
if ( uri.contains( QStringLiteral( "sslmode=" ), Qt::CaseSensitivity::CaseInsensitive ) )
{
decoded[ QStringLiteral( "sslmode" ) ] = dsUri.sslMode();
}
// Do not add sql if it's empty
if ( ! dsUri.sql().isEmpty() )
{
decoded[ QStringLiteral( "sql" ) ] = dsUri.sql();
}
if ( ! dsUri.geometryColumn().isEmpty() )
{
decoded[ QStringLiteral( "geometrycolumn" ) ] = dsUri.geometryColumn();
}
// Params
const static QStringList params {{
QStringLiteral( "temporalFieldIndex" ),
QStringLiteral( "temporalDefaultTime" ),
QStringLiteral( "enableTime" )
}};
for ( const QString &pname : qgis::as_const( params ) )
{
if ( dsUri.hasParam( pname ) )
{
decoded[ pname ] = dsUri.param( pname );
}
}
return decoded;
}
QString QgsPostgresRasterProviderMetadata::encodeUri( const QVariantMap &parts )
{
QgsDataSourceUri dsUri;
if ( parts.contains( QStringLiteral( "dbname" ) ) )
dsUri.setDatabase( parts.value( QStringLiteral( "dbname" ) ).toString() );
if ( parts.contains( QStringLiteral( "port" ) ) )
dsUri.setParam( QStringLiteral( "port" ), parts.value( QStringLiteral( "port" ) ).toString() );
if ( parts.contains( QStringLiteral( "host" ) ) )
dsUri.setParam( QStringLiteral( "host" ), parts.value( QStringLiteral( "host" ) ).toString() );
if ( parts.contains( QStringLiteral( "service" ) ) )
dsUri.setParam( QStringLiteral( "service" ), parts.value( QStringLiteral( "service" ) ).toString() );
if ( parts.contains( QStringLiteral( "username" ) ) )
dsUri.setUsername( parts.value( QStringLiteral( "username" ) ).toString() );
if ( parts.contains( QStringLiteral( "password" ) ) )
dsUri.setPassword( parts.value( QStringLiteral( "password" ) ).toString() );
if ( parts.contains( QStringLiteral( "authcfg" ) ) )
dsUri.setAuthConfigId( parts.value( QStringLiteral( "authcfg" ) ).toString() );
if ( parts.contains( QStringLiteral( "selectatid" ) ) )
dsUri.setParam( QStringLiteral( "selectatid" ), parts.value( QStringLiteral( "selectatid" ) ).toString() );
if ( parts.contains( QStringLiteral( "table" ) ) )
dsUri.setTable( parts.value( QStringLiteral( "table" ) ).toString() );
if ( parts.contains( QStringLiteral( "schema" ) ) )
dsUri.setSchema( parts.value( QStringLiteral( "schema" ) ).toString() );
if ( parts.contains( QStringLiteral( "key" ) ) )
dsUri.setParam( QStringLiteral( "key" ), parts.value( QStringLiteral( "key" ) ).toString() );
if ( parts.contains( QStringLiteral( "srid" ) ) )
dsUri.setSrid( parts.value( QStringLiteral( "srid" ) ).toString() );
if ( parts.contains( QStringLiteral( "estimatedmetadata" ) ) )
dsUri.setParam( QStringLiteral( "estimatedmetadata" ), parts.value( QStringLiteral( "estimatedmetadata" ) ).toString() );
if ( parts.contains( QStringLiteral( "sslmode" ) ) )
dsUri.setParam( QStringLiteral( "sslmode" ), QgsDataSourceUri::encodeSslMode( static_cast<QgsDataSourceUri::SslMode>( parts.value( QStringLiteral( "sslmode" ) ).toInt( ) ) ) );
if ( parts.contains( QStringLiteral( "sql" ) ) )
dsUri.setSql( parts.value( QStringLiteral( "sql" ) ).toString() );
if ( parts.contains( QStringLiteral( "geometrycolumn" ) ) )
dsUri.setGeometryColumn( parts.value( QStringLiteral( "geometrycolumn" ) ).toString() );
if ( parts.contains( QStringLiteral( "temporalFieldIndex" ) ) )
dsUri.setParam( QStringLiteral( "temporalFieldIndex" ), parts.value( QStringLiteral( "temporalFieldIndex" ) ).toString() );
if ( parts.contains( QStringLiteral( "temporalDefaultTime" ) ) )
dsUri.setParam( QStringLiteral( "temporalDefaultTime" ), parts.value( QStringLiteral( "temporalDefaultTime" ) ).toString() );
if ( parts.contains( QStringLiteral( "enableTime" ) ) )
dsUri.setParam( QStringLiteral( "enableTime" ), parts.value( QStringLiteral( "enableTime" ) ).toString() );
return dsUri.uri( false );
}
QgsPostgresRasterProvider *QgsPostgresRasterProviderMetadata::createProvider( const QString &uri, const QgsDataProvider::ProviderOptions &options, QgsDataProvider::ReadFlags flags )
{
return new QgsPostgresRasterProvider( uri, options, flags );
}
Qgis::DataType QgsPostgresRasterProvider::dataType( int bandNo ) const
{
if ( mDataTypes.size() < static_cast<unsigned long>( bandNo ) )
{
QgsMessageLog::logMessage( tr( "Data type size for band %1 could not be found: num bands is: %2 and the type size map for bands contains: %3 items" )
.arg( bandNo )
.arg( mBandCount )
.arg( mDataSizes.size() ),
QStringLiteral( "PostGIS" ), Qgis::Warning );
return Qgis::DataType::UnknownDataType;
}
// Band is 1-based
return mDataTypes[ static_cast<unsigned long>( bandNo ) - 1 ];
}
int QgsPostgresRasterProvider::bandCount() const
{
return mBandCount;
}
QgsRasterInterface *QgsPostgresRasterProvider::clone() const
{
QgsDataProvider::ProviderOptions options;
options.transformContext = transformContext();
QgsPostgresRasterProvider *provider = new QgsPostgresRasterProvider( *this, options );
provider->copyBaseSettings( *this );
return provider;
}
static inline QString dumpVariantMap( const QVariantMap &variantMap, const QString &title = QString() )
{
QString result;
if ( !title.isEmpty() )
{
result += QStringLiteral( "<tr><td class=\"highlight\">%1</td><td></td></tr>" ).arg( title );
}
for ( auto it = variantMap.constBegin(); it != variantMap.constEnd(); ++it )
{
const QVariantMap childMap = it.value().toMap();
const QVariantList childList = it.value().toList();
if ( !childList.isEmpty() )
{
result += QStringLiteral( "<tr><td class=\"highlight\">%1</td><td><ul>" ).arg( it.key() );
for ( const QVariant &v : childList )
{
const QVariantMap grandChildMap = v.toMap();
if ( !grandChildMap.isEmpty() )
{
result += QStringLiteral( "<li><table>%1</table></li>" ).arg( dumpVariantMap( grandChildMap ) );
}
else
{
result += QStringLiteral( "<li>%1</li>" ).arg( QgsStringUtils::insertLinks( v.toString() ) );
}
}
result += QStringLiteral( "</ul></td></tr>" );
}
else if ( !childMap.isEmpty() )
{
result += QStringLiteral( "<tr><td class=\"highlight\">%1</td><td><table>%2</table></td></tr>" ).arg( it.key(), dumpVariantMap( childMap ) );
}
else
{
result += QStringLiteral( "<tr><td class=\"highlight\">%1</td><td>%2</td></tr>" ).arg( it.key(), QgsStringUtils::insertLinks( it.value().toString() ) );
}
}
return result;
}
QString QgsPostgresRasterProvider::htmlMetadata()
{
// This must return the content of a HTML table starting by tr and ending by tr
QVariantMap overviews;
for ( auto it = mOverViews.constBegin(); it != mOverViews.constEnd(); ++it )
{
overviews.insert( QString::number( it.key() ), it.value() );
}
const QVariantMap additionalInformation
{
{ tr( "Is Tiled" ), mIsTiled },
{ tr( "Where Clause SQL" ), subsetString() },
{ tr( "Pixel Size" ), QStringLiteral( "%1, %2" ).arg( mScaleX ).arg( mScaleY ) },
{ tr( "Overviews" ), overviews },
{ tr( "Primary Keys SQL" ), pkSql() },
{ tr( "Temporal Column" ), mTemporalFieldIndex >= 0 && mAttributeFields.exists( mTemporalFieldIndex ) ? mAttributeFields.field( mTemporalFieldIndex ).name() : QString() },
};
return dumpVariantMap( additionalInformation, tr( "Additional information" ) );
}
QString QgsPostgresRasterProvider::lastErrorTitle()
{
return mErrorTitle;
}
QString QgsPostgresRasterProvider::lastError()
{
return mError;
}
int QgsPostgresRasterProvider::capabilities() const
{
const int capability = QgsRasterDataProvider::Identify
| QgsRasterDataProvider::IdentifyValue
| QgsRasterDataProvider::Size
// TODO:| QgsRasterDataProvider::BuildPyramids
| QgsRasterDataProvider::Create
| QgsRasterDataProvider::Remove
| QgsRasterDataProvider::Prefetch;
return capability;
}
QgsPostgresConn *QgsPostgresRasterProvider::connectionRO() const
{
return mConnectionRO;
}
QgsPostgresConn *QgsPostgresRasterProvider::connectionRW()
{
if ( !mConnectionRW )
{
mConnectionRW = QgsPostgresConn::connectDb( mUri.connectionInfo( false ), false );
}
return mConnectionRW;
}
QString QgsPostgresRasterProvider::subsetString() const
{
return mSqlWhereClause;
}
QString QgsPostgresRasterProvider::defaultTimeSubsetString( const QDateTime &defaultTime ) const
{
if ( defaultTime.isValid( ) &&
mTemporalFieldIndex >= 0 &&
mAttributeFields.exists( mTemporalFieldIndex ) )
{
const QgsField temporalField { mAttributeFields.field( mTemporalFieldIndex ) };
const QString typeCast { temporalField.type() != QVariant::DateTime ? QStringLiteral( "::timestamp" ) : QString() };
const QString temporalFieldName { temporalField.name() };
return { QStringLiteral( "%1%2 = %3" )
.arg( quotedIdentifier( temporalFieldName ),
typeCast,
quotedValue( defaultTime.toString( Qt::DateFormat::ISODate ) ) ) };
}
else
{
return QString();
}
}
bool QgsPostgresRasterProvider::setSubsetString( const QString &subset, bool updateFeatureCount )
{
Q_UNUSED( updateFeatureCount )
const QString oldSql { mSqlWhereClause };
mSqlWhereClause = subset;
// Recalculate extent and other metadata calling init()
if ( !init() )
{
// Restore
mSqlWhereClause = oldSql;
init();
return false;
}
mStatistics.clear();
mShared->invalidateCache();
// Update datasource uri too
mUri.setSql( subset );
setDataSourceUri( mUri.uri( false ) );
return true;
}
QString QgsPostgresRasterProvider::subsetStringWithTemporalRange() const
{
// Temporal
if ( mTemporalFieldIndex >= 0 && mAttributeFields.exists( mTemporalFieldIndex ) )
{
const QgsField temporalField { mAttributeFields.field( mTemporalFieldIndex ) };
const QString typeCast { temporalField.type() != QVariant::DateTime ? QStringLiteral( "::timestamp" ) : QString() };
const QString temporalFieldName { temporalField.name() };
if ( temporalCapabilities()->hasTemporalCapabilities() )
{
QString temporalClause;
const QgsTemporalRange<QDateTime> requestedRange { temporalCapabilities()->requestedTemporalRange() };
if ( ! requestedRange.isEmpty() && ! requestedRange.isInfinite() )
{
if ( requestedRange.isInstant() )
{
temporalClause = QStringLiteral( "%1%2 = %3" )
.arg( quotedIdentifier( temporalFieldName ),
typeCast,
quotedValue( requestedRange.begin().toString( Qt::DateFormat::ISODate ) ) );
}
else
{
if ( requestedRange.begin().isValid() )
{
temporalClause = QStringLiteral( "%1%2 %3 %4" )
.arg( quotedIdentifier( temporalFieldName ),
typeCast,
requestedRange.includeBeginning() ? ">=" : ">",
quotedValue( requestedRange.begin().toString( Qt::DateFormat::ISODate ) ) );
}
if ( requestedRange.end().isValid() )
{
if ( ! temporalClause.isEmpty() )
{
temporalClause.append( QStringLiteral( " AND " ) );
}
temporalClause.append( QStringLiteral( "%1%2 %3 %4" )
.arg( quotedIdentifier( temporalFieldName ),
typeCast,
requestedRange.includeEnd() ? "<=" : "<",
quotedValue( requestedRange.end().toString( Qt::DateFormat::ISODate ) ) ) );
}
}
return mSqlWhereClause.isEmpty() ? temporalClause : QStringLiteral( "%1 AND (%2)" ).arg( mSqlWhereClause, temporalClause );
}
const QString defaultTimeSubset { defaultTimeSubsetString( mTemporalDefaultTime ) };
if ( ! defaultTimeSubset.isEmpty() )
{
return mSqlWhereClause.isEmpty() ? defaultTimeSubset : QStringLiteral( "%1 AND (%2)" ).arg( mSqlWhereClause, defaultTimeSubset );
}
}
}
return mSqlWhereClause;
}
void QgsPostgresRasterProvider::disconnectDb()
{
if ( mConnectionRO )
{
mConnectionRO->unref();
mConnectionRO = nullptr;
}
if ( mConnectionRW )
{
mConnectionRW->unref();
mConnectionRW = nullptr;
}
}
bool QgsPostgresRasterProvider::init()
{
// WARNING: multiple failure and return points!
if ( !determinePrimaryKey() )
{
QgsMessageLog::logMessage( tr( "PostgreSQL raster layer has no primary key." ), tr( "PostGIS" ) );
return false;
}
// We first try to collect raster information using raster_columns information
// unless:
// - it is a query layer (unsupported at the moment)
// - use estimated metadata is false
// - there is a WHERE condition (except for temporal default value )
// If previous conditions are not met or the first method fail try to fetch information
// directly from the raster data. This can be very slow.
// Note that a temporal filter set as temporal default value does not count as a WHERE condition
// utility to get data type from string, used in both branches
auto pixelTypeFromString = [ ]( const QString & t ) -> Qgis::DataType
{
/* Pixel types
1BB - 1-bit boolean
2BUI - 2-bit unsigned integer
4BUI - 4-bit unsigned integer
8BSI - 8-bit signed integer
8BUI - 8-bit unsigned integer
16BSI - 16-bit signed integer
16BUI - 16-bit unsigned integer
32BSI - 32-bit signed integer
32BUI - 32-bit unsigned integer
32BF - 32-bit float
64BF - 64-bit float
*/
Qgis::DataType type { Qgis::DataType::UnknownDataType };
if ( t == QStringLiteral( "8BUI" ) )
{
type = Qgis::DataType::Byte;
}
else if ( t == QStringLiteral( "16BUI" ) )
{
type = Qgis::DataType::UInt16;
}
else if ( t == QStringLiteral( "16BSI" ) )
{
type = Qgis::DataType::Int16;
}
else if ( t == QStringLiteral( "32BSI" ) )
{
type = Qgis::DataType::Int32;
}
else if ( t == QStringLiteral( "32BUI" ) )
{
type = Qgis::DataType::UInt32;
}
else if ( t == QStringLiteral( "32BF" ) )
{
type = Qgis::DataType::Float32;
}
else if ( t == QStringLiteral( "64BF" ) )
{
type = Qgis::DataType::Float64;
}
return type;
};
// ///////////////////////////////////////////////////////////////////
// First method: get information from metadata
if ( ! mIsQuery && mUseEstimatedMetadata && subsetString().isEmpty() )
{