-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgspostgresprovider.cpp
5232 lines (4473 loc) · 169 KB
/
qgspostgresprovider.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
/***************************************************************************
qgspostgresprovider.cpp - QGIS data provider for PostgreSQL/PostGIS layers
-------------------
begin : 2004/01/07
copyright : (C) 2004 by Gary E.Sherman
email : sherman at mrcc.com
***************************************************************************/
/***************************************************************************
* *
* 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 "qgsapplication.h"
#include "qgsfeature.h"
#include "qgsfield.h"
#include "qgsgeometry.h"
#include "qgsmessageoutput.h"
#include "qgsmessagelog.h"
#include "qgsprojectstorageregistry.h"
#include "qgsrectangle.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsxmlutils.h"
#include "qgsvectorlayer.h"
#include <QMessageBox>
#include "qgsvectorlayerexporter.h"
#include "qgspostgresprovider.h"
#include "qgspostgresconn.h"
#include "qgspostgresconnpool.h"
#include "qgspostgresdataitems.h"
#include "qgspostgresfeatureiterator.h"
#include "qgspostgrestransaction.h"
#include "qgspostgreslistener.h"
#include "qgspostgresprojectstorage.h"
#include "qgspostgresproviderconnection.h"
#include "qgslogger.h"
#include "qgsfeedback.h"
#include "qgssettings.h"
#include "qgsjsonutils.h"
#include "qgspostgresprovider.h"
#include "qgsprovidermetadata.h"
#include "qgspostgresproviderconnection.h"
const QString QgsPostgresProvider::POSTGRES_KEY = QStringLiteral( "postgres" );
const QString QgsPostgresProvider::POSTGRES_DESCRIPTION = QStringLiteral( "PostgreSQL/PostGIS data provider" );
static const QString EDITOR_WIDGET_STYLES_TABLE = QStringLiteral( "qgis_editor_widget_styles" );
inline qint64 PKINT2FID( qint32 x )
{
return QgsPostgresUtils::int32pk_to_fid( x );
}
inline qint32 FID2PKINT( qint64 x )
{
return QgsPostgresUtils::fid_to_int32pk( x );
}
static bool tableExists( QgsPostgresConn &conn, const QString &name )
{
QgsPostgresResult res( conn.PQexec( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name=" + QgsPostgresConn::quotedValue( name ) ) );
return res.PQgetvalue( 0, 0 ).toInt() > 0;
}
QgsPostgresPrimaryKeyType
QgsPostgresProvider::pkType( const QgsField &f ) const
{
switch ( f.type() )
{
case QVariant::LongLong:
// unless we can guarantee all values are unsigned
// (in which case we could use pktUint64)
// we'll have to use a Map type.
// See https://github.com/qgis/QGIS/issues/22258
return PktFidMap; // pktUint64
case QVariant::Int:
return PktInt;
default:
return PktFidMap;
}
}
QgsPostgresProvider::QgsPostgresProvider( QString const &uri, const ProviderOptions &options )
: QgsVectorDataProvider( uri, options )
, mShared( new QgsPostgresSharedData )
{
QgsDebugMsg( QStringLiteral( "URI: %1 " ).arg( uri ) );
mUri = QgsDataSourceUri( uri );
// populate members from the uri structure
mSchemaName = mUri.schema();
mTableName = mUri.table();
mGeometryColumn = mUri.geometryColumn();
mBoundingBoxColumn = mUri.param( "bbox" );
if ( mBoundingBoxColumn.isEmpty() )
{
mBoundingBoxColumn = mGeometryColumn;
}
mSqlWhereClause = mUri.sql();
mRequestedSrid = mUri.srid();
mRequestedGeomType = mUri.wkbType();
if ( mUri.hasParam( QStringLiteral( "checkPrimaryKeyUnicity" ) ) )
{
if ( mUri.param( QStringLiteral( "checkPrimaryKeyUnicity" ) ).compare( QLatin1String( "0" ) ) == 0 )
{
mCheckPrimaryKeyUnicity = false;
}
else
{
mCheckPrimaryKeyUnicity = true;
}
}
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 );
}
}
mUseEstimatedMetadata = mUri.useEstimatedMetadata();
mSelectAtIdDisabled = mUri.selectAtIdDisabled();
QgsDebugMsg( QStringLiteral( "Connection info is %1" ).arg( mUri.connectionInfo( false ) ) );
QgsDebugMsg( QStringLiteral( "Geometry column is: %1" ).arg( mGeometryColumn ) );
QgsDebugMsg( QStringLiteral( "Schema is: %1" ).arg( mSchemaName ) );
QgsDebugMsg( QStringLiteral( "Table name is: %1" ).arg( mTableName ) );
QgsDebugMsg( QStringLiteral( "Query is: %1" ).arg( mQuery ) );
QgsDebugMsg( QStringLiteral( "Where clause is: %1" ).arg( mSqlWhereClause ) );
// 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 ( !getGeometryDetails() ) // gets srid, geometry and data type
{
// the table is not a geometry table
QgsMessageLog::logMessage( tr( "Invalid PostgreSQL layer" ), tr( "PostGIS" ) );
disconnectDb();
return;
}
// NOTE: mValid would be true after true return from
// getGeometryDetails, see https://github.com/qgis/QGIS/issues/21807
if ( mSpatialColType == SctTopoGeometry )
{
if ( !getTopoLayerInfo() ) // gets topology name and layer id
{
QgsMessageLog::logMessage( tr( "Invalid PostgreSQL topology layer" ), tr( "PostGIS" ) );
mValid = false;
disconnectDb();
return;
}
}
mLayerExtent.setMinimal();
// set the primary key
if ( !determinePrimaryKey() )
{
QgsMessageLog::logMessage( tr( "PostgreSQL layer has no primary key." ), tr( "PostGIS" ) );
mValid = false;
disconnectDb();
return;
}
// Set the PostgreSQL message level so that we don't get the
// 'there is no transaction in progress' warning.
#ifndef QGISDEBUG
mConnectionRO->PQexecNR( QStringLiteral( "set client_min_messages to error" ) );
#endif
//fill type names into sets
QList<NativeType> nativeTypes;
nativeTypes // integer types
<< QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), QStringLiteral( "int2" ), QVariant::Int, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), QStringLiteral( "int4" ), QVariant::Int, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), QStringLiteral( "int8" ), QVariant::LongLong, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 )
// floating point
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 )
// string types
<< QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), QStringLiteral( "char" ), QVariant::String, 1, 255, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), QStringLiteral( "varchar" ), QVariant::String, 1, 255, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Text, case-insensitive unlimited length (citext)" ), QStringLiteral( "citext" ), QVariant::String, -1, -1, -1, -1 )
// date type
<< QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "timestamp without time zone" ), QVariant::DateTime, -1, -1, -1, -1 )
// complex types
<< QgsVectorDataProvider::NativeType( tr( "Map (hstore)" ), QStringLiteral( "hstore" ), QVariant::Map, -1, -1, -1, -1, QVariant::String )
<< QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 32bit)" ), QStringLiteral( "int4[]" ), QVariant::List, -1, -1, -1, -1, QVariant::Int )
<< QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 64bit)" ), QStringLiteral( "int8[]" ), QVariant::List, -1, -1, -1, -1, QVariant::LongLong )
<< QgsVectorDataProvider::NativeType( tr( "Array of number (double)" ), QStringLiteral( "double precision[]" ), QVariant::List, -1, -1, -1, -1, QVariant::Double )
<< QgsVectorDataProvider::NativeType( tr( "Array of text" ), QStringLiteral( "text[]" ), QVariant::StringList, -1, -1, -1, -1, QVariant::String )
// boolean
<< QgsVectorDataProvider::NativeType( tr( "Boolean" ), QStringLiteral( "bool" ), QVariant::Bool, -1, -1, -1, -1 )
// binary (bytea)
<< QgsVectorDataProvider::NativeType( tr( "Binary object (bytea)" ), QStringLiteral( "bytea" ), QVariant::ByteArray, -1, -1, -1, -1 )
;
if ( connectionRO()->pgVersion() >= 90200 )
{
nativeTypes << QgsVectorDataProvider::NativeType( tr( "JSON (json)" ), QStringLiteral( "json" ), QVariant::Map, -1, -1, -1, -1, QVariant::String );
if ( connectionRO()->pgVersion() >= 90400 )
{
nativeTypes << QgsVectorDataProvider::NativeType( tr( "JSON (jsonb)" ), QStringLiteral( "jsonb" ), QVariant::Map, -1, -1, -1, -1, QVariant::String );
}
}
setNativeTypes( nativeTypes );
QString key;
switch ( mPrimaryKeyType )
{
case PktOid:
key = QStringLiteral( "oid" );
break;
case PktTid:
key = QStringLiteral( "tid" );
break;
case PktInt:
case PktUint64:
Q_ASSERT( mPrimaryKeyAttrs.size() == 1 );
Q_ASSERT( mPrimaryKeyAttrs[0] >= 0 && mPrimaryKeyAttrs[0] < mAttributeFields.count() );
key = mAttributeFields.at( mPrimaryKeyAttrs.at( 0 ) ).name();
break;
case PktFidMap:
{
QString delim;
const auto constMPrimaryKeyAttrs = mPrimaryKeyAttrs;
for ( int idx : constMPrimaryKeyAttrs )
{
key += delim + mAttributeFields.at( idx ).name();
delim = ',';
}
}
break;
case PktUnknown:
QgsMessageLog::logMessage( tr( "PostgreSQL layer has unknown primary key type." ), tr( "PostGIS" ) );
mValid = false;
break;
}
if ( mValid )
{
mUri.setKeyColumn( key );
setDataSourceUri( mUri.uri( false ) );
}
else
{
disconnectDb();
}
mLayerMetadata.setType( QStringLiteral( "dataset" ) );
mLayerMetadata.setCrs( crs() );
}
QgsPostgresProvider::~QgsPostgresProvider()
{
disconnectDb();
QgsDebugMsg( QStringLiteral( "deconstructing." ) );
}
QgsAbstractFeatureSource *QgsPostgresProvider::featureSource() const
{
return new QgsPostgresFeatureSource( this );
}
QgsPostgresConn *QgsPostgresProvider::connectionRO() const
{
return mTransaction ? mTransaction->connection() : mConnectionRO;
}
void QgsPostgresProvider::setListening( bool isListening )
{
if ( isListening && !mListener )
{
mListener.reset( QgsPostgresListener::create( mUri.connectionInfo( false ) ).release() );
connect( mListener.get(), &QgsPostgresListener::notify, this, &QgsPostgresProvider::notify );
}
else if ( !isListening && mListener )
{
disconnect( mListener.get(), &QgsPostgresListener::notify, this, &QgsPostgresProvider::notify );
mListener.reset();
}
}
QgsPostgresConn *QgsPostgresProvider::connectionRW()
{
if ( mTransaction )
{
return mTransaction->connection();
}
else if ( !mConnectionRW )
{
mConnectionRW = QgsPostgresConn::connectDb( mUri.connectionInfo( false ), false );
}
return mConnectionRW;
}
QgsTransaction *QgsPostgresProvider::transaction() const
{
return mTransaction;
}
void QgsPostgresProvider::setTransaction( QgsTransaction *transaction )
{
// static_cast since layers cannot be added to a transaction of a non-matching provider
mTransaction = static_cast<QgsPostgresTransaction *>( transaction );
}
void QgsPostgresProvider::disconnectDb()
{
if ( mConnectionRO )
{
mConnectionRO->unref();
mConnectionRO = nullptr;
}
if ( mConnectionRW )
{
mConnectionRW->unref();
mConnectionRW = nullptr;
}
}
QString QgsPostgresProvider::quotedByteaValue( const QVariant &value )
{
if ( value.isNull() )
return QStringLiteral( "NULL" );
const QByteArray ba = value.toByteArray();
const unsigned char *buf = reinterpret_cast< const unsigned char * >( ba.constData() );
QString param;
param.reserve( ba.length() * 4 );
for ( int i = 0; i < ba.length(); ++i )
{
param += QStringLiteral( "\\%1" ).arg( static_cast< int >( buf[i] ), 3, 8, QChar( '0' ) );
}
return QStringLiteral( "decode('%1','escape')" ).arg( param );
}
QString QgsPostgresProvider::storageType() const
{
return QStringLiteral( "PostgreSQL database with PostGIS extension" );
}
QgsFeatureIterator QgsPostgresProvider::getFeatures( const QgsFeatureRequest &request ) const
{
if ( !mValid )
{
QgsMessageLog::logMessage( tr( "Read attempt on an invalid PostgreSQL data source" ), tr( "PostGIS" ) );
return QgsFeatureIterator();
}
QgsPostgresFeatureSource *featureSrc = static_cast<QgsPostgresFeatureSource *>( featureSource() );
return QgsFeatureIterator( new QgsPostgresFeatureIterator( featureSrc, true, request ) );
}
QString QgsPostgresProvider::pkParamWhereClause( int offset, const char *alias ) const
{
QString whereClause;
QString aliased;
if ( alias ) aliased = QStringLiteral( "%1." ).arg( alias );
switch ( mPrimaryKeyType )
{
case PktTid:
whereClause = QStringLiteral( "%2ctid=$%1" ).arg( offset ).arg( aliased );
break;
case PktOid:
whereClause = QStringLiteral( "%2oid=$%1" ).arg( offset ).arg( aliased );
break;
case PktInt:
case PktUint64:
Q_ASSERT( mPrimaryKeyAttrs.size() == 1 );
whereClause = QStringLiteral( "%3%1=$%2" ).arg( quotedIdentifier( field( mPrimaryKeyAttrs[0] ).name() ) ).arg( offset ).arg( aliased );
break;
case PktFidMap:
{
QString delim;
for ( int i = 0; i < mPrimaryKeyAttrs.size(); i++ )
{
int idx = mPrimaryKeyAttrs[i];
QgsField fld = field( idx );
whereClause += delim + QStringLiteral( "%3%1=$%2" ).arg( connectionRO()->fieldExpression( fld ) ).arg( offset++ ).arg( aliased );
delim = QStringLiteral( " AND " );
}
}
break;
case PktUnknown:
Q_ASSERT( !"FAILURE: Primary key unknown" );
whereClause = QStringLiteral( "NULL" );
break;
}
if ( !mSqlWhereClause.isEmpty() )
{
if ( !whereClause.isEmpty() )
whereClause += QLatin1String( " AND " );
whereClause += '(' + mSqlWhereClause + ')';
}
return whereClause;
}
void QgsPostgresProvider::appendPkParams( QgsFeatureId featureId, QStringList ¶ms ) const
{
switch ( mPrimaryKeyType )
{
case PktOid:
case PktUint64:
params << QString::number( featureId );
break;
case PktInt:
params << QString::number( FID2PKINT( featureId ) );
break;
case PktTid:
params << QStringLiteral( "'(%1,%2)'" ).arg( FID_TO_NUMBER( featureId ) >> 16 ).arg( FID_TO_NUMBER( featureId ) & 0xffff );
break;
case PktFidMap:
{
QVariantList pkVals = mShared->lookupKey( featureId );
if ( !pkVals.isEmpty() )
{
Q_ASSERT( pkVals.size() == mPrimaryKeyAttrs.size() );
}
for ( int i = 0; i < mPrimaryKeyAttrs.size(); i++ )
{
if ( i < pkVals.size() )
{
params << pkVals[i].toString();
}
else
{
QgsDebugMsg( QStringLiteral( "FAILURE: Key value %1 for feature %2 not found." ).arg( mPrimaryKeyAttrs[i] ).arg( featureId ) );
params << QStringLiteral( "NULL" );
}
}
QgsDebugMsg( QStringLiteral( "keys params: %1" ).arg( params.join( "; " ) ) );
}
break;
case PktUnknown:
Q_ASSERT( !"FAILURE: Primary key unknown" );
break;
}
}
QString QgsPostgresProvider::whereClause( QgsFeatureId featureId ) const
{
return QgsPostgresUtils::whereClause( featureId, mAttributeFields, connectionRO(), mPrimaryKeyType, mPrimaryKeyAttrs, mShared );
}
QString QgsPostgresUtils::whereClause( QgsFeatureId featureId, const QgsFields &fields, QgsPostgresConn *conn, QgsPostgresPrimaryKeyType pkType, const QList<int> &pkAttrs, const std::shared_ptr<QgsPostgresSharedData> &sharedData )
{
QString whereClause;
switch ( pkType )
{
case PktTid:
whereClause = QStringLiteral( "ctid='(%1,%2)'" )
.arg( FID_TO_NUMBER( featureId ) >> 16 )
.arg( FID_TO_NUMBER( featureId ) & 0xffff );
break;
case PktOid:
whereClause = QStringLiteral( "oid=%1" ).arg( featureId );
break;
case PktInt:
Q_ASSERT( pkAttrs.size() == 1 );
whereClause = QStringLiteral( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( FID2PKINT( featureId ) );
break;
case PktUint64:
Q_ASSERT( pkAttrs.size() == 1 );
whereClause = QStringLiteral( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( featureId );
break;
case PktFidMap:
{
QVariantList pkVals = sharedData->lookupKey( featureId );
if ( !pkVals.isEmpty() )
{
Q_ASSERT( pkVals.size() == pkAttrs.size() );
QString delim;
for ( int i = 0; i < pkAttrs.size(); i++ )
{
int idx = pkAttrs[i];
QgsField fld = fields.at( idx );
whereClause += delim + conn->fieldExpression( fld );
if ( pkVals[i].isNull() )
whereClause += QLatin1String( " IS NULL" );
else
whereClause += '=' + QgsPostgresConn::quotedValue( pkVals[i].toString() );
delim = QStringLiteral( " AND " );
}
}
else
{
QgsDebugMsg( QStringLiteral( "FAILURE: Key values for feature %1 not found." ).arg( featureId ) );
whereClause = QStringLiteral( "NULL" );
}
}
break;
case PktUnknown:
Q_ASSERT( !"FAILURE: Primary key unknown" );
whereClause = QStringLiteral( "NULL" );
break;
}
return whereClause;
}
QString QgsPostgresUtils::whereClause( const QgsFeatureIds &featureIds, const QgsFields &fields, QgsPostgresConn *conn, QgsPostgresPrimaryKeyType pkType, const QList<int> &pkAttrs, const std::shared_ptr<QgsPostgresSharedData> &sharedData )
{
switch ( pkType )
{
case PktOid:
case PktInt:
case PktUint64:
{
QString expr;
//simple primary key, so prefer to use an "IN (...)" query. These are much faster then multiple chained ...OR... clauses
if ( !featureIds.isEmpty() )
{
QString delim;
expr = QStringLiteral( "%1 IN (" ).arg( ( pkType == PktOid ? QStringLiteral( "oid" ) : QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ) );
const auto constFeatureIds = featureIds;
for ( const QgsFeatureId featureId : constFeatureIds )
{
expr += delim + FID_TO_STRING( ( pkType == PktOid ? featureId : pkType == PktUint64 ? featureId : FID2PKINT( featureId ) ) );
delim = ',';
}
expr += ')';
}
return expr;
}
case PktFidMap:
case PktTid:
case PktUnknown:
{
//complex primary key, need to build up where string
QStringList whereClauses;
const auto constFeatureIds = featureIds;
for ( const QgsFeatureId featureId : constFeatureIds )
{
whereClauses << whereClause( featureId, fields, conn, pkType, pkAttrs, sharedData );
}
return whereClauses.isEmpty() ? QString() : whereClauses.join( QStringLiteral( " OR " ) ).prepend( '(' ).append( ')' );
}
}
return QString(); //avoid warning
}
QString QgsPostgresUtils::andWhereClauses( const QString &c1, const QString &c2 )
{
if ( c1.isEmpty() )
return c2;
if ( c2.isEmpty() )
return c1;
return QStringLiteral( "(%1) AND (%2)" ).arg( c1, c2 );
}
QString QgsPostgresProvider::filterWhereClause() const
{
QString where;
QString delim = QStringLiteral( " WHERE " );
if ( !mSqlWhereClause.isEmpty() )
{
where += delim + '(' + mSqlWhereClause + ')';
delim = QStringLiteral( " AND " );
}
if ( !mRequestedSrid.isEmpty() && ( mRequestedSrid != mDetectedSrid || mRequestedSrid.toInt() == 0 ) )
{
where += delim + QStringLiteral( "%1(%2%3)=%4" )
.arg( connectionRO()->majorVersion() < 2 ? "srid" : "st_srid",
quotedIdentifier( mGeometryColumn ),
mSpatialColType == SctGeography ? "::geography" : "",
mRequestedSrid );
delim = QStringLiteral( " AND " );
}
if ( mRequestedGeomType != QgsWkbTypes::Unknown && mRequestedGeomType != mDetectedGeomType )
{
where += delim + QgsPostgresConn::postgisTypeFilter( mGeometryColumn, ( QgsWkbTypes::Type )mRequestedGeomType, mSpatialColType == SctGeography );
delim = QStringLiteral( " AND " );
}
return where;
}
void QgsPostgresProvider::setExtent( QgsRectangle &newExtent )
{
mLayerExtent.setXMaximum( newExtent.xMaximum() );
mLayerExtent.setXMinimum( newExtent.xMinimum() );
mLayerExtent.setYMaximum( newExtent.yMaximum() );
mLayerExtent.setYMinimum( newExtent.yMinimum() );
}
/**
* Returns the feature type
*/
QgsWkbTypes::Type QgsPostgresProvider::wkbType() const
{
return mRequestedGeomType != QgsWkbTypes::Unknown ? mRequestedGeomType : mDetectedGeomType;
}
QgsLayerMetadata QgsPostgresProvider::layerMetadata() const
{
return mLayerMetadata;
}
QgsField QgsPostgresProvider::field( int index ) const
{
if ( index < 0 || index >= mAttributeFields.count() )
{
QgsMessageLog::logMessage( tr( "FAILURE: Field %1 not found." ).arg( index ), tr( "PostGIS" ) );
throw PGFieldNotFound();
}
return mAttributeFields.at( index );
}
QgsFields QgsPostgresProvider::fields() const
{
return mAttributeFields;
}
QString QgsPostgresProvider::dataComment() const
{
return mDataComment;
}
//! \todo XXX Perhaps this should be promoted to QgsDataProvider?
QString QgsPostgresProvider::endianString()
{
switch ( QgsApplication::endian() )
{
case QgsApplication::NDR:
return QStringLiteral( "NDR" );
case QgsApplication::XDR:
return QStringLiteral( "XDR" );
default :
return QStringLiteral( "Unknown" );
}
}
struct PGTypeInfo
{
QString typeName;
QString typeType;
QString typeElem;
int typeLen;
};
bool QgsPostgresProvider::loadFields()
{
// Clear cached information about enum values support
mShared->clearSupportsEnumValuesCache();
if ( !mIsQuery )
{
QgsDebugMsg( QStringLiteral( "Loading fields for table %1" ).arg( mTableName ) );
// Get the relation oid for use in later queries
QString sql = QStringLiteral( "SELECT regclass(%1)::oid" ).arg( quotedValue( mQuery ) );
QgsPostgresResult tresult( connectionRO()->PQexec( sql ) );
QString tableoid = tresult.PQgetvalue( 0, 0 );
// Get the table description
sql = QStringLiteral( "SELECT description FROM pg_description WHERE objoid=%1 AND objsubid=0" ).arg( tableoid );
tresult = connectionRO()->PQexec( sql );
if ( tresult.PQntuples() > 0 )
{
mDataComment = tresult.PQgetvalue( 0, 0 );
mLayerMetadata.setAbstract( mDataComment );
}
}
// Populate the field vector for this layer. The field vector contains
// field name, type, length, and precision (if numeric)
QString sql = QStringLiteral( "SELECT * FROM %1 LIMIT 0" ).arg( mQuery );
QgsPostgresResult result( connectionRO()->PQexec( sql ) );
// Collect type info
sql = QStringLiteral( "SELECT oid,typname,typtype,typelem,typlen FROM pg_type" );
QgsPostgresResult typeResult( connectionRO()->PQexec( sql ) );
QMap<Oid, PGTypeInfo> typeMap;
for ( int i = 0; i < typeResult.PQntuples(); ++i )
{
PGTypeInfo typeInfo =
{
/* typeName = */ typeResult.PQgetvalue( i, 1 ),
/* typeType = */ typeResult.PQgetvalue( i, 2 ),
/* typeElem = */ typeResult.PQgetvalue( i, 3 ),
/* typeLen = */ typeResult.PQgetvalue( i, 4 ).toInt()
};
typeMap.insert( typeResult.PQgetvalue( i, 0 ).toUInt(), typeInfo );
}
QMap<Oid, QMap<int, QString> > fmtFieldTypeMap, descrMap, defValMap, identityMap;
QMap<Oid, QMap<int, Oid> > attTypeIdMap;
QMap<Oid, QMap<int, bool> > notNullMap, uniqueMap;
if ( result.PQnfields() > 0 )
{
// Collect table oids
QSet<Oid> tableoids;
for ( int i = 0; i < result.PQnfields(); i++ )
{
Oid tableoid = result.PQftable( i );
if ( tableoid > 0 )
{
tableoids.insert( tableoid );
}
}
if ( !tableoids.isEmpty() )
{
QStringList tableoidsList;
const auto constTableoids = tableoids;
for ( Oid tableoid : constTableoids )
{
tableoidsList.append( QString::number( tableoid ) );
}
QString tableoidsFilter = '(' + tableoidsList.join( QStringLiteral( "," ) ) + ')';
// Collect formatted field types
sql = QStringLiteral(
"SELECT attrelid, attnum, pg_catalog.format_type(atttypid,atttypmod), pg_catalog.col_description(attrelid,attnum), pg_catalog.pg_get_expr(adbin,adrelid), atttypid, attnotnull::int, indisunique::int%1"
" FROM pg_attribute"
" LEFT OUTER JOIN pg_attrdef ON attrelid=adrelid AND attnum=adnum"
// find unique constraints if present. Text cast required to handle int2vector comparison. Distinct required as multiple unique constraints may exist
" LEFT OUTER JOIN ( SELECT DISTINCT indrelid, indkey, indisunique FROM pg_index WHERE indisunique ) uniq ON attrelid=indrelid AND attnum::text=indkey::text "
" WHERE attrelid IN %2"
).arg( connectionRO()->pgVersion() >= 100000 ? QStringLiteral( ", attidentity" ) : QString() ).arg( tableoidsFilter );
QgsPostgresResult fmtFieldTypeResult( connectionRO()->PQexec( sql ) );
for ( int i = 0; i < fmtFieldTypeResult.PQntuples(); ++i )
{
Oid attrelid = fmtFieldTypeResult.PQgetvalue( i, 0 ).toUInt();
int attnum = fmtFieldTypeResult.PQgetvalue( i, 1 ).toInt(); // Int2
QString formatType = fmtFieldTypeResult.PQgetvalue( i, 2 );
QString descr = fmtFieldTypeResult.PQgetvalue( i, 3 );
QString defVal = fmtFieldTypeResult.PQgetvalue( i, 4 );
Oid attType = fmtFieldTypeResult.PQgetvalue( i, 5 ).toUInt();
bool attNotNull = fmtFieldTypeResult.PQgetvalue( i, 6 ).toInt();
bool uniqueConstraint = fmtFieldTypeResult.PQgetvalue( i, 7 ).toInt();
QString attIdentity = connectionRO()->pgVersion() >= 100000 ? fmtFieldTypeResult.PQgetvalue( i, 8 ) : " ";
fmtFieldTypeMap[attrelid][attnum] = formatType;
descrMap[attrelid][attnum] = descr;
defValMap[attrelid][attnum] = defVal;
attTypeIdMap[attrelid][attnum] = attType;
notNullMap[attrelid][attnum] = attNotNull;
uniqueMap[attrelid][attnum] = uniqueConstraint;
identityMap[attrelid][attnum] = attIdentity.isEmpty() ? " " : attIdentity;
}
}
}
QSet<QString> fields;
mAttributeFields.clear();
mIdentityFields.clear();
for ( int i = 0; i < result.PQnfields(); i++ )
{
QString fieldName = result.PQfname( i );
if ( fieldName == mGeometryColumn )
continue;
Oid fldtyp = result.PQftype( i );
int fldMod = result.PQfmod( i );
int fieldPrec = -1;
Oid tableoid = result.PQftable( i );
int attnum = result.PQftablecol( i );
Oid atttypid = attTypeIdMap[tableoid][attnum];
const PGTypeInfo &typeInfo = typeMap.value( fldtyp );
QString fieldTypeName = typeInfo.typeName;
QString fieldTType = typeInfo.typeType;
int fieldSize = typeInfo.typeLen;
bool isDomain = ( typeMap.value( atttypid ).typeType == QLatin1String( "d" ) );
QString formattedFieldType = fmtFieldTypeMap[tableoid][attnum];
QString originalFormattedFieldType = formattedFieldType;
if ( isDomain )
{
// get correct formatted field type for domain
sql = QStringLiteral( "SELECT format_type(%1, %2)" ).arg( fldtyp ).arg( fldMod );
QgsPostgresResult fmtFieldModResult( connectionRO()->PQexec( sql ) );
if ( fmtFieldModResult.PQntuples() > 0 )
{
formattedFieldType = fmtFieldModResult.PQgetvalue( 0, 0 );
}
}
QString fieldComment = descrMap[tableoid][attnum];
QVariant::Type fieldType;
QVariant::Type fieldSubType = QVariant::Invalid;
if ( fieldTType == QLatin1String( "b" ) )
{
bool isArray = fieldTypeName.startsWith( '_' );
if ( isArray )
fieldTypeName = fieldTypeName.mid( 1 );
if ( fieldTypeName == QLatin1String( "int8" ) || fieldTypeName == QLatin1String( "serial8" ) )
{
fieldType = QVariant::LongLong;
fieldSize = -1;
fieldPrec = 0;
}
else if ( fieldTypeName == QLatin1String( "int2" ) || fieldTypeName == QLatin1String( "int4" ) ||
fieldTypeName == QLatin1String( "oid" ) || fieldTypeName == QLatin1String( "serial" ) )
{
fieldType = QVariant::Int;
fieldSize = -1;
fieldPrec = 0;
}
else if ( fieldTypeName == QLatin1String( "real" ) || fieldTypeName == QLatin1String( "double precision" ) ||
fieldTypeName == QLatin1String( "float4" ) || fieldTypeName == QLatin1String( "float8" ) )
{
fieldType = QVariant::Double;
fieldSize = -1;
fieldPrec = -1;
}
else if ( fieldTypeName == QLatin1String( "numeric" ) )
{
fieldType = QVariant::Double;
if ( formattedFieldType == QLatin1String( "numeric" ) || formattedFieldType.isEmpty() )
{
fieldSize = -1;
fieldPrec = -1;
}
else
{
QRegExp re( "numeric\\((\\d+),(\\d+)\\)" );
if ( re.exactMatch( formattedFieldType ) )
{
fieldSize = re.cap( 1 ).toInt();
fieldPrec = re.cap( 2 ).toInt();
}
else if ( formattedFieldType != QLatin1String( "numeric" ) )
{
QgsMessageLog::logMessage( tr( "Unexpected formatted field type '%1' for field %2" )
.arg( formattedFieldType,
fieldName ),
tr( "PostGIS" ) );
fieldSize = -1;
fieldPrec = -1;
}
}
}
else if ( fieldTypeName == QLatin1String( "varchar" ) )
{
fieldType = QVariant::String;
QRegExp re( "character varying\\((\\d+)\\)" );
if ( re.exactMatch( formattedFieldType ) )
{
fieldSize = re.cap( 1 ).toInt();
}
else
{
fieldSize = -1;
}
}
else if ( fieldTypeName == QLatin1String( "date" ) )
{
fieldType = QVariant::Date;
fieldSize = -1;
}
else if ( fieldTypeName == QLatin1String( "time" ) )
{
fieldType = QVariant::Time;
fieldSize = -1;
}
else if ( fieldTypeName == QLatin1String( "timestamp" ) )
{
fieldType = QVariant::DateTime;
fieldSize = -1;
}
else if ( fieldTypeName == QLatin1String( "bytea" ) )
{
fieldType = QVariant::ByteArray;
fieldSize = -1;
}
else if ( fieldTypeName == QLatin1String( "text" ) ||
fieldTypeName == QLatin1String( "citext" ) ||
fieldTypeName == QLatin1String( "geometry" ) ||
fieldTypeName == QLatin1String( "inet" ) ||
fieldTypeName == QLatin1String( "money" ) ||
fieldTypeName == QLatin1String( "ltree" ) ||
fieldTypeName == QLatin1String( "uuid" ) ||
fieldTypeName == QLatin1String( "xml" ) ||
fieldTypeName.startsWith( QLatin1String( "time" ) ) ||
fieldTypeName.startsWith( QLatin1String( "date" ) ) )
{
fieldType = QVariant::String;
fieldSize = -1;
}
else if ( fieldTypeName == QLatin1String( "bpchar" ) )
{