-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgspostgresprovider.cpp
2674 lines (2214 loc) · 79.3 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 <fstream>
#include <iostream>
#include <cassert>
#include <QStringList>
#include <QApplication>
#include <QEvent>
#include <QCustomEvent>
#include <QTextOStream>
#include <qgis.h>
#include <qgsapplication.h>
#include <qgsfeature.h>
#include <qgsfield.h>
#include <qgsgeometry.h>
#include <qgsmessageoutput.h>
#include <qgsrect.h>
#include <qgsspatialrefsys.h>
#include "qgsprovidercountcalcevent.h"
#include "qgsproviderextentcalcevent.h"
#include "qgspostgresprovider.h"
#include "qgspostgrescountthread.h"
#include "qgspostgresextentthread.h"
#include "qgspostgisbox3d.h"
#include "qgslogger.h"
#ifdef WIN32
#define QGISEXTERN extern "C" __declspec( dllexport )
#else
#define QGISEXTERN extern "C"
#endif
const QString POSTGRES_KEY = "postgres";
const QString POSTGRES_DESCRIPTION = "PostgreSQL/PostGIS data provider";
QgsPostgresProvider::QgsPostgresProvider(QString const & uri)
: QgsVectorDataProvider(uri),
geomType(QGis::WKBUnknown),
mFeatureQueueSize(200),
gotPostgisVersion(FALSE)
{
// assume this is a valid layer until we determine otherwise
valid = true;
/* OPEN LOG FILE */
// Make connection to the data source
// For postgres, the connection information is passed as a space delimited
// string:
// host=192.168.1.5 dbname=test port=5342 user=gsherman password=xxx table=tablename
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.
if (mSchemaName.length() > 0)
mSchemaTableName = "\"" + mSchemaName + "\".\"" + mTableName + "\"";
else
mSchemaTableName = "\"" + mTableName + "\"";
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);
//QString logFile = "./pg_provider_" + mTableName + ".log";
//pLog.open((const char *)logFile);
//QgsDebugMsg("Opened log file for " + mTableName);
connection = connectDb( (const char *)mUri.connInfo );
if( connection==NULL ) {
valid = false;
return;
}
QgsDebugMsg("Checking for select permission on the relation\n");
// Check that we can read from the table (i.e., we have
// select permission).
QString sql = "select * from " + mSchemaTableName + " limit 1";
PGresult* testAccess = PQexec(connection, (const char*)(sql.utf8()));
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(PQresultErrorMessage(testAccess)) + ".\n" +
"SQL: " + sql);
PQclear(testAccess);
valid = false;
disconnectDb();
return;
}
PQclear(testAccess);
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();
// Get the relation oid for use in later queries
sql = "SELECT oid FROM pg_class WHERE relname = '" + mTableName + "' AND relnamespace = ("
"SELECT oid FROM pg_namespace WHERE nspname = '" + mSchemaName + "')";
PGresult *tresult= PQexec(connection, (const char *)(sql.utf8()));
QString tableoid = PQgetvalue(tresult, 0, 0);
PQclear(tresult);
// Get the table description
sql = "SELECT description FROM pg_description WHERE "
"objoid = " + tableoid + " AND objsubid = 0";
tresult = PQexec(connection, (const char*) sql.utf8());
if (PQntuples(tresult) > 0)
mDataComment = PQgetvalue(tresult, 0, 0);
PQclear(tresult);
// Populate the field vector for this layer. The field vector contains
// field name, type, length, and precision (if numeric)
sql = "select * from " + mSchemaTableName + " limit 0";
PGresult *result = PQexec(connection, (const char *) (sql.utf8()));
//--std::cout << "Field: Name, Type, Size, Modifier:" << std::endl;
// The queries inside this loop could possibly be combined into one
// single query - this would make the code run faster.
for (int i = 0; i < PQnfields(result); i++)
{
QString fieldName = PQfname(result, i);
int fldtyp = PQftype(result, i);
QString typOid = QString().setNum(fldtyp);
int fieldModifier = PQfmod(result, i);
QString fieldComment("");
sql = "SELECT typname, typlen FROM pg_type WHERE "
"oid = (SELECT typelem FROM pg_type WHERE "
"typelem = " + typOid + " AND typlen = -1)";
PGresult* oidResult = PQexec(connection, (const char *) sql);
QString fieldTypeName = PQgetvalue(oidResult, 0, 0);
QString fieldSize = PQgetvalue(oidResult, 0, 1);
PQclear(oidResult);
sql = "SELECT attnum FROM pg_attribute WHERE "
"attrelid = " + tableoid + " AND attname = '" + fieldName + "'";
PGresult *tresult = PQexec(connection, (const char *)(sql.utf8()));
QString attnum = PQgetvalue(tresult, 0, 0);
PQclear(tresult);
sql = "SELECT description FROM pg_description WHERE "
"objoid = " + tableoid + " AND objsubid = " + attnum;
tresult = PQexec(connection, (const char*)(sql.utf8()));
if (PQntuples(tresult) > 0)
fieldComment = PQgetvalue(tresult, 0, 0);
PQclear(tresult);
QgsDebugMsg("Field: " + attnum + " maps to " + QString::number(i) + " " + fieldName + ", "
+ fieldTypeName + " (" + QString::number(fldtyp) + "), " + fieldSize + ", " + QString::number(fieldModifier));
if(fieldName!=geometryColumn)
{
QVariant::Type fieldType;
if (fieldTypeName.find("int") != -1 || fieldTypeName.find("serial") != -1)
fieldType = QVariant::Int;
else if (fieldTypeName == "real" || fieldTypeName == "double precision" || \
fieldTypeName.find("float") != -1)
fieldType = QVariant::Double;
else
fieldType = QVariant::String;
attributeFields.insert(i, QgsField(fieldName, fieldType, fieldTypeName, fieldSize.toInt(), fieldModifier, fieldComment));
}
}
PQclear(result);
// 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
PQexec(connection, "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
ready = false; // not ready to read yet cuz the cursor hasn't been created
//fill type names into sets
mSupportedNativeTypes.insert("double precision");
mSupportedNativeTypes.insert("int4");
mSupportedNativeTypes.insert("int8");
mSupportedNativeTypes.insert("text");
mSupportedNativeTypes.insert("varchar(30)");
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();
}
PGconn *QgsPostgresProvider::connectDb(const char *conninfo)
{
if( connections.contains(conninfo) )
{
QgsDebugMsg(QString("Using cached connection for ") + conninfo);
connections[conninfo]->ref++;
return connections[conninfo]->conn;
}
QgsDebugMsg(QString("New postgres connection for ") + conninfo);
PGconn *pd = PQconnectdb(conninfo);
// 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, "UNICODE");
if(errcode==0)
{
QgsDebugMsg("encoding successfully set");
}
else if(errcode==-1)
{
QgsDebugMsg("error in setting encoding");
}
else
{
QgsDebugMsg("undefined return value from encoding setting");
}
/* 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(!hasGEOS(pd))
{
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)"));
}
//--std::cout << "Connection to the database was successful\n";
Conn *conn = new Conn(pd);
connections.insert( conninfo, conn );
return pd;
}
void QgsPostgresProvider::disconnectDb()
{
QMapIterator <QString, Conn *> i(connections);
while( i.hasNext() )
{
i.next();
if( i.value()->conn == connection )
break;
}
assert( i.value()->conn==connection );
assert( i.value()->ref>0 );
if( --i.value()->ref==0 )
{
PQfinish( i.value()->conn );
delete (i.value());
connections.remove( i.key() );
}
}
QString QgsPostgresProvider::storageType()
{
return "PostgreSQL database with PostGIS extension";
}
bool QgsPostgresProvider::getNextFeature(QgsFeature& feature)
{
if (valid)
{
// Top up our queue if it is empty
if (mFeatureQueue.empty())
{
QString fetch = QString("fetch forward %1 from qgisf")
.arg(mFeatureQueueSize);
if(mFirstFetch)
{
if(PQsendQuery(connection, (const char *)fetch) == 0) //fetch features in asynchronously
{
qWarning("PQsendQuery failed (1)");
}
}
mFirstFetch = false;
queryResult = PQgetResult(connection);
PGresult* bla = PQgetResult(connection); //just to get the 0 pointer...
int rows = PQntuples(queryResult);
if (rows == 0)
{
QgsDebugMsg("End of features");
if (ready)
PQexec(connection, "end work");
ready = false;
return false;
}
for (int row = 0; row < rows; row++)
{
int oid = *(int *)PQgetvalue(queryResult, row, PQfnumber(queryResult,"\""+primaryKey+"\""));
// QgsDebugMsg("Primary key type is " + QString::number(primaryKeyType));
if (swapEndian)
oid = ntohl(oid); // convert oid to opposite endian
// set ID
feature.setFeatureId(oid);
// fetch attributes
std::list<QString>::const_iterator name_it = mFetchAttributeNames.begin();
QgsAttributeList::const_iterator index_it = mAttributesToFetch.constBegin();
for(; name_it != mFetchAttributeNames.end(); ++name_it, ++index_it)
{
QString name = *name_it; //just for the debugger
//int number = PQfnumber(queryResult,*name_it); //just for the debugger
char* attribute = PQgetvalue(queryResult, row, PQfnumber(queryResult,*name_it));
QString val = QString::fromUtf8(attribute);
switch (attributeFields[*index_it].type())
{
case QVariant::Int:
feature.addAttribute(*index_it, val.toInt());
break;
case QVariant::Double:
feature.addAttribute(*index_it, val.toDouble());
break;
case QVariant::String:
feature.addAttribute(*index_it, val);
break;
default:
assert(0 && "unsupported field type");
}
}
//fetch geometry
if (mFetchGeom)
{
int returnedLength = PQgetlength(queryResult, row, PQfnumber(queryResult,"qgs_feature_geometry"));
if(returnedLength > 0)
{
unsigned char *featureGeom = new unsigned char[returnedLength + 1];
memset(featureGeom, '\0', returnedLength + 1);
memcpy(featureGeom, PQgetvalue(queryResult, row, PQfnumber(queryResult,"qgs_feature_geometry")), returnedLength);
feature.setGeometryAndOwnership(featureGeom, returnedLength + 1);
}
else
{
QgsDebugMsg("Couldn't get the feature geometry in binary form");
}
}
//don't copy the geometry. Just pass a pointer instead
mFeatureQueue.push(QgsFeature());
mFeatureQueue.back().setGeometry(feature.geometryAndOwnership());
mFeatureQueue.back().setFeatureId(feature.featureId());
mFeatureQueue.back().setAttributeMap(feature.attributeMap());
} // for each row in queue
PQclear(queryResult);
if(PQsendQuery(connection, (const char *)fetch) == 0) //already fetch the next couple of features asynchronously
{
qWarning("PQsendQuery failed (2)");
}
} // if new queue is required
// Now return the next feature from the queue
//don't copy the geometry. Just pass a pointer instead
feature.setGeometry(mFeatureQueue.front().geometryAndOwnership());
feature.setFeatureId(mFeatureQueue.front().featureId());
feature.setAttributeMap(mFeatureQueue.front().attributeMap());
mFeatureQueue.pop();
}
else
{
QgsDebugMsg("Read attempt on an invalid postgresql data source");
return false;
}
return true;
}
void QgsPostgresProvider::select(QgsAttributeList fetchAttributes,
QgsRect rect,
bool fetchGeometry,
bool useIntersect)
{
mFetchGeom = fetchGeometry;
mAttributesToFetch = fetchAttributes;
mFetchAttributeNames.clear();
QgsFieldMap attributeMap = fields();
QgsFieldMap::const_iterator fieldIt;
for(QgsAttributeList::const_iterator it = mAttributesToFetch.constBegin(); \
it != mAttributesToFetch.constEnd(); ++it)
{
fieldIt = attributeMap.find(*it);
if(fieldIt != attributeMap.end())
{
mFetchAttributeNames.push_back(fieldIt.value().name());
}
}
QString declare = "declare qgisf binary cursor for select \"" + primaryKey + "\"";
if(fetchGeometry)
{
declare += QString(",asbinary(\"%1\",'%2') as qgs_feature_geometry").arg(geometryColumn).arg(endianString());
}
for(std::list<QString>::const_iterator it = mFetchAttributeNames.begin(); it != mFetchAttributeNames.end(); ++it)
{
declare += "," + *it + "::text";
}
declare += " ";
declare += QString("from %1").arg(mSchemaTableName);
QgsDebugMsg("Binary cursor: " + declare);
bool hasWhere = FALSE;
if(!rect.isEmpty())
{
if(useIntersect)
{
// Contributed by #qgis irc "creeping"
// This version actually invokes PostGIS's use of spatial indexes
declare += " where " + geometryColumn;
declare += " && setsrid('BOX3D(" + rect.asWKTCoords();
declare += ")'::box3d,";
declare += srid;
declare += ")";
declare += " and intersects(" + geometryColumn;
declare += ", setsrid('BOX3D(" + rect.asWKTCoords();
declare += ")'::box3d,";
declare += srid;
declare += "))";
}
else
{
declare += " where " + geometryColumn;
declare += " && setsrid('BOX3D(" + rect.asWKTCoords();
declare += ")'::box3d,";
declare += srid;
declare += ")";
}
hasWhere = TRUE;
}
if(sqlWhereClause.length() > 0)
{
if (hasWhere)
declare += " and ";
else
declare += " where ";
declare += "(" + sqlWhereClause + ")";
hasWhere = TRUE;
}
QgsDebugMsg("Selecting features using: " + declare);
// set up the cursor
if(ready){
PQexec(connection, "end work");
}
PQexec(connection,"begin work");
ready = true;
PQexec(connection, (const char *)(declare.utf8()));
mFeatureQueue.empty();
mFirstFetch = true;
}
bool QgsPostgresProvider::getFeatureAtId(int featureId,
QgsFeature& feature,
bool fetchGeometry,
QgsAttributeList fetchAttributes)
{
std::list<QString> attributeNames;
QgsFieldMap fldMap = fields();
QgsFieldMap::const_iterator fieldIt;
QgsAttributeList::const_iterator it;
std::list<QString>::const_iterator namesIt;
for (it = fetchAttributes.constBegin(); it != fetchAttributes.constEnd(); ++it)
{
fieldIt = fldMap.find(*it);
if(fieldIt != fldMap.end())
{
attributeNames.push_back(fieldIt.value().name());
}
}
QString sql = "declare qgisfid binary cursor for select \"" + primaryKey + "\"";
if(fetchGeometry)
{
sql += QString(",asbinary(\"%1\",'%2') as qgs_feature_geometry").arg(geometryColumn).arg(endianString());
}
for(namesIt = attributeNames.begin(); namesIt != attributeNames.end(); ++namesIt)
{
sql += "," + *namesIt + "::text";
}
sql += " " + QString("from %1").arg(mSchemaTableName);
sql += " where " + primaryKey + " = " + QString::number(featureId);
QgsDebugMsg("Selecting feature using: " + sql);
PQexec(connection,"begin work");
// execute query
PQexec(connection, (const char *)(sql.utf8()));
PGresult *res = PQexec(connection, "fetch forward 1 from qgisfid");
int rows = PQntuples(res);
if (rows == 0)
{
PQexec(connection, "end work");
QgsDebugMsg("feature " + QString::number(featureId) + " not found");
return FALSE;
}
// set ID
int oid = *(int *)PQgetvalue(res, 0, PQfnumber(res,"\""+primaryKey+"\""));
if (swapEndian)
oid = ntohl(oid); // convert oid to opposite endian
feature.setFeatureId(oid);
// fetch attributes
it = fetchAttributes.constBegin();
for(namesIt = attributeNames.begin(); namesIt != attributeNames.end(); ++namesIt, ++it)
{
QString name = *namesIt; //just for the debugger
char* attribute = PQgetvalue(res, 0, PQfnumber(res,*namesIt));
QString val = QString::fromUtf8(attribute);
switch (attributeFields[*it].type())
{
case QVariant::Int:
feature.addAttribute(*it, val.toInt());
break;
case QVariant::Double:
feature.addAttribute(*it, val.toDouble());
break;
case QVariant::String:
feature.addAttribute(*it, val);
break;
default:
assert(0 && "unsupported field type");
}
}
// fetch geometry
if (fetchGeometry)
{
int returnedLength = PQgetlength(res, 0, PQfnumber(res,"qgs_feature_geometry"));
if(returnedLength > 0)
{
unsigned char *featureGeom = new unsigned char[returnedLength + 1];
memset(featureGeom, '\0', returnedLength + 1);
memcpy(featureGeom, PQgetvalue(res, 0, PQfnumber(res,"qgs_feature_geometry")), returnedLength);
feature.setGeometryAndOwnership(featureGeom, returnedLength + 1);
}
}
PQexec(connection, "end work");
return TRUE;
}
QgsDataSourceURI& QgsPostgresProvider::getURI()
{
return mUri;
}
void QgsPostgresProvider::setExtent( QgsRect& newExtent )
{
layerExtent.setXmax( newExtent.xMax() );
layerExtent.setXmin( newExtent.xMin() );
layerExtent.setYmax( newExtent.yMax() );
layerExtent.setYmin( 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;
}
/**
* 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::reset()
{
QString move = "move 0 in qgisf"; //move cursor to first record
PQexec(connection, (const char *)(move.utf8()));
mFeatureQueue.empty();
}
/** @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");
}
}
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 = "select indkey from pg_index where indisunique = 't' and "
"indrelid = (select oid from pg_class where relname = '"
+ mTableName + "' and relnamespace = (select oid from pg_namespace where "
"nspname = '" + mSchemaName + "'))";
QgsDebugMsg("Getting unique index using '" + sql + "'");
PGresult *pk = executeDbCommand(connection, 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 = "select relkind from pg_class where relname = '" + mTableName +
"' and relnamespace = (select oid from pg_namespace where "
"nspname = '" + mSchemaName + "')";
PGresult* tableType = executeDbCommand(connection, sql);
QString type = PQgetvalue(tableType, 0, 0);
PQclear(tableType);
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 = "select attname from pg_attribute where attname = 'oid' and "
"attrelid = (select oid from pg_class where relname = '" +
mTableName + "' and relnamespace = (select oid from pg_namespace "
"where nspname = '" + mSchemaName + "'))";
PGresult* oidCheck = executeDbCommand(connection, 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"));
}
PQclear(oidCheck);
}
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 = PQgetvalue(pk, i, 0);
QStringList columns = QStringList::split(" ", col);
if (columns.count() == 1)
{
// Get the column name and data type
sql = "select attname, pg_type.typname from pg_attribute, pg_type where "
"atttypid = pg_type.oid and attnum = " +
col + " and attrelid = (select oid from pg_class where " +
"relname = '" + mTableName + "' and relnamespace = (select oid "
"from pg_namespace where nspname = '" + mSchemaName + "'))";
PGresult* types = executeDbCommand(connection, sql);
assert(PQntuples(types) > 0); // should never happen
QString columnName = PQgetvalue(types, 0, 0);
QString columnType = 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));
PQclear(types);
}
else
{
sql = "select attname from pg_attribute, pg_type where "
"atttypid = pg_type.oid and attnum in (" +
col.replace(" ", ",")
+ ") and attrelid = (select oid from pg_class where " +
"relname = '" + mTableName + "' and relnamespace = (select oid "
"from pg_namespace where nspname = '" + mSchemaName + "'))";
PGresult* types = executeDbCommand(connection, sql);
QString colNames;
int numCols = PQntuples(types);
for (int j = 0; j < numCols; ++j)
{
if (j == numCols-1)
colNames += tr("and ");
colNames += "'" + QString(PQgetvalue(types, j, 0))
+ (j < numCols-2 ? "', " : "' ");
}
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.
if (suitableKeyColumns.size() > 0)
{
primaryKey = suitableKeyColumns[0].first;
primaryKeyType = suitableKeyColumns[0].second;
}
else
{
// If there is an oid on the table, use that instead,
// otherwise give up
sql = "select attname from pg_attribute where attname = 'oid' and "
"attrelid = (select oid from pg_class where relname = '" +
mTableName + "' and relnamespace = (select oid from pg_namespace "
"where nspname = '" + mSchemaName + "'))";
PGresult* oidCheck = executeDbCommand(connection, sql);
if (PQntuples(oidCheck) != 0)
{
primaryKey = "oid";
primaryKeyType = "int4";
}
else
{
log.prepend("There were no columns in the table that were suitable "
"as a qgis key into the table (either a column with a "
"unique index and type int4 or a PostgreSQL oid column.\n");
}
PQclear(oidCheck);
}
// Either primaryKey has been set by the above code, or it
// hasn't. If not, present some info to the user to give them some
// idea of why not.
if (primaryKey.isEmpty())
{
// Give some info to the user about why things didn't work out.
valid = false;
showMessageBox(tr("Unable to find a key column"), log);
}
}
PQclear(pk);
if (primaryKey.length() > 0) {
QgsDebugMsg("Qgis row key is " + primaryKey);
} else {
QgsDebugMsg("Qgis row key was not set.");
}
return primaryKey;
}
// Given the table and column that each column in the view refers to,
// choose one. Prefers column with an index on them, but will
// otherwise choose something suitable.
QString QgsPostgresProvider::chooseViewColumn(const tableCols& cols)
{
// For each relation name and column name need to see if it
// has unique constraints on it, or is a primary key (if not,
// it shouldn't be used). Should then be left with one or more
// entries in the map which can be used as the key.
QString sql, key;
QStringList log;
tableCols suitable;
// Cache of relation oid's
std::map<QString, QString> relOid;
std::vector<tableCols::const_iterator> oids;
tableCols::const_iterator iter = cols.begin();
for (; iter != cols.end(); ++iter)
{