/
qgsogrprovider.cpp
1822 lines (1536 loc) · 51.1 KB
/
qgsogrprovider.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
/***************************************************************************
qgsogrprovider.cpp Data provider for OGR supported formats
Formerly known as qgsshapefileprovider.cpp
begin : Oct 29, 2003
copyright : (C) 2003 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$ */
#include "qgsogrprovider.h"
#include "qgslogger.h"
#define CPL_SUPRESS_CPLUSPLUS
#include <gdal.h> // to collect version information
#include <ogr_api.h>
#include <ogr_srs_api.h>
#include <cpl_error.h>
#include <cpl_conv.h>
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QMap>
#include <QString>
#include <QTextCodec>
#include "qgsapplication.h"
#include "qgsdataprovider.h"
#include "qgsfeature.h"
#include "qgsfield.h"
#include "qgsgeometry.h"
#include "qgslogger.h"
#include "qgscoordinatereferencesystem.h"
static const QString TEXT_PROVIDER_KEY = "ogr";
static const QString TEXT_PROVIDER_DESCRIPTION =
QString( "OGR data provider" )
+ " (compiled against GDAL/OGR library version "
+ GDAL_RELEASE_NAME
+ ", running against GDAL/OGR library version "
+ GDALVersionInfo( "RELEASE_NAME" )
+ ")";
QgsOgrProvider::QgsOgrProvider( QString const & uri )
: QgsVectorDataProvider( uri ),
ogrDataSource( 0 ),
extent_( 0 ),
ogrLayer( 0 ),
ogrOrigLayer( 0 ),
ogrDriver( 0 ),
featuresCounted( -1 )
{
QgsApplication::registerOgrDrivers();
// set the selection rectangle pointer to 0
mSelectionRectangle = 0;
// make connection to the data source
QgsDebugMsg( "Data source uri is " + uri );
// try to open for update, but disable error messages to avoid a
// message if the file is read only, because we cope with that
// ourselves.
// This part of the code parses the uri transmitted to the ogr provider to
// get the options the client wants us to apply
// If there is no & in the uri, then the uri is just the filename. The loaded
// layer will be layer 0.
//this is not true for geojson
if ( !uri.contains( '|', Qt::CaseSensitive ) )
{
mFilePath = uri;
mLayerIndex = 0;
mLayerName = QString::null;
}
else
{
QStringList theURIParts = uri.split( "|" );
mFilePath = theURIParts.at( 0 );
for ( int i = 1 ; i < theURIParts.size(); i++ )
{
QString part = theURIParts.at( i );
int pos = part.indexOf( "=" );
QString field = part.left( pos );
QString value = part.mid( pos + 1 );
if ( field == "layerid" )
{
bool ok;
mLayerIndex = value.toInt( &ok );
if ( ! ok )
{
mLayerIndex = -1;
}
}
else if ( field == "layername" )
{
mLayerName = value;
}
if ( field == "subset" )
{
mSubsetString = value;
}
}
}
QgsDebugMsg( "mFilePath: " + mFilePath );
QgsDebugMsg( "mLayerIndex: " + QString::number( mLayerIndex ) );
QgsDebugMsg( "mLayerName: " + mLayerName );
QgsDebugMsg( "mSubsetString: " + mSubsetString );
CPLSetConfigOption( "OGR_ORGANIZE_POLYGONS", "ONLY_CCW" ); // "SKIP" returns MULTIPOLYGONs for multiringed POLYGONs
CPLPushErrorHandler( CPLQuietErrorHandler );
ogrDataSource = OGROpen( QFile::encodeName( mFilePath ).constData(), TRUE, &ogrDriver );
CPLPopErrorHandler();
if ( ogrDataSource == NULL )
{
// try to open read-only
ogrDataSource = OGROpen( QFile::encodeName( mFilePath ).constData(), FALSE, &ogrDriver );
//TODO Need to set a flag or something to indicate that the layer
//TODO is in read-only mode, otherwise edit ops will fail
//TODO: capabilities() should now reflect this; need to test.
}
if ( ogrDataSource != NULL )
{
QgsDebugMsg( "Data source is valid" );
QgsDebugMsg( "OGR Driver was " + QString( OGR_Dr_GetName( ogrDriver ) ) );
valid = true;
ogrDriverName = OGR_Dr_GetName( ogrDriver );
// We get the layer which was requested by the uri. The layername
// has precedence over the layerid if both are given.
if ( mLayerName.isNull() )
{
ogrOrigLayer = OGR_DS_GetLayer( ogrDataSource, mLayerIndex );
}
else
{
ogrOrigLayer = OGR_DS_GetLayerByName( ogrDataSource, mLayerName.toLocal8Bit().data() );
}
extent_ = calloc( sizeof( OGREnvelope ), 1 );
ogrLayer = ogrOrigLayer;
setSubsetString( mSubsetString );
}
else
{
QgsLogger::critical( "Data source is invalid" );
QgsLogger::critical( QString::fromUtf8( CPLGetLastErrorMsg() ) );
valid = false;
}
// FIXME: sync with app/qgsnewvectorlayerdialog.cpp
mNativeTypes
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 1, 10 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double", QVariant::Double, 1, 20, 0, 5 )
<< QgsVectorDataProvider::NativeType( tr( "Text (string)" ), "string", QVariant::String, 1, 255 )
;
}
QgsOgrProvider::~QgsOgrProvider()
{
if ( ogrLayer != ogrOrigLayer )
{
OGR_DS_ReleaseResultSet( ogrDataSource, ogrLayer );
}
OGR_DS_Destroy( ogrDataSource );
ogrDataSource = 0;
free( extent_ );
extent_ = 0;
if ( mSelectionRectangle )
{
OGR_G_DestroyGeometry( mSelectionRectangle );
mSelectionRectangle = 0;
}
}
bool QgsOgrProvider::setSubsetString( QString theSQL )
{
if ( theSQL == mSubsetString && featuresCounted >= 0 )
return true;
OGRLayerH prevLayer = ogrLayer;
QString prevSubsetString = mSubsetString;
mSubsetString = theSQL;
if ( !mSubsetString.isEmpty() )
{
QString sql = QString( "SELECT * FROM %1 WHERE %2" )
.arg( quotedIdentifier( OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) ) ) )
.arg( mSubsetString );
ogrLayer = OGR_DS_ExecuteSQL( ogrDataSource, mEncoding->fromUnicode( sql ).constData(), NULL, NULL );
if ( !ogrLayer )
{
ogrLayer = prevLayer;
mSubsetString = prevSubsetString;
return false;
}
}
else
{
ogrLayer = ogrOrigLayer;
}
if ( prevLayer != ogrOrigLayer )
{
OGR_DS_ReleaseResultSet( ogrDataSource, prevLayer );
}
QString uri = mFilePath;
if ( !mLayerName.isNull() )
{
uri += QString( "|layername=%1" ).arg( mLayerName );
}
else if ( mLayerIndex >= 0 )
{
uri += QString( "|layerid=%1" ).arg( mLayerIndex );
}
if ( !mSubsetString.isEmpty() )
{
uri += QString( "|subset=%1" ).arg( mSubsetString );
}
setDataSourceUri( uri );
OGR_L_ResetReading( ogrLayer );
// getting the total number of features in the layer
// TODO: This can be expensive, do we really need it!
featuresCounted = OGR_L_GetFeatureCount( ogrLayer, TRUE );
// get the extent_ (envelope) of the layer
QgsDebugMsg( "Starting get extent" );
// TODO: This can be expensive, do we really need it!
OGR_L_GetExtent( ogrLayer, ( OGREnvelope * ) extent_, TRUE );
QgsDebugMsg( "Finished get extent" );
// check the validity of the layer
QgsDebugMsg( "checking validity" );
loadFields();
QgsDebugMsg( "Done checking validity" );
return true;
}
QString QgsOgrProvider::subsetString()
{
return mSubsetString;
}
QStringList QgsOgrProvider::subLayers() const
{
QStringList theList = QStringList();
if ( ! valid )
{
return theList;
}
for ( unsigned int i = 0; i < layerCount() ; i++ )
{
QString theLayerName = QString::fromLocal8Bit( OGR_FD_GetName( OGR_L_GetLayerDefn( OGR_DS_GetLayer( ogrDataSource, i ) ) ) );
OGRwkbGeometryType layerGeomType = OGR_FD_GetGeomType( OGR_L_GetLayerDefn( OGR_DS_GetLayer( ogrDataSource, i ) ) );
int theLayerFeatureCount = OGR_L_GetFeatureCount( OGR_DS_GetLayer( ogrDataSource, i ), 1 ) ;
QString geom;
switch ( layerGeomType )
{
case wkbUnknown: geom = "Unknown"; break;
case wkbPoint: geom = "Point"; break;
case wkbLineString: geom = "LineString"; break;
case wkbPolygon: geom = "Polygon"; break;
case wkbMultiPoint: geom = "MultiPoint"; break;
case wkbMultiLineString: geom = "MultiLineString"; break;
case wkbGeometryCollection: geom = "GeometryCollection"; break;
case wkbNone: geom = "None"; break;
case wkbPoint25D: geom = "Point25D"; break;
case wkbLineString25D: geom = "LineString25D"; break;
case wkbPolygon25D: geom = "Polygon25D"; break;
case wkbMultiPoint25D: geom = "MultiPoint25D"; break;
case wkbMultiLineString25D: geom = "MultiLineString25D"; break;
case wkbMultiPolygon25D: geom = "MultiPolygon25D"; break;
default: geom="Unknown WKB: " + QString::number( layerGeomType );
}
theList.append( QString::number( i ) + ":" + theLayerName + ":" + QString::number( theLayerFeatureCount ) + ":" + geom );
}
return theList;
}
void QgsOgrProvider::setEncoding( const QString& e )
{
QgsVectorDataProvider::setEncoding( e );
loadFields();
}
void QgsOgrProvider::loadFields()
{
//the attribute fields need to be read again when the encoding changes
mAttributeFields.clear();
OGRFeatureDefnH fdef = OGR_L_GetLayerDefn( ogrLayer );
if ( fdef )
{
geomType = OGR_FD_GetGeomType( fdef );
//Some ogr drivers (e.g. GML) are not able to determine the geometry type of a layer like this.
//In such cases, we examine the first feature
if ( geomType == wkbUnknown )
{
OGR_L_ResetReading( ogrLayer );
OGRFeatureH firstFeature = OGR_L_GetNextFeature( ogrLayer );
if ( firstFeature )
{
OGRGeometryH firstGeometry = OGR_F_GetGeometryRef( firstFeature );
if ( firstGeometry )
{
geomType = OGR_G_GetGeometryType( firstGeometry );
}
OGR_F_Destroy( firstFeature );
}
OGR_L_ResetReading( ogrLayer );
}
for ( int i = 0; i < OGR_FD_GetFieldCount( fdef ); ++i )
{
OGRFieldDefnH fldDef = OGR_FD_GetFieldDefn( fdef, i );
OGRFieldType ogrType = OGR_Fld_GetType( fldDef );
QVariant::Type varType;
switch ( ogrType )
{
case OFTInteger: varType = QVariant::Int; break;
case OFTReal: varType = QVariant::Double; break;
// unsupported in OGR 1.3
//case OFTDateTime: varType = QVariant::DateTime; break;
#if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1400
case OFTString: varType = QVariant::String; break;
#endif
default: varType = QVariant::String; // other unsupported, leave it as a string
}
mAttributeFields.insert(
i, QgsField(
mEncoding->toUnicode( OGR_Fld_GetNameRef( fldDef ) ), varType,
mEncoding->toUnicode( OGR_GetFieldTypeName( ogrType ) ),
OGR_Fld_GetWidth( fldDef ),
OGR_Fld_GetPrecision( fldDef ) ) );
}
}
}
QString QgsOgrProvider::storageType() const
{
// Delegate to the driver loaded in by OGR
return ogrDriverName;
}
bool QgsOgrProvider::featureAtId( int featureId,
QgsFeature& feature,
bool fetchGeometry,
QgsAttributeList fetchAttributes )
{
OGRFeatureH fet = OGR_L_GetFeature( ogrLayer, featureId );
if ( fet == NULL )
return false;
feature.setFeatureId( OGR_F_GetFID( fet ) );
// skip features without geometry
if ( OGR_F_GetGeometryRef( fet ) == NULL && !mFetchFeaturesWithoutGeom )
{
OGR_F_Destroy( fet );
return false;
}
/* fetch geometry */
if ( fetchGeometry )
{
OGRGeometryH geom = OGR_F_GetGeometryRef( fet );
// skip features without geometry
// get the wkb representation
unsigned char *wkb = new unsigned char[OGR_G_WkbSize( geom )];
OGR_G_ExportToWkb( geom, ( OGRwkbByteOrder ) QgsApplication::endian(), wkb );
feature.setGeometryAndOwnership( wkb, OGR_G_WkbSize( geom ) );
}
/* fetch attributes */
for ( QgsAttributeList::iterator it = fetchAttributes.begin(); it != fetchAttributes.end(); ++it )
{
getFeatureAttribute( fet, feature, *it );
}
if ( OGR_F_GetGeometryRef( fet ) != NULL )
{
feature.setValid( true );
}
else
{
feature.setValid( false );
}
OGR_F_Destroy( fet );
return true;
}
bool QgsOgrProvider::nextFeature( QgsFeature& feature )
{
feature.setValid( false );
if ( !valid )
{
QgsLogger::warning( "Read attempt on an invalid shapefile data source" );
return false;
}
OGRFeatureH fet;
QgsRectangle selectionRect;
while (( fet = OGR_L_GetNextFeature( ogrLayer ) ) != NULL )
{
// skip features without geometry
if ( !mFetchFeaturesWithoutGeom && OGR_F_GetGeometryRef( fet ) == NULL )
{
OGR_F_Destroy( fet );
continue;
}
OGRFeatureDefnH featureDefinition = OGR_F_GetDefnRef( fet );
QString featureTypeName = featureDefinition ? QString( OGR_FD_GetName( featureDefinition ) ) : QString( "" );
feature.setFeatureId( OGR_F_GetFID( fet ) );
feature.setTypeName( featureTypeName );
/* fetch geometry */
if ( mFetchGeom || mUseIntersect )
{
OGRGeometryH geom = OGR_F_GetGeometryRef( fet );
if ( geom == 0 )
{
OGR_F_Destroy( fet );
continue;
}
// get the wkb representation
unsigned char *wkb = new unsigned char[OGR_G_WkbSize( geom )];
OGR_G_ExportToWkb( geom, ( OGRwkbByteOrder ) QgsApplication::endian(), wkb );
feature.setGeometryAndOwnership( wkb, OGR_G_WkbSize( geom ) );
if ( mUseIntersect )
{
//precise test for intersection with search rectangle
//first make QgsRectangle from OGRPolygon
OGREnvelope env;
memset( &env, 0, sizeof( env ) );
if ( mSelectionRectangle )
OGR_G_GetEnvelope( mSelectionRectangle, &env );
if ( env.MinX != 0 || env.MinY != 0 || env.MaxX != 0 || env.MaxY != 0 ) //if envelope is invalid, skip the precise intersection test
{
selectionRect.set( env.MinX, env.MinY, env.MaxX, env.MaxY );
if ( !feature.geometry()->intersects( selectionRect ) )
{
OGR_F_Destroy( fet );
continue;
}
}
}
}
/* fetch attributes */
for ( QgsAttributeList::iterator it = mAttributesToFetch.begin(); it != mAttributesToFetch.end(); ++it )
{
getFeatureAttribute( fet, feature, *it );
}
/* we have a feature, end this cycle */
break;
} /* while */
if ( fet )
{
if ( OGR_F_GetGeometryRef( fet ) != NULL )
{
feature.setValid( true );
}
else
{
feature.setValid( false );
}
OGR_F_Destroy( fet );
return true;
}
else
{
QgsDebugMsg( "Feature is null" );
// probably should reset reading here
OGR_L_ResetReading( ogrLayer );
return false;
}
}
void QgsOgrProvider::select( QgsAttributeList fetchAttributes, QgsRectangle rect, bool fetchGeometry, bool useIntersect )
{
mUseIntersect = useIntersect;
mAttributesToFetch = fetchAttributes;
mFetchGeom = fetchGeometry;
// spatial query to select features
if ( rect.isEmpty() )
{
OGR_L_SetSpatialFilter( ogrLayer, 0 );
}
else
{
OGRGeometryH filter = 0;
QString wktExtent = QString( "POLYGON((%1))" ).arg( rect.asPolygon() );
QByteArray ba = wktExtent.toAscii();
const char *wktText = ba;
if ( useIntersect )
{
// store the selection rectangle for use in filtering features during
// an identify and display attributes
if ( mSelectionRectangle )
OGR_G_DestroyGeometry( mSelectionRectangle );
OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &mSelectionRectangle );
wktText = ba;
}
OGR_G_CreateFromWkt(( char ** )&wktText, NULL, &filter );
QgsDebugMsg( "Setting spatial filter using " + wktExtent );
OGR_L_SetSpatialFilter( ogrLayer, filter );
OGR_G_DestroyGeometry( filter );
}
//start with first feature
OGR_L_ResetReading( ogrLayer );
}
unsigned char * QgsOgrProvider::getGeometryPointer( OGRFeatureH fet )
{
OGRGeometryH geom = OGR_F_GetGeometryRef( fet );
unsigned char *gPtr = 0;
if ( geom == NULL )
return NULL;
// get the wkb representation
gPtr = new unsigned char[OGR_G_WkbSize( geom )];
OGR_G_ExportToWkb( geom, ( OGRwkbByteOrder ) QgsApplication::endian(), gPtr );
return gPtr;
}
QgsRectangle QgsOgrProvider::extent()
{
OGREnvelope *ext = ( OGREnvelope * ) extent_;
mExtentRect.set( ext->MinX, ext->MinY, ext->MaxX, ext->MaxY );
return mExtentRect;
}
size_t QgsOgrProvider::layerCount() const
{
return OGR_DS_GetLayerCount( ogrDataSource );
} // QgsOgrProvider::layerCount()
/**
* Return the feature type
*/
QGis::WkbType QgsOgrProvider::geometryType() const
{
return ( QGis::WkbType ) geomType;
}
/**
* Return the feature type
*/
long QgsOgrProvider::featureCount() const
{
return featuresCounted;
}
/**
* Return the number of fields
*/
uint QgsOgrProvider::fieldCount() const
{
return mAttributeFields.size();
}
void QgsOgrProvider::getFeatureAttribute( OGRFeatureH ogrFet, QgsFeature & f, int attindex )
{
OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attindex );
if ( ! fldDef )
{
QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" );
return;
}
QVariant value;
if ( OGR_F_IsFieldSet( ogrFet, attindex ) )
{
switch ( mAttributeFields[attindex].type() )
{
case QVariant::String: value = QVariant( mEncoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attindex ) ) ); break;
case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break;
case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break;
//case QVariant::DateTime: value = QVariant(QDateTime::fromString(str)); break;
default: assert( NULL && "unsupported field type" );
}
}
else
{
value = QVariant( QString::null );
}
f.addAttribute( attindex, value );
}
const QgsFieldMap & QgsOgrProvider::fields() const
{
return mAttributeFields;
}
void QgsOgrProvider::rewind()
{
OGR_L_ResetReading( ogrLayer );
}
//TODO - add sanity check for shape file layers, to include cheking to
// see if the .shp, .dbf, .shx files are all present and the layer
// actually has features
bool QgsOgrProvider::isValid()
{
return valid;
}
bool QgsOgrProvider::addFeature( QgsFeature& f )
{
bool returnValue = true;
OGRFeatureDefnH fdef = OGR_L_GetLayerDefn( ogrLayer );
OGRFeatureH feature = OGR_F_Create( fdef );
unsigned char* wkb = f.geometry()->asWkb();
if ( f.geometry()->wkbSize() > 0 )
{
OGRGeometryH geom = NULL;
if ( OGR_G_CreateFromWkb( wkb, NULL, &geom, f.geometry()->wkbSize() )
!= OGRERR_NONE )
{
return false;
}
OGR_F_SetGeometryDirectly( feature, geom );
}
QgsAttributeMap attrs = f.attributeMap();
//add possible attribute information
for ( QgsAttributeMap::iterator it = attrs.begin(); it != attrs.end(); ++it )
{
int targetAttributeId = it.key();
// don't try to set field from attribute map if it's not present in layer
if ( targetAttributeId >= OGR_FD_GetFieldCount( fdef ) )
continue;
//if(!s.isEmpty())
// continue;
//
OGRFieldDefnH fldDef = OGR_FD_GetFieldDefn( fdef, targetAttributeId );
OGRFieldType type = OGR_Fld_GetType( fldDef );
if ( it->isNull() || ( type != OFTString && it->toString().isEmpty() ) )
{
OGR_F_UnsetField( feature, targetAttributeId );
}
else
{
switch ( type )
{
case OFTInteger:
OGR_F_SetFieldInteger( feature, targetAttributeId, it->toInt() );
break;
case OFTReal:
OGR_F_SetFieldDouble( feature, targetAttributeId, it->toDouble() );
break;
case OFTString:
QgsDebugMsg( QString( "Writing string attribute %1 with %2, encoding %3" )
.arg( targetAttributeId )
.arg( it->toString() )
.arg( mEncoding->name().data() ) );
OGR_F_SetFieldString( feature, targetAttributeId, mEncoding->fromUnicode( it->toString() ).constData() );
break;
default:
QgsLogger::warning( "QgsOgrProvider::addFeature, no type found" );
break;
}
}
}
if ( OGR_L_CreateFeature( ogrLayer, feature ) != OGRERR_NONE )
{
QgsLogger::warning( "Writing of the feature failed" );
returnValue = false;
}
else
{
f.setFeatureId( OGR_F_GetFID( feature ) );
}
++featuresCounted;
OGR_F_Destroy( feature );
return returnValue;
}
bool QgsOgrProvider::addFeatures( QgsFeatureList & flist )
{
bool returnvalue = true;
for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end(); ++it )
{
if ( !addFeature( *it ) )
{
returnvalue = false;
}
}
if ( !syncToDisc() )
{
returnvalue = false;
}
featuresCounted = OGR_L_GetFeatureCount( ogrLayer, TRUE ); //new feature count
return returnvalue;
}
bool QgsOgrProvider::addAttributes( const QList<QgsField> &attributes )
{
bool returnvalue = true;
for ( QList<QgsField>::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter )
{
OGRFieldType type;
switch ( iter->type() )
{
case QVariant::Int:
type = OFTInteger;
break;
case QVariant::Double:
type = OFTReal;
break;
case QVariant::String:
type = OFTString;
break;
default:
QgsLogger::warning( QString( "QgsOgrProvider::addAttributes, type %1 not found" ).arg( iter->typeName() ) );
returnvalue = false;
continue;
}
OGRFieldDefnH fielddefn = OGR_Fld_Create( mEncoding->fromUnicode( iter->name() ).data(), type );
OGR_Fld_SetWidth( fielddefn, iter->length() );
OGR_Fld_SetPrecision( fielddefn, iter->precision() );
if ( OGR_L_CreateField( ogrLayer, fielddefn, TRUE ) != OGRERR_NONE )
{
QgsLogger::warning( "QgsOgrProvider.cpp: writing of field failed" );
returnvalue = false;
}
OGR_Fld_Destroy( fielddefn );
}
loadFields();
return returnvalue;
}
bool QgsOgrProvider::changeAttributeValues( const QgsChangedAttributesMap & attr_map )
{
for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
{
long fid = ( long ) it.key();
OGRFeatureH of = OGR_L_GetFeature( ogrLayer, fid );
if ( !of )
{
QgsLogger::warning( "QgsOgrProvider::changeAttributeValues, Cannot read feature, cannot change attributes" );
return false;
}
const QgsAttributeMap& attr = it.value();
for ( QgsAttributeMap::const_iterator it2 = attr.begin(); it2 != attr.end(); ++it2 )
{
int f = it2.key();
OGRFieldDefnH fd = OGR_F_GetFieldDefnRef( of, f );
if ( fd == NULL )
{
QgsLogger::warning( "QgsOgrProvider::changeAttributeValues, Field " + QString::number( f ) + " doesn't exist" );
continue;
}
OGRFieldType type = OGR_Fld_GetType( fd );
if ( it2->isNull() || ( type != OFTString && it2->toString().isEmpty() ) )
{
OGR_F_UnsetField( of, f );
}
else
{
switch ( type )
{
case OFTInteger:
OGR_F_SetFieldInteger( of, f, it2->toInt() );
break;
case OFTReal:
OGR_F_SetFieldDouble( of, f, it2->toDouble() );
break;
case OFTString:
OGR_F_SetFieldString( of, f, mEncoding->fromUnicode( it2->toString() ).constData() );
break;
default:
QgsLogger::warning( "QgsOgrProvider::changeAttributeValues, Unknown field type, cannot change attribute" );
break;
}
}
}
OGRErr res;
if (( res = OGR_L_SetFeature( ogrLayer, of ) ) != OGRERR_NONE )
{
QgsLogger::warning( "QgsOgrProvider::changeAttributeValues, setting the feature failed: " + QString::number( res ) );
}
}
OGR_L_SyncToDisk( ogrLayer );
return true;
}
bool QgsOgrProvider::changeGeometryValues( QgsGeometryMap & geometry_map )
{
OGRErr res;
OGRFeatureH theOGRFeature = 0;
OGRGeometryH theNewGeometry = 0;
for ( QgsGeometryMap::iterator it = geometry_map.begin(); it != geometry_map.end(); ++it )
{
theOGRFeature = OGR_L_GetFeature( ogrLayer, it.key() );
if ( !theOGRFeature )
{
QgsLogger::warning( "QgsOgrProvider::changeGeometryValues, cannot find feature" );
continue;
}
//create an OGRGeometry
if ( OGR_G_CreateFromWkb( it->asWkb(),
OGR_L_GetSpatialRef( ogrLayer ),
&theNewGeometry,
it->wkbSize() ) != OGRERR_NONE )
{
QgsLogger::warning( "QgsOgrProvider::changeGeometryValues, error while creating new OGRGeometry" );
OGR_G_DestroyGeometry( theNewGeometry );
theNewGeometry = 0;
continue;
}
if ( !theNewGeometry )
{
QgsLogger::warning( "QgsOgrProvider::changeGeometryValues, new geometry is NULL" );
continue;
}
//set the new geometry
if (( res = OGR_F_SetGeometryDirectly( theOGRFeature, theNewGeometry ) ) != OGRERR_NONE )
{
QgsLogger::warning( "QgsOgrProvider::changeGeometryValues, error while replacing geometry: " + QString::number( res ) );
OGR_G_DestroyGeometry( theNewGeometry );
theNewGeometry = 0;
continue;
}
if (( res = OGR_L_SetFeature( ogrLayer, theOGRFeature ) ) != OGRERR_NONE )
{
QgsLogger::warning( "QgsOgrProvider::changeGeometryValues, error while setting feature: " + QString::number( res ) );
OGR_G_DestroyGeometry( theNewGeometry );
theNewGeometry = 0;
continue;
}
OGR_F_Destroy( theOGRFeature );
}
return syncToDisc();
}
bool QgsOgrProvider::createSpatialIndex()
{
QString layerName = OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) );
QString sql = QString( "CREATE SPATIAL INDEX ON %1" ).arg( quotedIdentifier( layerName ) ); // quote the layer name so spaces are handled
OGR_DS_ExecuteSQL( ogrDataSource, mEncoding->fromUnicode( sql ).data(), OGR_L_GetSpatialFilter( ogrOrigLayer ), "" );
QFileInfo fi( mFilePath ); // to get the base name
//find out, if the .qix file is there
QFile indexfile( fi.path().append( "/" ).append( fi.completeBaseName() ).append( ".qix" ) );
return indexfile.exists();
}
bool QgsOgrProvider::deleteFeatures( const QgsFeatureIds & id )
{
bool returnvalue = true;
for ( QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it )
{
if ( !deleteFeature( *it ) )
{
returnvalue = false;
}
}
if ( !syncToDisc() )
{
returnvalue = false;
}
QString layerName = OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) );
QFileInfo fi( dataSourceUri() ); // to get the base name
QString sql = QString( "REPACK %1" ).arg( layerName ); // don't quote the layer name as it works with spaces in the name and won't work if the name is quoted
OGR_DS_ExecuteSQL( ogrDataSource, mEncoding->fromUnicode( sql ).data(), NULL, NULL );
featuresCounted = OGR_L_GetFeatureCount( ogrLayer, TRUE ); //new feature count
return returnvalue;
}
bool QgsOgrProvider::deleteFeature( int id )
{
OGRErr res = OGR_L_DeleteFeature( ogrLayer, id );
return ( res == OGRERR_NONE );
}
int QgsOgrProvider::capabilities() const
{
int ability = NoCapabilities;
// collect abilities reported by OGR
if ( ogrLayer )
{
// Whilst the OGR documentation (e.g. at
// http://www.gdal.org/ogr/classOGRLayer.html#a17) states "The capability
// codes that can be tested are represented as strings, but #defined
// constants exists to ensure correct spelling", we always use strings
// here. This is because older versions of OGR don't always have all
// the #defines we want to test for here.
if ( OGR_L_TestCapability( ogrLayer, "RandomRead" ) )
// TRUE if the GetFeature() method works *efficiently* for this layer.
// TODO: Perhaps influence if QGIS caches into memory
// (vs read from disk every time) based on this setting.
{
// the latter flag is here just for compatibility
ability |= QgsVectorDataProvider::SelectAtId | QgsVectorDataProvider::SelectGeometryAtId;