/
qgspostgresprovider.cpp
2788 lines (2326 loc) · 83.4 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. *
* *
***************************************************************************/
/* $Id$ */
// for htonl
#ifdef WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#endif
#include <cassert>
#include <qgis.h>
#include <qgsapplication.h>
#include <qgsfeature.h>
#include <qgsfield.h>
#include <qgsgeometry.h>
#include <qgsmessageoutput.h>
#include <qgsrect.h>
#include <qgscoordinatereferencesystem.h>
#include "qgsprovidercountcalcevent.h"
#include "qgsproviderextentcalcevent.h"
#include "qgspostgresprovider.h"
#include "qgspostgrescountthread.h"
#include "qgspostgresextentthread.h"
#include "qgspostgisbox3d.h"
#include "qgslogger.h"
#include "qgslogger.h"
const QString POSTGRES_KEY = "postgres";
const QString POSTGRES_DESCRIPTION = "PostgreSQL/PostGIS data provider";
QMap<QString, QgsPostgresProvider::Conn *> QgsPostgresProvider::Conn::connectionsRO;
QMap<QString, QgsPostgresProvider::Conn *> QgsPostgresProvider::Conn::connectionsRW;
int QgsPostgresProvider::providerIds = 0;
QgsPostgresProvider::QgsPostgresProvider( QString const & uri )
: QgsVectorDataProvider( uri ),
mFetching( false ),
geomType( QGis::WKBUnknown ),
mFeatureQueueSize( 200 )
{
// assume this is a valid layer until we determine otherwise
valid = true;
providerId = providerIds++;
QgsDebugMsg( "Postgresql Layer Creation" );
QgsDebugMsg( "URI: " + uri );
mUri = QgsDataSourceURI( uri );
/* populate members from the uri structure */
mSchemaName = mUri.schema();
mTableName = mUri.table();
geometryColumn = mUri.geometryColumn();
sqlWhereClause = mUri.sql();
// Keep a schema qualified table name for convenience later on.
mSchemaTableName = mUri.quotedTablename();
QgsDebugMsg( "Table name is " + mTableName );
QgsDebugMsg( "SQL is " + sqlWhereClause );
QgsDebugMsg( "Connection info is " + mUri.connInfo() );
QgsDebugMsg( "Geometry column is: " + geometryColumn );
QgsDebugMsg( "Schema is: " + mSchemaName );
QgsDebugMsg( "Table name is: " + mTableName );
connectionRW = NULL;
connectionRO = Conn::connectDb( mUri.connInfo(), true );
if ( connectionRO == NULL )
{
valid = false;
return;
}
QgsDebugMsg( "Checking for permissions on the relation" );
// Check that we can read from the table (i.e., we have
// select permission).
QString sql = QString( "select * from %1 limit 1" ).arg( mSchemaTableName );
Result testAccess = connectionRO->PQexec( sql );
if ( PQresultStatus( testAccess ) != PGRES_TUPLES_OK )
{
showMessageBox( tr( "Unable to access relation" ),
tr( "Unable to access the " ) + mSchemaTableName +
tr( " relation.\nThe error message from the database was:\n" ) +
QString::fromUtf8( PQresultErrorMessage( testAccess ) ) + ".\n" +
"SQL: " + sql );
valid = false;
disconnectDb();
return;
}
sql = QString( "SELECT "
"has_table_privilege(%1,'DELETE'),"
"has_table_privilege(%1,'UPDATE'),"
"has_table_privilege(%1,'INSERT'),"
"current_schema()" )
.arg( quotedValue( mSchemaTableName ) );
testAccess = connectionRO->PQexec( sql );
if ( PQresultStatus( testAccess ) != PGRES_TUPLES_OK )
{
showMessageBox( tr( "Unable to access relation" ),
tr( "Unable to determine table access privileges for the " ) + mSchemaTableName +
tr( " relation.\nThe error message from the database was:\n" ) +
QString::fromUtf8( PQresultErrorMessage( testAccess ) ) + ".\n" +
"SQL: " + sql );
valid = false;
disconnectDb();
return;
}
enabledCapabilities = QgsVectorDataProvider::SelectGeometryAtId;
if ( QString::fromUtf8( PQgetvalue( testAccess, 0, 0 ) ) == "t" )
{
// DELETE
enabledCapabilities |= QgsVectorDataProvider::DeleteFeatures;
}
if ( QString::fromUtf8( PQgetvalue( testAccess, 0, 1 ) ) == "t" )
{
// UPDATE
enabledCapabilities |= QgsVectorDataProvider::ChangeGeometries | QgsVectorDataProvider::ChangeAttributeValues;
}
if ( QString::fromUtf8( PQgetvalue( testAccess, 0, 2 ) ) == "t" )
{
// INSERT
enabledCapabilities |= QgsVectorDataProvider::AddFeatures;
}
mCurrentSchema = QString::fromUtf8( PQgetvalue( testAccess, 0, 3 ) );
if ( mCurrentSchema == mSchemaName )
{
mUri.clearSchema();
setDataSourceUri( mUri.uri() );
}
if ( mSchemaName == "" )
mSchemaName = mCurrentSchema;
sql = QString( "SELECT 1 FROM pg_class,pg_namespace WHERE "
"pg_class.relnamespace=pg_namespace.oid AND "
"pg_get_userbyid(relowner)=current_user AND "
"relname=%1 AND nspname=%2" )
.arg( quotedValue( mTableName ) )
.arg( quotedValue( mSchemaName ) );
testAccess = connectionRO->PQexec( sql );
if ( PQresultStatus( testAccess ) == PGRES_TUPLES_OK && PQntuples( testAccess ) == 1 )
{
enabledCapabilities |= QgsVectorDataProvider::AddAttributes | QgsVectorDataProvider::DeleteAttributes;
}
if ( !getGeometryDetails() ) // gets srid and geometry type
{
// the table is not a geometry table
numberFeatures = 0;
valid = false;
QgsDebugMsg( "Invalid Postgres layer" );
disconnectDb();
return;
}
deduceEndian();
calculateExtents();
getFeatureCount();
// load the field list
loadFields();
// set the primary key
getPrimaryKey();
// Set the postgresql message level so that we don't get the
// 'there is no transaction in progress' warning.
#ifndef QGISDEBUG
connectionRO->PQexecNR( "set client_min_messages to error" );
#endif
// Kick off the long running threads
#ifdef POSTGRESQL_THREADS
QgsDebugMsg( "About to touch mExtentThread" );
mExtentThread.setConnInfo( mUri.connInfo );
mExtentThread.setTableName( mTableName );
mExtentThread.setSqlWhereClause( sqlWhereClause );
mExtentThread.setGeometryColumn( geometryColumn );
mExtentThread.setCallback( this );
QgsDebugMsg( "About to start mExtentThread" );
mExtentThread.start();
QgsDebugMsg( "Main thread just dispatched mExtentThread" );
QgsDebugMsg( "About to touch mCountThread" );
mCountThread.setConnInfo( mUri.connInfo );
mCountThread.setTableName( mTableName );
mCountThread.setSqlWhereClause( sqlWhereClause );
mCountThread.setGeometryColumn( geometryColumn );
mCountThread.setCallback( this );
QgsDebugMsg( "About to start mCountThread" );
mCountThread.start();
QgsDebugMsg( "Main thread just dispatched mCountThread" );
#endif
//fill type names into sets
mSupportedNativeTypes.insert( "double precision", QVariant::Double );
mSupportedNativeTypes.insert( "int4", QVariant::Int );
mSupportedNativeTypes.insert( "int8", QVariant::LongLong );
mSupportedNativeTypes.insert( "text", QVariant::String );
mSupportedNativeTypes.insert( "varchar(30)", QVariant::String );
if ( primaryKey.isEmpty() )
{
valid = false;
}
// Close the database connection if the layer isn't going to be loaded.
if ( !valid )
disconnectDb();
}
QgsPostgresProvider::~QgsPostgresProvider()
{
#ifdef POSTGRESQL_THREADS
QgsDebugMsg( "About to wait for mExtentThread" );
mExtentThread.wait();
QgsDebugMsg( "Finished waiting for mExtentThread" );
QgsDebugMsg( "About to wait for mCountThread" );
mCountThread.wait();
QgsDebugMsg( "Finished waiting for mCountThread" );
// Make sure all events from threads have been processed
// (otherwise they will get destroyed prematurely)
QApplication::sendPostedEvents( this, QGis::ProviderExtentCalcEvent );
QApplication::sendPostedEvents( this, QGis::ProviderCountCalcEvent );
#endif
disconnectDb();
QgsDebugMsg( "deconstructing." );
//pLog.flush();
}
QgsPostgresProvider::Conn *QgsPostgresProvider::Conn::connectDb( const QString & conninfo, bool readonly )
{
QMap<QString, QgsPostgresProvider::Conn *> &connections =
readonly ? QgsPostgresProvider::Conn::connectionsRO : QgsPostgresProvider::Conn::connectionsRW;
if ( connections.contains( conninfo ) )
{
QgsDebugMsg( QString( "Using cached connection for %1" ).arg( conninfo ) );
connections[conninfo]->ref++;
return connections[conninfo];
}
QgsDebugMsg( QString( "New postgres connection for " ) + conninfo );
PGconn *pd = PQconnectdb( conninfo.toLocal8Bit() ); // use what is set based on locale; after connecting, use Utf8
// check the connection status
if ( PQstatus( pd ) != CONNECTION_OK )
{
QgsDebugMsg( "Connection to database failed" );
return NULL;
}
//set client encoding to unicode because QString uses UTF-8 anyway
QgsDebugMsg( "setting client encoding to UNICODE" );
int errcode = PQsetClientEncoding( pd, QString( "UNICODE" ).toLocal8Bit() );
if ( errcode == 0 )
{
QgsDebugMsg( "encoding successfully set" );
}
else if ( errcode == -1 )
{
QgsDebugMsg( "error in setting encoding" );
}
else
{
QgsDebugMsg( "undefined return value from encoding setting" );
}
QgsDebugMsg( "Connection to the database was successful" );
Conn *conn = new Conn( pd );
connections.insert( conninfo, conn );
/* Check to see if we have GEOS support and if not, warn the user about
the problems they will see :) */
QgsDebugMsg( "Checking for GEOS support" );
if ( !conn->hasGEOS() )
{
showMessageBox( tr( "No GEOS Support!" ),
tr( "Your PostGIS installation has no GEOS support.\n"
"Feature selection and identification will not "
"work properly.\nPlease install PostGIS with "
"GEOS support (http://geos.refractions.net)" ) );
}
return conn;
}
void QgsPostgresProvider::disconnectDb()
{
if ( mFetching )
{
connectionRO->closeCursor( QString( "qgisf%1" ).arg( providerId ) );
mFetching = false;
}
if ( connectionRO )
{
Conn::disconnectRO( connectionRO );
}
if ( connectionRW )
{
Conn::disconnectRW( connectionRW );
}
}
void QgsPostgresProvider::Conn::disconnectRW( Conn *&connection )
{
disconnect( connectionsRW, connection );
}
void QgsPostgresProvider::Conn::disconnectRO( Conn *&connection )
{
disconnect( connectionsRO, connection );
}
void QgsPostgresProvider::Conn::disconnect( QMap<QString, Conn *>& connections, Conn *&conn )
{
QMap<QString, Conn *>::iterator i;
for ( i = connections.begin(); i != connections.end() && i.value() != conn; i++ )
;
assert( i.value() == conn );
assert( i.value()->ref > 0 );
if ( --i.value()->ref == 0 )
{
i.value()->PQfinish();
delete i.value();
connections.remove( i.key() );
}
conn = NULL;
}
QString QgsPostgresProvider::storageType() const
{
return "PostgreSQL database with PostGIS extension";
}
bool QgsPostgresProvider::declareCursor(
const QString &cursorName,
const QgsAttributeList &fetchAttributes,
bool fetchGeometry,
QString whereClause )
{
try
{
QString query = QString( "select %1" ).arg( quotedIdentifier( primaryKey ) );
if ( fetchGeometry )
{
query += QString( ",asbinary(%1,'%2')" )
.arg( quotedIdentifier( geometryColumn ) )
.arg( endianString() );
}
for ( QgsAttributeList::const_iterator it = fetchAttributes.constBegin(); it != fetchAttributes.constEnd(); ++it )
{
const QgsField &fld = field( *it );
const QString &fieldname = fld.name();
if ( fieldname == primaryKey )
continue;
const QString &type = fld.typeName();
if ( type == "money" )
{
query += QString( ",cash_out(%1)" ).arg( quotedIdentifier( fieldname ) );
}
else if ( type.startsWith( "_" ) )
{
query += QString( ",array_out(%1)" ).arg( quotedIdentifier( fieldname ) );
}
else if ( type == "bool" )
{
query += QString( ",boolout(%1)" ).arg( quotedIdentifier( fieldname ) );
}
else
{
query += "," + quotedIdentifier( fieldname ) + "::text";
}
}
query += " from " + mSchemaTableName;
if ( !whereClause.isEmpty() )
query += QString( " where %1" ).arg( whereClause );
return connectionRO->openCursor( cursorName, query );
}
catch ( PGFieldNotFound )
{
return false;
}
}
bool QgsPostgresProvider::getFeature( PGresult *queryResult, int row, bool fetchGeometry,
QgsFeature &feature,
const QgsAttributeList &fetchAttributes )
{
try
{
int oid = *( int * )PQgetvalue( queryResult, row, 0 );
if ( swapEndian )
oid = ntohl( oid ); // convert oid to opposite endian
feature.setFeatureId( oid );
int col; // first attribute column after geometry
if ( fetchGeometry )
{
int returnedLength = PQgetlength( queryResult, row, 1 );
if ( returnedLength > 0 )
{
unsigned char *featureGeom = new unsigned char[returnedLength + 1];
memset( featureGeom, '\0', returnedLength + 1 );
memcpy( featureGeom, PQgetvalue( queryResult, row, 1 ), returnedLength );
feature.setGeometryAndOwnership( featureGeom, returnedLength + 1 );
}
else
{
feature.setGeometryAndOwnership( 0, 0 );
QgsDebugMsg( "Couldn't get the feature geometry in binary form" );
}
col = 2;
}
else
{
col = 1;
}
// iterate attributes
for ( QgsAttributeList::const_iterator it = fetchAttributes.constBegin(); it != fetchAttributes.constEnd(); it++ )
{
const QgsField &fld = field( *it );
if ( fld.name() == primaryKey )
{
// primary key was already processed
feature.addAttribute( *it, QString::number( oid ) );
continue;
}
if ( !PQgetisnull( queryResult, row, col ) )
{
feature.addAttribute( *it, convertValue( fld.type(), QString::fromUtf8( PQgetvalue( queryResult, row, col ) ) ) );
}
else
{
feature.addAttribute( *it, QVariant( QString::null ) );
}
col++;
}
return true;
}
catch ( PGFieldNotFound )
{
return false;
}
}
void QgsPostgresProvider::select( QgsAttributeList fetchAttributes, QgsRect rect, bool fetchGeometry, bool useIntersect )
{
QString cursorName = QString( "qgisf%1" ).arg( providerId );
if ( mFetching )
{
connectionRO->closeCursor( cursorName );
mFetching = false;
while ( !mFeatureQueue.empty() )
{
mFeatureQueue.pop();
}
}
QString whereClause;
if ( !rect.isEmpty() )
{
if ( useIntersect )
{
// Contributed by #qgis irc "creeping"
// This version actually invokes PostGIS's use of spatial indexes
whereClause = QString( "%1 && setsrid('BOX3D(%2)'::box3d,%3) and intersects(%1,setsrid('BOX3D(%2)'::box3d,%3))" )
.arg( quotedIdentifier( geometryColumn ) )
.arg( rect.asWktCoordinates() )
.arg( srid );
}
else
{
whereClause = QString( "%1 && setsrid('BOX3D(%2)'::box3d,%3)" )
.arg( quotedIdentifier( geometryColumn ) )
.arg( rect.asWktCoordinates() )
.arg( srid );
}
}
if ( !sqlWhereClause.isEmpty() )
{
if ( !whereClause.isEmpty() )
whereClause += " and ";
whereClause += "(" + sqlWhereClause + ")";
}
mFetchGeom = fetchGeometry;
mAttributesToFetch = fetchAttributes;
if ( !declareCursor( cursorName, fetchAttributes, fetchGeometry, whereClause ) )
return;
mFetching = true;
}
bool QgsPostgresProvider::nextFeature( QgsFeature& feature )
{
QString cursorName = QString( "qgisf%1" ).arg( providerId );
if ( !valid )
{
QgsDebugMsg( "Read attempt on an invalid postgresql data source" );
return false;
}
if ( mFeatureQueue.empty() )
{
QString fetch = QString( "fetch forward %1 from %2" ).arg( mFeatureQueueSize ).arg( cursorName );
if ( connectionRO->PQsendQuery( fetch ) == 0 ) // fetch features asynchronously
{
qWarning( "PQsendQuery failed (1)" );
}
Result queryResult;
while (( queryResult = connectionRO->PQgetResult() ) )
{
int rows = PQntuples( queryResult );
if ( rows == 0 )
continue;
for ( int row = 0; row < rows; row++ )
{
mFeatureQueue.push( QgsFeature() );
getFeature( queryResult, row, mFetchGeom, mFeatureQueue.back(), mAttributesToFetch );
} // for each row in queue
}
}
if ( mFeatureQueue.empty() )
{
QgsDebugMsg( "End of features" );
connectionRO->closeCursor( cursorName );
mFetching = false;
return false;
}
// Now return the next feature from the queue
if ( mFetchGeom )
{
QgsGeometry* featureGeom = mFeatureQueue.front().geometryAndOwnership();
feature.setGeometry( featureGeom );
}
else
{
feature.setGeometryAndOwnership( 0, 0 );
}
feature.setFeatureId( mFeatureQueue.front().featureId() );
feature.setAttributeMap( mFeatureQueue.front().attributeMap() );
mFeatureQueue.pop();
return true;
}
bool QgsPostgresProvider::featureAtId( int featureId, QgsFeature& feature, bool fetchGeometry, QgsAttributeList fetchAttributes )
{
QString cursorName = QString( "qgisfid%1" ).arg( providerId );
if ( !declareCursor( cursorName, fetchAttributes, fetchGeometry, QString( "%2=%3" ).arg( quotedIdentifier( primaryKey ) ).arg( featureId ) ) )
return false;
Result queryResult = connectionRO->PQexec( QString( "fetch forward 1 from %1" ).arg( cursorName ) );
if ( queryResult == 0 )
return false;
int rows = PQntuples( queryResult );
if ( rows == 0 )
{
QgsDebugMsg( "feature " + QString::number( featureId ) + " not found" );
connectionRO->closeCursor( cursorName );
return false;
}
else if ( rows != 1 )
{
QgsDebugMsg( QString( "found %1 features instead of just one." ).arg( rows ) );
}
bool gotit = getFeature( queryResult, 0, fetchGeometry, feature, fetchAttributes );
connectionRO->closeCursor( cursorName );
return gotit;
}
QgsDataSourceURI& QgsPostgresProvider::getURI()
{
return mUri;
}
void QgsPostgresProvider::setExtent( QgsRect& newExtent )
{
layerExtent.setXMaximum( newExtent.xMax() );
layerExtent.setXMinimum( newExtent.xMin() );
layerExtent.setYMaximum( newExtent.yMax() );
layerExtent.setYMinimum( newExtent.yMin() );
}
// TODO - make this function return the real extent_
QgsRect QgsPostgresProvider::extent()
{
return layerExtent; //extent_->MinX, extent_->MinY, extent_->MaxX, extent_->MaxY);
}
/**
* Return the feature type
*/
QGis::WkbType QgsPostgresProvider::geometryType() const
{
return geomType;
}
/**
* Return the feature type
*/
long QgsPostgresProvider::featureCount() const
{
return numberFeatures;
}
const QgsField &QgsPostgresProvider::field( int index ) const
{
QgsFieldMap::const_iterator it = attributeFields.find( index );
if ( it == attributeFields.constEnd() )
{
QgsDebugMsg( "Field " + QString::number( index ) + " not found." );
throw PGFieldNotFound();
}
return it.value();
}
/**
* Return the number of fields
*/
uint QgsPostgresProvider::fieldCount() const
{
return attributeFields.size();
}
const QgsFieldMap & QgsPostgresProvider::fields() const
{
return attributeFields;
}
QString QgsPostgresProvider::dataComment() const
{
return mDataComment;
}
void QgsPostgresProvider::begin()
{
if ( mFetching )
{
//move cursor to first record
connectionRO->PQexecNR( QString( "move 0 in qgisf%1" ).arg( providerId ) );
}
mFeatureQueue.empty();
loadFields();
}
/** @todo XXX Perhaps this should be promoted to QgsDataProvider? */
QString QgsPostgresProvider::endianString()
{
switch ( QgsApplication::endian() )
{
case QgsApplication::NDR:
return QString( "NDR" );
break;
case QgsApplication::XDR:
return QString( "XDR" );
break;
default :
return QString( "Unknown" );
}
}
void QgsPostgresProvider::loadFields()
{
QgsDebugMsg( "Loading fields for table " + mTableName );
// Get the relation oid for use in later queries
QString sql = QString( "SELECT regclass(%1)::oid" ).arg( quotedValue( mSchemaTableName ) );
Result tresult = connectionRO->PQexec( sql );
QString tableoid = QString::fromUtf8( PQgetvalue( tresult, 0, 0 ) );
// Get the table description
sql = QString( "SELECT description FROM pg_description WHERE objoid=%1 AND objsubid=0" ).arg( tableoid );
tresult = connectionRO->PQexec( sql );
if ( PQntuples( tresult ) > 0 )
mDataComment = QString::fromUtf8( PQgetvalue( tresult, 0, 0 ) );
// Populate the field vector for this layer. The field vector contains
// field name, type, length, and precision (if numeric)
sql = QString( "select * from %1 limit 0" ).arg( mSchemaTableName );
Result result = connectionRO->PQexec( sql );
// The queries inside this loop could possibly be combined into one
// single query - this would make the code run faster.
attributeFields.clear();
for ( int i = 0; i < PQnfields( result ); i++ )
{
QString fieldName = QString::fromUtf8( PQfname( result, i ) );
int fldtyp = PQftype( result, i );
QString typOid = QString().setNum( fldtyp );
int fieldModifier = PQfmod( result, i );
QString fieldComment( "" );
sql = QString( "SELECT typname,typtype,typelem,typlen FROM pg_type WHERE oid=%1" ).arg( typOid );
// just oid; needs more work to support array type
// "oid = (SELECT Distinct typelem FROM pg_type WHERE " //needs DISTINCT to guard against 2 or more rows on int2
// "typelem = " + typOid + " AND typlen = -1)";
Result oidResult = connectionRO->PQexec( sql );
QString fieldTypeName = QString::fromUtf8( PQgetvalue( oidResult, 0, 0 ) );
QString fieldTType = QString::fromUtf8( PQgetvalue( oidResult, 0, 1 ) );
QString fieldElem = QString::fromUtf8( PQgetvalue( oidResult, 0, 2 ) );
QString fieldSize = QString::fromUtf8( PQgetvalue( oidResult, 0, 3 ) );
sql = QString( "SELECT attnum FROM pg_attribute WHERE attrelid=%1 AND attname=%2" )
.arg( tableoid ).arg( quotedValue( fieldName ) );
Result tresult = connectionRO->PQexec( sql );
QString attnum = QString::fromUtf8( PQgetvalue( tresult, 0, 0 ) );
sql = QString( "SELECT description FROM pg_description WHERE objoid=%1 AND objsubid=%2" )
.arg( tableoid ).arg( attnum );
tresult = connectionRO->PQexec( sql );
if ( PQntuples( tresult ) > 0 )
fieldComment = QString::fromUtf8( PQgetvalue( tresult, 0, 0 ) );
if ( fieldName != geometryColumn )
{
QVariant::Type fieldType;
if ( fieldTType == "b" )
{
bool isArray = fieldTypeName.startsWith( "_" );
if ( isArray )
fieldTypeName = fieldTypeName.mid( 1 );
if ( fieldTypeName == "int8" )
fieldType = QVariant::LongLong;
else if ( fieldTypeName.startsWith( "int" ) || fieldTypeName == "serial" )
fieldType = QVariant::Int;
else if ( fieldTypeName == "real" || fieldTypeName == "double precision" || fieldTypeName.startsWith( "float" ) || fieldTypeName == "numeric" )
fieldType = QVariant::Double;
else if ( fieldTypeName == "text" ||
fieldTypeName == "char" ||
fieldTypeName == "bpchar" ||
fieldTypeName == "varchar" ||
fieldTypeName == "bool" ||
fieldTypeName == "money" ||
fieldTypeName.startsWith( "time" ) ||
fieldTypeName.startsWith( "date" ) )
fieldType = QVariant::String;
else
{
QgsDebugMsg( "Field " + fieldName + " ignored, because of unsupported type " + fieldTypeName );
continue;
}
if ( isArray )
{
fieldTypeName = "_" + fieldTypeName;
fieldType = QVariant::String;
}
}
else if ( fieldTType == "e" )
{
// enum
fieldType = QVariant::String;
}
else
{
QgsDebugMsg( "Field " + fieldName + " ignored, because of unsupported type type " + fieldTType );
continue;
}
attributeFields.insert( i, QgsField( fieldName, fieldType, fieldTypeName, fieldSize.toInt(), fieldModifier, fieldComment ) );
}
}
}
QString QgsPostgresProvider::getPrimaryKey()
{
// check to see if there is an unique index on the relation, which
// can be used as a key into the table. Primary keys are always
// unique indices, so we catch them as well.
QString sql = QString( "select indkey from pg_index where indisunique='t' and indrelid=regclass(%1)::oid" )
.arg( quotedValue( mSchemaTableName ) );
QgsDebugMsg( "Getting unique index using '" + sql + "'" );
Result pk = connectionRO->PQexec( sql );
QgsDebugMsg( "Got " + QString::number( PQntuples( pk ) ) + " rows." );
QStringList log;
// if we got no tuples we ain't got no unique index :)
if ( PQntuples( pk ) == 0 )
{
QgsDebugMsg( "Relation has no unique index -- investigating alternatives" );
// Two options here. If the relation is a table, see if there is
// an oid column that can be used instead.
// If the relation is a view try to find a suitable column to use as
// the primary key.
sql = QString( "SELECT relkind FROM pg_class WHERE oid=regclass(%1)::oid" )
.arg( quotedValue( mSchemaTableName ) );
Result tableType = connectionRO->PQexec( sql );
QString type = QString::fromUtf8( PQgetvalue( tableType, 0, 0 ) );
primaryKey = "";
if ( type == "r" ) // the relation is a table
{
QgsDebugMsg( "Relation is a table. Checking to see if it has an oid column." );
// If there is an oid on the table, use that instead,
// otherwise give up
sql = QString( "SELECT attname FROM pg_attribute WHERE attname='oid' AND attrelid=regclass(%1)" )
.arg( quotedValue( mSchemaTableName ) );
Result oidCheck = connectionRO->PQexec( sql );
if ( PQntuples( oidCheck ) != 0 )
{
// Could warn the user here that performance will suffer if
// oid isn't indexed (and that they may want to add a
// primary key to the table)
primaryKey = "oid";
primaryKeyType = "int4";
}
else
{
showMessageBox( tr( "No suitable key column in table" ),
tr( "The table has no column suitable for use as a key.\n\n"
"Qgis requires that the table either has a column of type\n"
"int4 with a unique constraint on it (which includes the\n"
"primary key) or has a PostgreSQL oid column.\n" ) );
}
}
else if ( type == "v" ) // the relation is a view
{
// Have a poke around the view to see if any of the columns
// could be used as the primary key.
tableCols cols;
// Given a schema.view, populate the cols variable with the
// schema.table.column's that underly the view columns.
findColumns( cols );
// From the view columns, choose one for which the underlying
// column is suitable for use as a key into the view.
primaryKey = chooseViewColumn( cols );
}
else
QgsDebugMsg( "Unexpected relation type of '" + type + "'." );
}
else // have some unique indices on the table. Now choose one...
{
// choose which (if more than one) unique index to use
std::vector<std::pair<QString, QString> > suitableKeyColumns;
for ( int i = 0; i < PQntuples( pk ); ++i )
{
QString col = QString::fromUtf8( PQgetvalue( pk, i, 0 ) );
QStringList columns = col.split( " ", QString::SkipEmptyParts );
if ( columns.count() == 1 )
{
// Get the column name and data type
sql = QString( "select attname,pg_type.typname from pg_attribute,pg_type where atttypid=pg_type.oid and attnum=%1 and attrelid=regclass(%2)" )
.arg( col ).arg( quotedValue( mSchemaTableName ) );
Result types = connectionRO->PQexec( sql );
if ( PQntuples( types ) > 0 )
{
QString columnName = QString::fromUtf8( PQgetvalue( types, 0, 0 ) );
QString columnType = QString::fromUtf8( PQgetvalue( types, 0, 1 ) );
if ( columnType != "int4" )
log.append( tr( "The unique index on column" ) +
" '" + columnName + "' " +
tr( "is unsuitable because Qgis does not currently support"
" non-int4 type columns as a key into the table.\n" ) );
else
suitableKeyColumns.push_back( std::make_pair( columnName, columnType ) );
}
else
{
//QgsDebugMsg( QString("name and type of %3. column of %1.%2 not found").arg(mSchemaName).arg(mTables).arg(col) );
}
}
else
{
sql = QString( "select attname from pg_attribute, pg_type where atttypid=pg_type.oid and attnum in (%1) and attrelid=regclass(%2)::oid" )
.arg( col.replace( " ", "," ) )
.arg( quotedValue( mSchemaTableName ) );
Result types = connectionRO->PQexec( sql );
QString colNames;
int numCols = PQntuples( types );
for ( int j = 0; j < numCols; ++j )
{
if ( j == numCols - 1 )
colNames += tr( "and " );
colNames += quotedValue( QString::fromUtf8( PQgetvalue( types, j, 0 ) ) );
if ( j < numCols - 2 )
colNames += ",";
}
log.append( tr( "The unique index based on columns " ) + colNames +
tr( " is unsuitable because Qgis does not currently support"
" multiple columns as a key into the table.\n" ) );
}
}
// suitableKeyColumns now contains the name of columns (and their
// data type) that
// are suitable for use as a key into the table. If there is
// more than one we need to choose one. For the moment, just
// choose the first in the list.