/
qgsdb2provider.cpp
1752 lines (1524 loc) · 46 KB
/
qgsdb2provider.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
/***************************************************************************
qgsdb2provider.cpp - Data provider for DB2 server
--------------------------------------
Date : 2016-01-27
Copyright : (C) 2016 by David Adler
Shirley Xiao, David Nguyen
Email : dadler at adtechgeospatial.com
xshirley2012 at yahoo.com, davidng0123 at gmail.com
Adapted from MSSQL provider by Tamas Szekeres
****************************************************************************
*
* 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 "qgsdb2provider.h"
#include "qgsdb2dataitems.h"
#include "qgsdb2featureiterator.h"
#include "qgsdb2geometrycolumns.h"
#include <qgscoordinatereferencesystem.h>
#include <qgsdataitem.h>
#include <qgslogger.h>
#include "qgscrscache.h"
#include "qgscredentials.h"
static const QString PROVIDER_KEY = "DB2";
static const QString PROVIDER_DESCRIPTION = "DB2 Spatial Extender provider";
int QgsDb2Provider::sConnectionId = 0;
QgsDb2Provider::QgsDb2Provider( QString uri )
: QgsVectorDataProvider( uri )
, mNumberFeatures( 0 )
, mEnvironment( ENV_LUW )
, mWkbType( Qgis::WKBUnknown )
{
QgsDebugMsg( "uri: " + uri );
QgsDataSourceURI anUri = QgsDataSourceURI( uri );
if ( !anUri.srid().isEmpty() )
mSRId = anUri.srid().toInt();
else
mSRId = -1;
if ( 0 != anUri.newWkbType() )
{
mWkbType = Qgis::fromNewWkbType( anUri.newWkbType() );
}
QgsDebugMsg( QString( "mWkbType: %1" ).arg( mWkbType ) );
QgsDebugMsg( QString( "new mWkbType: %1" ).arg( anUri.newWkbType() ) );
mValid = true;
mSkipFailures = false;
int dim; // Not used
db2WkbTypeAndDimension( mWkbType, mGeometryColType, dim ); // Get DB2 geometry type name
mFidColName = anUri.keyColumn().toUpper();
QgsDebugMsg( "mFidColName " + mFidColName );
mExtents = anUri.param( "extents" );
QgsDebugMsg( "mExtents " + mExtents );
mUseEstimatedMetadata = anUri.useEstimatedMetadata();
QgsDebugMsg( QString( "mUseEstimatedMetadata: '%1'" ).arg( mUseEstimatedMetadata ) );
mSqlWhereClause = anUri.sql();
QString errMsg;
mDatabase = getDatabase( uri, errMsg );
mConnInfo = anUri.connectionInfo();
QgsCoordinateReferenceSystem layerCrs = crs();
QgsDebugMsg( "CRS: " + layerCrs.toWkt() );
if ( !errMsg.isEmpty() )
{
setLastError( errMsg );
QgsDebugMsg( mLastError );
mValid = false;
return;
}
// Create a query for default connection
mQuery = QSqlQuery( mDatabase );
mSchemaName = anUri.schema();
mTableName = anUri.table().toUpper();
QStringList sl = mTableName.split( '.' );
if ( sl.length() == 2 ) // Never seems to be the case
{
mSchemaName = sl[0];
mTableName = sl[1];
}
if ( mSchemaName.isEmpty() )
{
mSchemaName = anUri.username().toUpper();
}
QgsDebugMsg( "mSchemaName: '" + mSchemaName + "; mTableName: '" + mTableName );
if ( !anUri.geometryColumn().isEmpty() )
mGeometryColName = anUri.geometryColumn().toUpper();
loadFields();
updateStatistics();
if ( mGeometryColName.isEmpty() )
{
// table contains no geometries
mWkbType = Qgis::WKBNoGeometry;
mSRId = 0;
}
//fill type names into sets
mNativeTypes
// integer types
<< QgsVectorDataProvider::NativeType( tr( "8 Bytes integer" ), "bigint", QVariant::Int )
<< QgsVectorDataProvider::NativeType( tr( "4 Bytes integer" ), "integer", QVariant::Int )
<< QgsVectorDataProvider::NativeType( tr( "2 Bytes integer" ), "smallint", QVariant::Int )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 31, 0, 31 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 31, 0, 31 )
// floating point
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double", QVariant::Double )
// date/time types
<< QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "datetime", QVariant::DateTime, -1, -1, -1, -1 )
// string types
<< QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), "char", QVariant::String, 1, 254 )
<< QgsVectorDataProvider::NativeType( tr( "Text, variable length (varchar)" ), "varchar", QVariant::String, 1, 32704 )
<< QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (clob)" ), "clob", QVariant::String, 1, 2147483647 )
//DBCLOB is for 1073741824 double-byte characters, data length should be the same as CLOB (2147483647)?
<< QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (dbclob)" ), "dbclob", QVariant::String, 1, 1073741824 )
;
}
QgsDb2Provider::~QgsDb2Provider()
{
if ( mDatabase.isOpen() )
mDatabase.close();
}
QSqlDatabase QgsDb2Provider::getDatabase( const QString &connInfo, QString &errMsg )
{
QSqlDatabase db;
QString service;
QString driver;
QString host;
QString databaseName;
QString port;
QString userName;
QString password;
QString connectionName;
QString connectionString;
QgsDataSourceURI uri( connInfo );
// Fill in the password if authentication is used
QString expandedConnectionInfo = uri.connectionInfo( true );
QgsDebugMsg( "expanded connInfo: " + expandedConnectionInfo );
QgsDataSourceURI uriExpanded( expandedConnectionInfo );
userName = uriExpanded.username();
password = uriExpanded.password();
service = uriExpanded.service();
databaseName = uriExpanded.database();
host = uriExpanded.host();
port = uriExpanded.port();
driver = uriExpanded.driver();
QgsDebugMsg( QString( "driver: '%1'; host: '%2'; databaseName: '%3'" ).arg( driver, host, databaseName ) );
if ( service.isEmpty() )
{
if ( driver.isEmpty() || host.isEmpty() || databaseName.isEmpty() )
{
QgsDebugMsg( "service not provided, a required argument is empty." );
return db;
}
connectionName = databaseName + ".";
}
else
{
connectionName = service;
}
QgsDebugMsg( "connectionName: " + connectionName );
/* if new database connection */
if ( !QSqlDatabase::contains( connectionName ) )
{
QgsDebugMsg( "new connection. create new QODBC mapping" );
db = QSqlDatabase::addDatabase( "QODBC3", connectionName );
}
else /* if existing database connection */
{
QgsDebugMsg( "found existing connection, use the existing one" );
db = QSqlDatabase::database( connectionName );
}
db.setHostName( host );
db.setPort( port.toInt() );
bool connected = false;
int i = 0;
QgsCredentials::instance()->lock();
while ( !connected && i < 3 )
{
i++;
// Don't prompt if this is the first time and we have both userName and password
// This is needed for Python or any non-GUI process
if ( userName.isEmpty() || password.isEmpty() || ( !connected && i > 1 ) )
{
bool ok = QgsCredentials::instance()->get( databaseName, userName,
password, errMsg );
if ( !ok )
{
errMsg = "Cancel clicked";
QgsDebugMsg( errMsg );
QgsCredentials::instance()->unlock();
break;
}
}
db.setUserName( userName );
db.setPassword( password );
/* start building connection string */
if ( service.isEmpty() )
{
connectionString = QString( "Driver={%1};Hostname=%2;Port=%3;"
"Protocol=TCPIP;Database=%4;Uid=%5;Pwd=%6;" )
.arg( driver,
host )
.arg( db.port() )
.arg( databaseName,
userName,
password );
}
else
{
connectionString = service;
}
QgsDebugMsg( "ODBC connection string: " + connectionString );
db.setDatabaseName( connectionString ); //for QODBC driver, the name can be a DSN or connection string
if ( db.open() )
{
connected = true;
errMsg = "";
}
else
{
errMsg = db.lastError().text();
QgsDebugMsg( "DB not open" + errMsg );
}
}
if ( connected )
{
QgsCredentials::instance()->put( databaseName, userName, password );
}
QgsCredentials::instance()->unlock();
return db;
}
bool QgsDb2Provider::openDatabase( QSqlDatabase db )
{
QgsDebugMsg( "openDatabase" );
if ( !db.isOpen() )
{
if ( !db.open() )
{
QgsDebugMsg( "Database could not be opened." );
return false;
}
}
return true;
}
// loadFields() gets the type from the field record
void QgsDb2Provider::loadFields()
{
mAttributeFields.clear();
//mDefaultValues.clear();
QString table = QString( "%1.%2" ).arg( mSchemaName, mTableName );
// Use the Qt functionality to get the fields and their definitions.
QSqlRecord r = mDatabase.record( table );
int fieldCount = r.count();
for ( int i = 0; i < fieldCount; i++ )
{
QSqlField f = r.field( i );
int typeID = f.typeID(); // seems to be DB2 numeric type id (standard?)
QString sqlTypeName = db2TypeName( typeID );
QVariant::Type sqlType = f.type();
QgsDebugMsg( QString( "name: %1; length: %2; sqlTypeID: %3; sqlTypeName: %4" )
.arg( f.name() ).arg( f.length() ).arg( QString::number( typeID ), sqlTypeName ) );
if ( f.name() == mGeometryColName ) continue; // Got this with uri, just skip
if ( sqlType == QVariant::String )
{
mAttributeFields.append(
QgsField(
f.name(),
sqlType,
sqlTypeName,
f.length()
) );
}
else if ( sqlType == QVariant::Double )
{
mAttributeFields.append(
QgsField(
f.name(),
sqlType,
sqlTypeName,
f.length(),
f.precision()
) );
}
else
{
mAttributeFields.append(
QgsField(
f.name(),
sqlType,
sqlTypeName
) );
}
if ( !f.defaultValue().isNull() )
{
mDefaultValues.insert( i, f.defaultValue() );
}
// Hack to get primary key since the primaryIndex function above doesn't work
// on z/OS. Pick first integer column.
if ( mFidColName.length() == 0 &&
( sqlType == QVariant::LongLong || sqlType == QVariant::Int ) )
{
mFidColName = f.name();
}
}
}
QVariant::Type QgsDb2Provider::decodeSqlType( int typeId )
{
QVariant::Type type = QVariant::Invalid;
switch ( typeId )
{
case -5: //BIGINT
type = QVariant::LongLong;
break;
case -3: //VARBINARY
type = QVariant::ByteArray;
break;
case 1: //CHAR
case 12: //VARCHAR
type = QVariant::String;
break;
case 4: //INTEGER
type = QVariant::Int;
break;
case 3: //NUMERIC and DECIMAL
case 7: //REAL
case 8: //DOUBLE
type = QVariant::Double;
break;
case 9: //DATE
type = QVariant::String; // don't know why it doesn't like QVariant::Date
break;
case 10: //TIME
type = QVariant::Time;
break;
case 11: //TIMESTAMP
type = QVariant::String; // don't know why it doesn't like QVariant::DateTime
break;
default:
// Everything else just dumped as a string.
type = QVariant::String;
}
return type;
}
// Return the DB2 type name for the type numeric value
QString QgsDb2Provider::db2TypeName( int typeId )
{
QString typeName = "";
switch ( typeId )
{
case -3: //VARBINARY
typeName = "VARBINARY"; // also for spatial types
break;
case 1: //CHAR
typeName = "CHAR";
break;
case 12: //VARCHAR
typeName = "VARCHAR";
break;
case 4: //INTEGER
typeName = "INTEGER";
break;
case -5: //BIGINT
typeName = "BIGINT";
break;
case 3: //NUMERIC and DECIMAL
typeName = "DECIMAL";
break;
case 7: //REAL
typeName = "REAL";
break;
case 8: //DOUBLE
typeName = "DOUBLE";
break;
case 9: //DATE
typeName = "DATE";
break;
case 10: //TIME
typeName = "TIME";
break;
case 11: //TIMESTAMP
typeName = "TIMESTAMP";
break;
default:
typeName = "UNKNOWN";
}
return typeName;
}
QgsAbstractFeatureSource* QgsDb2Provider::featureSource() const
{
return new QgsDb2FeatureSource( this );
}
QgsFeatureIterator QgsDb2Provider::getFeatures( const QgsFeatureRequest& request ) const
{
if ( !mValid )
{
QgsDebugMsg( "Read attempt on an invalid db2 data source" );
return QgsFeatureIterator();
}
return QgsFeatureIterator( new QgsDb2FeatureIterator( new QgsDb2FeatureSource( this ), true, request ) );
}
Qgis::WkbType QgsDb2Provider::geometryType() const
{
return mWkbType;
}
long QgsDb2Provider::featureCount() const
{
// Return the count that we get from the subset.
if ( !mSqlWhereClause.isEmpty() )
return mNumberFeatures;
// On LUW, this could be selected from syscat.tables but I'm not sure if this
// is actually correct if RUNSTATS hasn't been done.
// On z/OS, we don't have access to the system catalog.
// Use count(*) as the easiest approach
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
QString sql = "SELECT COUNT(*) FROM %1.%2";
QString statement = QString( sql ).arg( mSchemaName, mTableName );
QgsDebugMsg( statement );
if ( query.exec( statement ) && query.next() )
{
QgsDebugMsg( QString( "count: %1" ).arg( query.value( 0 ).toInt() ) );
return query.value( 0 ).toInt();
}
else
{
QgsDebugMsg( "Failed" );
QgsDebugMsg( query.lastError().text() );
return -1;
}
}
QgsFields QgsDb2Provider::fields() const
{
return mAttributeFields;
}
QgsCoordinateReferenceSystem QgsDb2Provider::crs() const
{
if ( !mCrs.isValid() && mSRId > 0 )
{
mCrs.createFromSrid( mSRId );
if ( mCrs.isValid() )
{
return mCrs;
}
// try to load crs from the database tables as a fallback
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
bool execOk = query.exec( QString( "SELECT DEFINITION FROM DB2GSE.ST_SPATIAL_REFERENCE_SYSTEMS WHERE SRS_ID = %1" ).arg( QString::number( mSRId ) ) );
if ( execOk && query.isActive() )
{
if ( query.next() )
{
mCrs = QgsCrsCache::instance()->crsByWkt( query.value( 0 ).toString() );
if ( mCrs.isValid() )
return mCrs;
}
}
}
return mCrs;
}
// update the extent for this layer
void QgsDb2Provider::updateStatistics() const
{
// get features to calculate the statistics
QString statement;
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
statement = QString( "SELECT MIN(DB2GSE.ST_MINX(%1)), MIN(DB2GSE.ST_MINY(%1)), MAX(DB2GSE.ST_MAXX(%1)), MAX(DB2GSE.ST_MAXY(%1))" ).arg( mGeometryColName );
statement += QString( " FROM %1.%2" ).arg( mSchemaName, mTableName );
if ( !mSqlWhereClause.isEmpty() )
{
statement += " WHERE (" + mSqlWhereClause + ")";
}
QgsDebugMsg( statement );
if ( !query.exec( statement ) )
{
QgsDebugMsg( query.lastError().text() );
}
if ( !query.isActive() )
{
return;
}
if ( query.next() )
{
mExtent.setXMinimum( query.value( 0 ).toDouble() );
mExtent.setYMinimum( query.value( 1 ).toDouble() );
mExtent.setXMaximum( query.value( 2 ).toDouble() );
mExtent.setYMaximum( query.value( 3 ).toDouble() );
QgsDebugMsg( QString( "after setting; mExtent: %1" ).arg( mExtent.toString() ) );
}
QgsDebugMsg( QString( "mSRId: %1" ).arg( mSRId ) );
QgsDb2GeometryColumns gc( mDatabase );
int rc = gc.open( mSchemaName, mTableName ); // returns SQLCODE if failure
if ( rc == 0 )
{
mEnvironment = gc.db2Environment();
if ( -1 == mSRId )
{
QgsDb2LayerProperty layer;
gc.populateLayerProperty( layer );
if ( !layer.srid.isEmpty() )
{
mSRId = layer.srid.toInt();
mSrsName = layer.srsName;
}
mGeometryColType = layer.type;
QgsDebugMsg( QString( "srs_id: %1; srs_name: %2; mGeometryColType: %3" )
.arg( mSRId ).arg( mSrsName, mGeometryColType ) );
return;
}
}
else
{
QgsDebugMsg( "Couldn't get srid from geometry columns" );
}
// Try to get the srid from the data if srid isn't already set
QgsDebugMsg( QString( "mSRId: %1" ).arg( mSRId ) );
if ( -1 == mSRId )
{
query.clear();
statement = QString( "SELECT DB2GSE.ST_SRID(%1) FROM %2.%3 FETCH FIRST ROW ONLY" )
.arg( mGeometryColName, mSchemaName, mTableName );
QgsDebugMsg( statement );
if ( !query.exec( statement ) || !query.isActive() )
{
QgsDebugMsg( query.lastError().text() );
}
if ( query.next() )
{
mSRId = query.value( 0 ).toInt();
QgsDebugMsg( QString( "srid from data: %1" ).arg( mSRId ) );
return;
}
else
{
QgsDebugMsg( "Couldn't get srid from data" );
}
}
}
QgsRectangle QgsDb2Provider::extent() const
{
QgsDebugMsg( QString( "entering; mExtent: %1" ).arg( mExtent.toString() ) );
if ( mExtent.isEmpty() )
updateStatistics();
return mExtent;
}
bool QgsDb2Provider::isValid() const
{
return true; //DB2 only has valid geometries
}
QString QgsDb2Provider::subsetString() const
{
return mSqlWhereClause;
}
bool QgsDb2Provider::setSubsetString( const QString& theSQL, bool )
{
QString prevWhere = mSqlWhereClause;
QgsDebugMsg( theSQL );
mSqlWhereClause = theSQL.trimmed();
QString sql = QString( "SELECT COUNT(*) FROM " );
sql += QString( "%1.%2" ).arg( mSchemaName, mTableName );
if ( !mSqlWhereClause.isEmpty() )
{
sql += QString( " WHERE %1" ).arg( mSqlWhereClause );
}
if ( !openDatabase( mDatabase ) )
{
return false;
}
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
QgsDebugMsg( sql );
if ( !query.exec( sql ) )
{
pushError( query.lastError().text() );
mSqlWhereClause = prevWhere;
QgsDebugMsg( query.lastError().text() );
return false;
}
if ( query.isActive() && query.next() )
{
mNumberFeatures = query.value( 0 ).toInt();
QgsDebugMsg( QString( "count: %1" ).arg( mNumberFeatures ) );
}
else
{
pushError( query.lastError().text() );
mSqlWhereClause = prevWhere;
QgsDebugMsg( query.lastError().text() );
return false;
}
QgsDataSourceURI anUri = QgsDataSourceURI( dataSourceUri() );
anUri.setSql( mSqlWhereClause );
setDataSourceUri( anUri.uri() );
mExtent.setMinimal();
emit dataChanged();
return true;
}
void QgsDb2Provider::db2WkbTypeAndDimension( Qgis::WkbType wkbType, QString &geometryType, int &dim )
{
switch ( wkbType )
{
case Qgis::WKBPoint25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBPoint:
geometryType = "ST_POINT";
break;
case Qgis::WKBLineString25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBLineString:
geometryType = "ST_LINESTRING";
break;
case Qgis::WKBPolygon25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBPolygon:
geometryType = "ST_POLYGON";
break;
case Qgis::WKBMultiPoint25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBMultiPoint:
geometryType = "ST_MULTIPOINT";
break;
case Qgis::WKBMultiLineString25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBMultiLineString:
geometryType = "ST_MULTILINESTRING";
break;
case Qgis::WKBMultiPolygon25D:
dim = 3;
FALLTHROUGH;
case Qgis::WKBMultiPolygon:
geometryType = "ST_MULTIPOLYGON";
break;
case Qgis::WKBUnknown:
geometryType = "ST_GEOMETRY";
break;
case Qgis::WKBNoGeometry:
default:
dim = 0;
break;
}
}
bool QgsDb2Provider::deleteFeatures( const QgsFeatureIds & id )
{
if ( mFidColName.isEmpty() )
return false;
QString featureIds;
for ( QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it )
{
if ( featureIds.isEmpty() )
featureIds = FID_TO_STRING( *it );
else
featureIds += ',' + FID_TO_STRING( *it );
}
if ( !mDatabase.isOpen() )
{
QString errMsg;
mDatabase = getDatabase( mConnInfo, errMsg );
if ( !errMsg.isEmpty() )
{
return false;
}
}
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
QString statement;
statement = QString( "DELETE FROM %1.%2 WHERE %3 IN (%4)" ).arg( mSchemaName,
mTableName, mFidColName, featureIds );
QgsDebugMsg( statement );
if ( !query.exec( statement ) )
{
QgsDebugMsg( query.lastError().text() );
return false;
}
return true;
}
bool QgsDb2Provider::changeAttributeValues( const QgsChangedAttributesMap &attr_map )
{
QgsDebugMsg( "Entering" );
if ( attr_map.isEmpty() )
return true;
if ( mFidColName.isEmpty() )
return false;
for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
{
QgsFeatureId fid = it.key();
// skip added features
if ( FID_IS_NEW( fid ) )
continue;
const QgsAttributeMap& attrs = it.value();
if ( attrs.isEmpty() )
continue;
QString statement = QString( "UPDATE %1.%2 SET " ).arg( mSchemaName, mTableName );
bool first = true;
if ( !mDatabase.isOpen() )
{
QString errMsg;
mDatabase = getDatabase( mConnInfo, errMsg );
if ( !errMsg.isEmpty() )
{
return false;
}
}
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
for ( QgsAttributeMap::const_iterator it2 = attrs.begin(); it2 != attrs.end(); ++it2 )
{
QgsField fld = mAttributeFields.at( it2.key() );
if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) )
continue; // skip identity field
if ( fld.name().isEmpty() )
continue; // invalid
if ( !first )
statement += ',';
else
first = false;
statement += QString( "%1=?" ).arg( fld.name() );
}
if ( first )
return true; // no fields have been changed
// set attribute filter
statement += QString( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) );
// use prepared statement to prevent from sql injection
if ( !query.prepare( statement ) )
{
QgsDebugMsg( query.lastError().text() );
return false;
}
QgsDebugMsg( statement );
for ( QgsAttributeMap::const_iterator it2 = attrs.begin(); it2 != attrs.end(); ++it2 )
{
QgsField fld = mAttributeFields.at( it2.key() );
if ( fld.name().isEmpty() )
continue; // invalid
QVariant::Type type = fld.type();
if ( it2->isNull() || !it2->isValid() )
{
// binding null values
if ( type == QVariant::Date || type == QVariant::DateTime )
query.addBindValue( QVariant( QVariant::String ) );
else
query.addBindValue( QVariant( type ) );
}
else if ( type == QVariant::Int )
{
// binding an INTEGER value
query.addBindValue( it2->toInt() );
}
else if ( type == QVariant::Double )
{
// binding a DOUBLE value
query.addBindValue( it2->toDouble() );
}
else if ( type == QVariant::String )
{
// binding a TEXT value
query.addBindValue( it2->toString() );
}
else if ( type == QVariant::DateTime )
{
// binding a DATETIME value
query.addBindValue( it2->toDateTime().toString( Qt::ISODate ) );
}
else if ( type == QVariant::Date )
{
// binding a DATE value
query.addBindValue( it2->toDate().toString( Qt::ISODate ) );
}
else if ( type == QVariant::Time )
{
// binding a TIME value
query.addBindValue( it2->toTime().toString( Qt::ISODate ) );
}
else
{
query.addBindValue( *it2 );
}
}
if ( !query.exec() )
{
QgsDebugMsg( query.lastError().text() );
return false;
}
}
return true;
}
bool QgsDb2Provider::addFeatures( QgsFeatureList & flist )
{
QgsDebugMsg( "mGeometryColType: " + mGeometryColType );
int writeCount = 0;
bool copyOperation = false;
if ( !mDatabase.isOpen() )
{
QString errMsg;
mDatabase = getDatabase( mConnInfo, errMsg );
if ( !errMsg.isEmpty() )
{
QgsDebugMsg( "getDatabase failed: " + errMsg );
return false;
}
}
if ( !mDatabase.transaction() )
{
QgsDebugMsg( "transaction failed" );
return false;
}
QSqlQuery query = QSqlQuery( mDatabase );
query.setForwardOnly( true );
QSqlQuery queryFid = QSqlQuery( mDatabase );
queryFid.setForwardOnly( true );
QgsFeature it = flist.at( 0 );
QString statement;
QString values;
statement = QString( "INSERT INTO %1.%2 (" ).arg( mSchemaName, mTableName );
bool first = true;
// Get the first geometry and its wkbType as when we are doing drag/drop,
// the wkbType is not passed to the DB2 provider from QgsVectorLayerImport
// Can't figure out how to resolved "unreferenced" wkbType compile message
// Don't really do anything with it at this point
#if 0
QgsGeometry *geom = it.geometry();
Qgis::WkbType wkbType = geom->wkbType();
QgsDebugMsg( QString( "wkbType: %1" ).arg( wkbType ) );
QgsDebugMsg( QString( "mWkbType: %1" ).arg( mWkbType ) );
#endif
QgsAttributes attrs = it.attributes();
QgsDebugMsg( QString( "attrs.count: %1" ).arg( attrs.count() ) );
QgsDebugMsg( QString( "fields.count: %1" ).arg( mAttributeFields.count() ) );
if ( mAttributeFields.count() == ( attrs.count() + 1 ) )
{
copyOperation = true; // FID is first field but no attribute in attrs
}
else if ( mAttributeFields.count() != attrs.count() )
{
QgsDebugMsg( "Count mismatch - failing" );
return false;
}
if ( attrs.count() != mAttributeFields.count() )
{
QgsDebugMsg( "field counts don't match" );
// return false;
}
for ( int i = 0; i < mAttributeFields.count(); ++i )
{
QgsField fld = mAttributeFields.at( i );
QgsDebugMsg( QString( "i: %1; got field: %2" ).arg( i ).arg( fld.name() ) );
if ( fld.name().isEmpty() )
continue; // invalid
if ( mFidColName == fld.name() )
continue; // skip identity field
// if ( mDefaultValues.contains( i ) && mDefaultValues[i] == attrs.at( i ) )
// continue; // skip fields having default values
if ( !first )
{
statement += ',';
values += ',';