-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgsshapefile.cpp
456 lines (404 loc) · 13.5 KB
/
qgsshapefile.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
/***************************************************************************
qgsshapefile.cpp - description
-------------------
begin : Fri Dec 19 2003
copyright : (C) 2003 by Denis Antipov
email :
***************************************************************************/
/***************************************************************************
* *
* 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 <QApplication>
#include <ogr_api.h>
#include <cpl_conv.h>
#include <QFile>
#include <QProgressDialog>
#include <QString>
#include <QLabel>
#include <QTextCodec>
#include <QFileInfo>
#include "qgsapplication.h"
#include "cpl_error.h"
#include "qgsshapefile.h"
#include "qgis.h"
#include "qgslogger.h"
#include "qgspgutil.h"
#if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1800
#define TO8F(x) (x).toUtf8().constData()
#else
#define TO8F(x) QFile::encodeName( x ).constData()
#endif
QgsShapeFile::QgsShapeFile( QString name, QString encoding )
{
fileName = name;
features = 0;
QgsApplication::registerOgrDrivers();
ogrDataSource = OGROpen( TO8F( fileName ), false, NULL );
if ( ogrDataSource != NULL )
{
valid = true;
ogrLayer = OGR_DS_GetLayer( ogrDataSource, 0 );
features = OGR_L_GetFeatureCount( ogrLayer, true );
}
else
valid = false;
setDefaultTable();
// init the geometry types
geometries << "NULL" << "POINT" << "LINESTRING" << "POLYGON" << "MULTIPOINT"
<< "MULTILINESTRING" << "MULTIPOLYGON" << "GEOMETRYCOLLECTION";
codec = QTextCodec::codecForName( encoding.toLocal8Bit().data() );
if ( !codec )
codec = QTextCodec::codecForLocale();
}
QgsShapeFile::~QgsShapeFile()
{
OGR_DS_Destroy( ogrDataSource );
}
int QgsShapeFile::getFeatureCount()
{
return features;
}
bool QgsShapeFile::scanGeometries()
{
QProgressDialog *sg = new QProgressDialog();
sg->setMinimum( 0 );
sg->setMaximum( 0 );
QString label = tr( "Scanning " );
label += fileName;
sg->setLabel( new QLabel( label ) );
sg->show();
qApp->processEvents();
OGRFeatureH feat;
OGRwkbGeometryType currentType = wkbUnknown;
bool multi = false;
while (( feat = OGR_L_GetNextFeature( ogrLayer ) ) )
{
qApp->processEvents();
// feat->DumpReadable(NULL);
OGRGeometryH geom = OGR_F_GetGeometryRef( feat );
if ( geom )
{
QString gml = OGR_G_ExportToGML( geom );
// QgsDebugMsg(gml);
if ( gml.indexOf( "gml:Multi" ) > -1 )
{
// QgsDebugMsg("MULTI Part Feature detected");
multi = true;
}
OGRFeatureDefnH fDef = OGR_F_GetDefnRef( feat );
OGRwkbGeometryType gType = OGR_FD_GetGeomType( fDef );
// QgsDebugMsg(gType);
if ( gType > currentType )
{
currentType = gType;
}
if ( gType < currentType )
{
QgsDebugMsg( QString( "Encountered inconsistent geometry type %1" ).arg( gType ) );
}
}
}
// a hack to support 2.5D geometries (their wkb is equivalent to 2D variants
// except that the highest bit is set also). For now we will ignore 3rd coordinate.
hasMoreDimensions = false;
if ( currentType & wkb25DBit )
{
QgsDebugMsg( "Got a shapefile with 2.5D geometry." );
currentType = wkbFlatten( currentType );
hasMoreDimensions = true;
}
OGR_L_ResetReading( ogrLayer );
geom_type = geometries[currentType];
if ( multi && ( geom_type.indexOf( "MULTI" ) == -1 ) )
{
geom_type = "MULTI" + geom_type;
}
delete sg;
// QgsDebugMsg(QString("Geometry type is %1 (%2)").arg(currentType).arg(geometries[currentType]));
return multi;
}
QString QgsShapeFile::getFeatureClass()
{
// scan the whole layer to try to determine the geometry
// type.
qApp->processEvents();
isMulti = scanGeometries();
OGRFeatureH feat;
// skip features without geometry
while (( feat = OGR_L_GetNextFeature( ogrLayer ) ) != NULL )
{
if ( OGR_F_GetGeometryRef( feat ) )
break;
}
if ( feat )
{
OGRGeometryH geom = OGR_F_GetGeometryRef( feat );
if ( geom )
{
/* OGR doesn't appear to report geometry type properly
* for a layer containing both polygon and multipolygon
* entities
*
// get the feature type from the layer
OGRFeatureDefn * gDef = ogrLayer->GetLayerDefn();
OGRwkbGeometryType gType = gDef->GetGeomType();
geom_type = QGis::qgisFeatureTypes[gType];
*/
//geom_type = QString(geom->getGeometryName());
//geom_type = "GEOMETRY";
QgsDebugMsg( "Preparing to escape " + geom_type );
char * esc_str = new char[geom_type.length()*2+1];
PQescapeString( esc_str, geom_type.toUtf8(), geom_type.length() );
geom_type = QString( esc_str );
QgsDebugMsg( "After escaping, geom_type is : " + geom_type );
delete[] esc_str;
int numFields = OGR_F_GetFieldCount( feat );
for ( int n = 0; n < numFields; n++ )
{
OGRFieldDefnH fld = OGR_F_GetFieldDefnRef( feat, n );
column_names.push_back( codec->toUnicode( OGR_Fld_GetNameRef( fld ) ) );
switch ( OGR_Fld_GetType( fld ) )
{
case OFTInteger:
column_types.push_back( "int" );
break;
case OFTReal:
column_types.push_back( "float" );
break;
case OFTString:
column_types.push_back( QString( "varchar(%1)" ).arg( OGR_Fld_GetWidth( fld ) ) );
break;
case OFTDate:
column_types.push_back( "date" );
break;
case OFTTime:
column_types.push_back( "time" );
break;
case OFTDateTime:
column_types.push_back( "timestamp" );
break;
default:
column_types.push_back( "varchar(256)" );
break;
}
}
}
else valid = false;
OGR_F_Destroy( feat );
}
else valid = false;
OGR_L_ResetReading( ogrLayer );
return valid ? geom_type : QString::null;
}
bool QgsShapeFile::is_valid()
{
return valid;
}
QString QgsShapeFile::getName()
{
return fileName;
}
QString QgsShapeFile::getTable()
{
return table_name;
}
void QgsShapeFile::setTable( QString new_table )
{
new_table.replace( "\'", "\\'" );
new_table.replace( "\\", "\\\\" );
table_name = new_table;
}
void QgsShapeFile::setDefaultTable()
{
QFileInfo fi( fileName );
table_name = fi.baseName();
}
void QgsShapeFile::setColumnNames( QStringList columns )
{
column_names.clear();
for ( QStringList::Iterator it = columns.begin(); it != columns.end(); ++it )
{
column_names.push_back( *it );
}
}
bool QgsShapeFile::insertLayer( QString dbname, QString schema, QString primary_key, QString geom_col,
QString srid, PGconn * conn, QProgressDialog& pro, bool &fin,
QString& errorText )
{
connect( &pro, SIGNAL( canceled() ), this, SLOT( cancelImport() ) );
import_canceled = false;
bool result = true;
QString query = QString( "CREATE TABLE %1.%2(%3 SERIAL PRIMARY KEY" )
.arg( QgsPgUtil::quotedIdentifier( schema ) )
.arg( QgsPgUtil::quotedIdentifier( table_name ) )
.arg( QgsPgUtil::quotedIdentifier( primary_key ) );
for ( uint n = 0; n < column_names.size() && result; n++ )
{
query += QString( ",%1 %2" )
.arg( QgsPgUtil::quotedIdentifier( column_names[n] ) )
.arg( column_types[n] );
}
query += " )";
QgsDebugMsg( "Query string is: " + query );
PGresult *res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
// flag error and send query and error message to stdout on debug
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
else
{
PQclear( res );
}
query = QString( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,2)" )
.arg( QgsPgUtil::quotedValue( schema ) )
.arg( QgsPgUtil::quotedValue( table_name ) )
.arg( QgsPgUtil::quotedValue( geom_col ) )
.arg( srid )
.arg( QgsPgUtil::quotedValue( geom_type ) );
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK )
{
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
else
{
PQclear( res );
}
if ( isMulti )
{
query = QString( "select constraint_name from information_schema.table_constraints where table_schema=%1 and table_name=%2 and constraint_name in ('$2','enforce_geotype_the_geom')" )
.arg( QgsPgUtil::quotedValue( schema ) )
.arg( QgsPgUtil::quotedValue( table_name ) );
QStringList constraints;
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) == PGRES_TUPLES_OK )
{
for ( int i = 0; i < PQntuples( res ); i++ )
constraints.append( PQgetvalue( res, i, 0 ) );
}
PQclear( res );
if ( constraints.size() > 0 )
{
// drop the check constraint
// TODO This whole concept needs to be changed to either
// convert the geometries to the same type or allow
// multiple types in the check constraint. For now, we
// just drop the constraint...
query = QString( "alter table %1 drop constraint %2" )
.arg( QgsPgUtil::quotedIdentifier( table_name ) )
.arg( QgsPgUtil::quotedIdentifier( constraints[0] ) );
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
PQclear( res );
}
}
//adding the data into the table
for ( int m = 0; m < features && result; m++ )
{
if ( import_canceled )
{
fin = true;
break;
}
OGRFeatureH feat = OGR_L_GetNextFeature( ogrLayer );
if ( feat )
{
OGRGeometryH geom = OGR_F_GetGeometryRef( feat );
if ( geom )
{
query = QString( "INSERT INTO %1.%2(" )
.arg( QgsPgUtil::quotedIdentifier( schema ) )
.arg( QgsPgUtil::quotedIdentifier( table_name ) );
QString values = " VALUES (";
char *geo_temp;
// 'GeometryFromText' supports only 2D coordinates
// TODO for proper 2.5D support we would need to use 'GeomFromEWkt'
if ( hasMoreDimensions )
OGR_G_SetCoordinateDimension( geom, 2 );
OGR_G_ExportToWkt( geom, &geo_temp );
QString geometry( geo_temp );
CPLFree( geo_temp );
for ( uint n = 0; n < column_types.size(); n++ )
{
QString val;
// FIXME: OGR_F_GetFieldAsString returns junk when called with a 8.255 float field
if ( column_types[n] == "float" )
val = QString::number( OGR_F_GetFieldAsDouble( feat, n ) );
else
val = codec->toUnicode( OGR_F_GetFieldAsString( feat, n ) );
if ( val.isEmpty() )
val = "NULL";
else
val = QgsPgUtil::quotedValue( val );
if ( n > 0 )
{
query += ",";
values += ",";
}
query += QgsPgUtil::quotedIdentifier( column_names[n] );
values += val;
}
query += "," + QgsPgUtil::quotedIdentifier( geom_col );
values += QString( ",st_geometryfromtext(%1,%2)" )
.arg( QgsPgUtil::quotedValue( geometry ) )
.arg( srid );
query += ")" + values + ")";
if ( result )
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
// flag error and send query and error message to stdout on debug
result = false;
errorText += tr( "The database gave an error while executing this SQL:" ) + "\n";
// the query string can be quite long. Trim if necessary...
if ( query.count() > 100 )
errorText += query.left( 150 ) +
tr( "... (rest of SQL trimmed)", "is appended to a truncated SQL statement" ) +
"\n";
else
errorText += query + '\n';
errorText += tr( "The error was:\n%1\n" ).arg( PQresultErrorMessage( res ) );
errorText += '\n';
}
else
{
PQclear( res );
}
pro.setValue( pro.value() + 1 );
qApp->processEvents();
}
OGR_F_Destroy( feat );
}
}
// create the GIST index if the the load was successful
if ( result )
{
// prompt user to see if they want to build the index and warn
// them about the potential time-cost
}
OGR_L_ResetReading( ogrLayer );
return result;
}
void QgsShapeFile::cancelImport()
{
import_canceled = true;
}