/
qgsspit.cpp
885 lines (808 loc) · 30.9 KB
/
qgsspit.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
/***************************************************************************
qgsspit.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 <QMessageBox>
#include <QComboBox>
#include <QFileDialog>
#include <QProgressDialog>
#include <QRegExp>
#include <QFile>
#include <QSettings>
#include <QPixmap>
#include <QHeaderView>
#include <iostream>
#include "qgspgutil.h"
#include "qgsspit.h"
#include "qgsconnectiondialog.h"
#include "qgseditreservedwordsdialog.h"
#include "qgsmessageviewer.h"
#include "spiticon.xpm"
#include "spit_icons.h"
// Qt implementation of alignment() + changed the numeric types to be shown on the left as well
/* Is this still needed? Numbers in Qt4 table seem to be left justified by default.
int Q3TableItem::alignment() const
{
bool num;
bool ok1 = FALSE, ok2 = FALSE;
( void ) txt.toInt( &ok1 );
if ( !ok1 )
( void ) txt.toDouble( &ok2 );
num = ok1 || ok2;
return ( num ? Qt::AlignLeft : Qt::AlignLeft ) | Qt::AlignVCenter;
}
*/
QgsSpit::QgsSpit( QWidget *parent, Qt::WFlags fl ) : QDialog( parent, fl )
{
setupUi(this);
QPixmap icon;
icon = QPixmap( spitIcon );
setIcon( icon );
// Set up the table column headers
tblShapefiles->setColumnCount(5);
QStringList headerText;
headerText << tr("File Name") << tr("Feature Class") << tr("Features")
<< tr("DB Relation Name") << tr("Schema");
tblShapefiles->setHorizontalHeaderLabels(headerText);
tblShapefiles->verticalHeader()->hide();
tblShapefiles->horizontalHeader()->setStretchLastSection(true);
populateConnectionList();
defSrid = -1;
defGeom = "the_geom";
total_features = 0;
chkUseDefaultSrid->setChecked( true );
chkUseDefaultGeom->setChecked( true );
useDefaultSrid();
useDefaultGeom();
schema_list << "public";
gl_key = "/PostgreSQL/connections/";
getSchema();
// Install a delegate that provides the combo box widget for
// changing the schema (but there can only be one delegate per
// table, so it also provides edit widgets for the textual columns).
// This needs to be done after the call to getSchema() so that
// schema_list is populated.
ShapefileTableDelegate* delegate = new ShapefileTableDelegate(tblShapefiles, schema_list);
tblShapefiles->setItemDelegate(delegate);
// Now that everything is in the table, adjust the column sizes
tblShapefiles->resizeColumnsToContents();
}
QgsSpit::~QgsSpit()
{}
void QgsSpit::populateConnectionList()
{
QSettings settings("QuantumGIS", "qgis");
QStringList keys = settings.subkeyList( "/PostgreSQL/connections" );
QStringList::Iterator it = keys.begin();
cmbConnections->clear();
while ( it != keys.end() )
{
cmbConnections->insertItem( *it );
++it;
}
}
void QgsSpit::newConnection()
{
QgsConnectionDialog * con = new QgsConnectionDialog( this, "New Connection" );
if ( con->exec() )
{
populateConnectionList();
getSchema();
}
}
void QgsSpit::editConnection()
{
QgsConnectionDialog * con = new QgsConnectionDialog( this, cmbConnections->currentText() );
if ( con->exec() )
{
con->saveConnection();
getSchema();
}
}
void QgsSpit::removeConnection()
{
QSettings settings("QuantumGIS", "qgis");
QString key = "/PostgreSQL/connections/" + cmbConnections->currentText();
QString msg = tr("Are you sure you want to remove the [") + cmbConnections->currentText() + tr("] connection and all associated settings?");
int result = QMessageBox::information( this, tr("Confirm Delete"), msg, tr("Yes"), tr("No") );
if ( result == 0 )
{
settings.removeEntry( key + "/host" );
settings.removeEntry( key + "/database" );
settings.removeEntry( key + "/port" );
settings.removeEntry( key + "/username" );
settings.removeEntry( key + "/password" );
settings.removeEntry( key + "/save" );
cmbConnections->removeItem( cmbConnections->currentItem() );
getSchema();
}
}
void QgsSpit::addFile()
{
QString error1 = "";
QString error2 = "";
bool exist;
bool is_error = false;
QSettings settings("QuantumGIS", "qgis");
QStringList files = QFileDialog::getOpenFileNames(this,
"Add Shapefiles",
settings.readEntry( "/Plugin-Spit/last_directory" ),
"Shapefiles (*.shp);;All files (*.*)" );
if ( files.size() > 0 )
{
// Save the directory for future use
QFileInfo fi( files[ 0 ] );
settings.writeEntry( "/Plugin-Spit/last_directory", fi.dirPath( true ) );
}
// Process the files
for ( QStringList::Iterator it = files.begin(); it != files.end(); ++it )
{
exist = false;
is_error = false;
// Check to ensure that we don't insert the same file twice
QList<QTableWidgetItem*> items = tblShapefiles->findItems(*it,
Qt::MatchExactly);
if (items.count() > 0)
{
exist = true;
}
if ( !exist )
{
// check other files: file.dbf and file.shx
QString name = *it;
if ( !QFile::exists( name.left( name.length() - 3 ) + "dbf" ) )
{
is_error = true;
}
else if ( !QFile::exists( name.left( name.length() - 3 ) + "shx" ) )
{
is_error = true;
}
if ( !is_error )
{
QgsShapeFile * file = new QgsShapeFile( name );
if ( file->is_valid() )
{
/* XXX getFeatureClass actually does a whole bunch
* of things and is probably better named
* something else
*/
QString featureClass = file->getFeatureClass();
fileList.push_back( file );
QTableWidgetItem *filenameItem = new QTableWidgetItem( name );
QTableWidgetItem *featureClassItem = new QTableWidgetItem( featureClass );
QTableWidgetItem *featureCountItem = new QTableWidgetItem( QString( "%1" ).arg( file->getFeatureCount() ) );
// Sanitize the relation name to make it pg friendly
QString relName = file->getTable().replace(QRegExp("\\s"), "_");
QTableWidgetItem *dbRelationNameItem = new QTableWidgetItem( relName );
QTableWidgetItem *dbSchemaNameItem = new QTableWidgetItem( cmbSchema->currentText() );
// All items are editable except for these two
filenameItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
featureCountItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
int row = tblShapefiles->rowCount();
tblShapefiles->insertRow( row );
tblShapefiles->setItem( row, ColFILENAME, filenameItem );
tblShapefiles->setItem( row, ColFEATURECLASS, featureClassItem );
tblShapefiles->setItem( row, ColFEATURECOUNT, featureCountItem );
tblShapefiles->setItem( row, ColDBRELATIONNAME, dbRelationNameItem );
tblShapefiles->setItem( row, ColDBSCHEMA, dbSchemaNameItem );
total_features += file->getFeatureCount();
// check for postgresql reserved words
// First get an instance of the PG utility class
QgsPgUtil *pgu = QgsPgUtil::instance();
bool hasReservedWords = false;
// if a reserved word is found, set the flag so the "adjustment"
// dialog can be presented to the user
hasReservedWords = false;
for ( int i = 0; i < file->column_names.size(); i++ )
{
if ( pgu->isReserved( file->column_names[ i ] ) )
{
hasReservedWords = true;
}
}
// Why loop through all of them and then turn around and test
// the flag? Because if there are reserved words, we want to
// add all columns to the listview so the user can have the
// opportunity to change them.
if ( hasReservedWords )
{
// show the dialog for adjusting reserved words. Reserved
// words are displayed differently so they are easy to spot
QgsEditReservedWordsDialog * srw = new QgsEditReservedWordsDialog( this );
srw->setCaption( file->getTable().upper() + tr(" - Edit Column Names") );
// load the reserved words list
srw->setReservedWords( pgu->reservedWords() );
// load the columns and set their status
for ( int i = 0; i < file->column_names.size(); i++ )
{
srw->addColumn( file->column_names[ i ],
pgu->isReserved( file->column_names[ i ] ), i );
}
if ( srw->exec() )
{
// get the new column specs from the listview control
// and replace the existing column spec for the shapefile
file->setColumnNames( srw->columnNames() );
}
}
}
else
{
error1 += name + "\n";
is_error = true;
delete file;
}
}
else
{
error2 += name + "\n";
}
}
}
tblShapefiles->resizeColumnsToContents();
if ( error1 != "" || error2 != "" )
{
QString message = tr("The following Shapefile(s) could not be loaded:\n\n");
if ( error1 != "" )
{
error1 += "----------------------------------------------------------------------------------------";
error1 += "\n" + tr("REASON: File cannot be opened") + "\n\n";
}
if ( error2 != "" )
{
error2 += "----------------------------------------------------------------------------------------";
error2 += "\n" + tr("REASON: One or both of the Shapefile files (*.dbf, *.shx) missing") + "\n\n";
}
QgsMessageViewer * e = new QgsMessageViewer( this );
e->setMessage( message + error1 + error2 );
e->exec();
}
}
void QgsSpit::removeFile()
{
std::vector <int> temp;
for ( int n = 0; n < tblShapefiles->rowCount(); n++ )
if ( tblShapefiles->isItemSelected( tblShapefiles->item( n, 0 ) ) )
{
for ( std::vector<QgsShapeFile *>::iterator vit = fileList.begin(); vit != fileList.end(); vit++ )
{
if ( ( *vit ) ->getName() == tblShapefiles->item( n, 0 )->text() )
{
total_features -= ( *vit ) ->getFeatureCount();
fileList.erase( vit );
temp.push_back( n );
break;
}
}
}
for ( int i = temp.size()-1; i >= 0; --i )
tblShapefiles->removeRow( temp[ i ] );
tblShapefiles->setCurrentCell( -1, 0 );
}
void QgsSpit::removeAllFiles()
{
int i = tblShapefiles->rowCount() - 1;
for (; i >= 0; --i)
tblShapefiles->removeRow(i);
fileList.clear();
total_features = 0;
}
void QgsSpit::useDefaultSrid()
{
if ( chkUseDefaultSrid->isChecked() )
{
defaultSridValue = spinSrid->value();
spinSrid->setValue( defSrid );
spinSrid->setEnabled( false );
}
else
{
spinSrid->setEnabled( true );
spinSrid->setValue( defaultSridValue );
}
}
void QgsSpit::useDefaultGeom()
{
if ( chkUseDefaultGeom->isChecked() )
{
defaultGeomValue = txtGeomName->text();
txtGeomName->setText( defGeom );
txtGeomName->setEnabled( false );
}
else
{
txtGeomName->setEnabled( true );
txtGeomName->setText( defaultGeomValue );
}
}
// TODO: make translation of helpinfo
void QgsSpit::helpInfo()
{
QString message = tr("General Interface Help:") + "\n\n";
message += QString(
tr("PostgreSQL Connections:") + "\n" ) + QString(
"----------------------------------------------------------------------------------------\n" ) + QString(
tr("[New ...] - create a new connection") + "\n" ) + QString(
tr("[Edit ...] - edit the currently selected connection") + "\n" ) + QString(
tr("[Remove] - remove the currently selected connection") + "\n" ) + QString(
tr("-you need to select a connection that works (connects properly) in order to import files") + "\n" ) + QString(
tr("-when changing connections Global Schema also changes accordingly") + "\n\n" ) + QString(
tr("Shapefile List:") + "\n" ) + QString(
"----------------------------------------------------------------------------------------\n" ) + QString(
tr("[Add ...] - open a File dialog and browse to the desired file(s) to import") + "\n" ) + QString(
tr("[Remove] - remove the currently selected file(s) from the list") + "\n" ) + QString(
tr("[Remove All] - remove all the files in the list") + "\n" ) + QString(
tr("[SRID] - Reference ID for the shapefiles to be imported") + "\n" ) + QString(
tr("[Use Default (SRID)] - set SRID to -1") + "\n" ) + QString(
tr("[Geometry Column Name] - name of the geometry column in the database") + "\n" ) + QString(
tr("[Use Default (Geometry Column Name)] - set column name to \'the_geom\'") + "\n" ) + QString(
tr("[Glogal Schema] - set the schema for all files to be imported into") + "\n\n" ) + QString(
"----------------------------------------------------------------------------------------\n" ) + QString(
tr("[Import] - import the current shapefiles in the list") + "\n" ) + QString(
tr("[Quit] - quit the program\n") ) + QString(
tr("[Help] - display this help dialog") + "\n\n" );
QgsMessageViewer * e = new QgsMessageViewer( this );
e->setMessage( message );
e->exec();
}
PGconn* QgsSpit::checkConnection()
{
QSettings settings("QuantumGIS", "qgis");
PGconn * pd;
bool result = true;
QString connName = cmbConnections->currentText();
if ( connName.isEmpty() )
{
QMessageBox::warning( this, tr("Import Shapefiles"), tr("You need to specify a Connection first") );
result = false;
}
else
{
QString connInfo = "host=" + settings.readEntry( gl_key + connName + "/host" ) +
" dbname=" + settings.readEntry( gl_key + connName + "/database" ) +
" port=" + settings.readEntry( gl_key + connName + "/port" ) +
" user=" + settings.readEntry( gl_key + connName + "/username" ) +
" password=" + settings.readEntry( gl_key + connName + "/password" );
pd = PQconnectdb( ( const char * ) connInfo );
if ( PQstatus( pd ) != CONNECTION_OK )
{
QMessageBox::warning( this, tr("Import Shapefiles"), tr("Connection failed - Check settings and try again") );
result = false;
}
}
if ( result )
return pd;
else
return NULL;
}
void QgsSpit::getSchema()
{
QSettings settings("QuantumGIS", "qgis");
schema_list.clear();
schema_list << "public";
PGconn* pd = checkConnection();
if ( pd != NULL )
{
QString connName = cmbConnections->currentText();
QString user = settings.readEntry( gl_key + connName + "/username" );
QString schemaSql = QString( "select nspname from pg_namespace,pg_user where nspowner = usesysid and usename = '%1'" ).arg( user );
PGresult *schemas = PQexec( pd, ( const char * ) schemaSql );
// get the schema names
if ( PQresultStatus( schemas ) == PGRES_TUPLES_OK )
{
for ( int i = 0; i < PQntuples( schemas ); i++ )
{
if ( QString( PQgetvalue( schemas, i, 0 ) ) != "public" )
schema_list << QString( PQgetvalue( schemas, i, 0 ) );
}
}
PQclear( schemas );
}
PQfinish(pd);
// install a new delegate with an updated schema list (rather than
// update the existing delegate because delegates don't seem able to
// store modifiable data).
ShapefileTableDelegate* delegate = new ShapefileTableDelegate(tblShapefiles, schema_list);
tblShapefiles->setItemDelegate(delegate);
cmbSchema->clear();
cmbSchema->insertItems( 0, schema_list );
cmbSchema->setCurrentIndex( 0 ); // index 0 is always "public"
}
void QgsSpit::updateSchema()
{
// install a new delegate with an updated schema list (rather than
// update the existing delegate because delegates don't seem able to
// store modifiable data).
ShapefileTableDelegate* delegate = new ShapefileTableDelegate(tblShapefiles, schema_list);
tblShapefiles->setItemDelegate(delegate);
}
void QgsSpit::import()
{
tblShapefiles->setCurrentCell( -1, 0 );
QString connName = cmbConnections->currentText();
QSettings settings("QuantumGIS", "qgis");
bool cancelled = false;
PGconn* pd = checkConnection();
QString query;
if ( total_features == 0 )
{
QMessageBox::warning( this, tr("Import Shapefiles"),
tr("You need to add shapefiles to the list first") );
}
else if ( pd != NULL )
{
PGresult * res;
QProgressDialog pro( tr("Importing files"), tr("Cancel"),
0, total_features, this);
pro.setValue( 0 );
pro.setLabelText(tr("Progress"));
pro.setAutoClose( true );
//pro->show();
qApp->processEvents();
for ( int i = 0; i < fileList.size() ; i++ )
{
QString error = tr("Problem inserting features from file:") + "\n" +
tblShapefiles->item( i, ColFILENAME )->text();
// if a name starts with invalid character
if ( ! tblShapefiles->item( i, ColDBRELATIONNAME )->text()[ 0 ].isLetter() )
{
QMessageBox::warning( &pro, tr("Import Shapefiles"),
error + "\n" + tr("Invalid table name.") );
pro.setValue( pro.value()
+ tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
// if no fields detected
if ( ( fileList[ i ] ->column_names ).size() == 0 )
{
QMessageBox::warning( &pro, tr("Import Shapefiles"),
error + "\n" + tr("No fields detected.") );
pro.setValue( pro.value() +
tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
// duplicate field check
std::vector<QString> names_copy = fileList[ i ] ->column_names;
std::cerr << "Size of names_copy before sort: " << names_copy.size() << std::endl;
QString dupl = "";
std::sort( names_copy.begin(), names_copy.end() );
std::cerr << "Size of names_copy after sort: " << names_copy.size() << std::endl;
for ( int k = 1; k < names_copy.size(); k++ )
{
std::cerr << "USING :" << names_copy[ k ].toLocal8Bit().data() << " index " << k << std::endl;
qWarning( "Checking to see if " + names_copy[ k ] + " == " + names_copy[ k - 1 ] );
if ( names_copy[ k ] == names_copy[ k - 1 ] )
dupl += names_copy[ k ] + "\n";
}
// if duplicate field names exist
if ( dupl != "" )
{
QMessageBox::warning( &pro, tr("Import Shapefiles"), error +
"\n" + tr("The following fields are duplicates:") + "\n" + dupl );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
// Check and set destination table
fileList[ i ] ->setTable( tblShapefiles->item( i, ColDBRELATIONNAME )->text() );
pro.setLabelText( tr("Importing files") + "\n"
+ tblShapefiles->item(i, ColFILENAME)->text() );
bool rel_exists1 = false;
bool rel_exists2 = false;
query = "SELECT f_table_name FROM geometry_columns WHERE f_table_name=\'"
+ tblShapefiles->item( i, ColDBRELATIONNAME )->text() +
"\' AND f_table_schema=\'"
+ tblShapefiles->item( i, ColDBSCHEMA )->text() + "\'";
res = PQexec( pd, ( const char * ) query );
rel_exists1 = ( PQntuples( res ) > 0 );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
query = "SELECT tablename FROM pg_tables WHERE tablename=\'" + tblShapefiles->item( i, ColDBRELATIONNAME )->text() + "\' AND schemaname=\'" +
tblShapefiles->item( i, ColDBSCHEMA )->text() + "\'";
res = PQexec( pd, ( const char * ) query );
qWarning( query );
rel_exists2 = ( PQntuples( res ) > 0 );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
// begin session
query = "BEGIN";
res = PQexec( pd, query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
query = "SET SEARCH_PATH TO \'";
if ( tblShapefiles->item( i, ColDBSCHEMA )->text() == "public" )
query += "public\'";
else
query += tblShapefiles->item( i, ColDBSCHEMA )->text() + "\', \'public\'";
res = PQexec( pd, query );
qWarning( query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
qWarning( PQresStatus( PQresultStatus( res ) ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
QMessageBox *del_confirm;
if ( rel_exists1 || rel_exists2 )
{
del_confirm = new QMessageBox( tr("Import Shapefiles - Relation Exists"),
tr("The Shapefile:" ) + "\n" + tblShapefiles->item( i, 0 )->text() + "\n" + tr("will use [") +
tblShapefiles->item( i, ColDBRELATIONNAME )->text() + tr("] relation for its data,") + "\n" + tr("which already exists and possibly contains data.") + "\n" +
tr("To avoid data loss change the \"DB Relation Name\"") + "\n" + tr("for this Shapefile in the main dialog file list.") + "\n\n" +
tr("Do you want to overwrite the [") + tblShapefiles->item( i, ColDBRELATIONNAME )->text() + tr("] relation?"),
QMessageBox::Warning,
QMessageBox::Yes | QMessageBox::Default,
QMessageBox::No | QMessageBox::Escape,
Qt::NoButton,
this
// tr("Relation Exists")
);
if ( del_confirm->exec() == QMessageBox::Yes )
{
if ( rel_exists2 )
{
query = "DROP TABLE " + tblShapefiles->item( i, ColDBRELATIONNAME )->text();
qWarning( query );
res = PQexec( pd, ( const char * ) query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
}
if ( rel_exists1 )
{
/*query = "SELECT DropGeometryColumn(\'"+QString(settings.readEntry(key + "/database"))+"\', \'"+
fileList[i]->getTable()+"\', \'"+txtGeomName->text()+"')";*/
query = "DELETE FROM geometry_columns WHERE f_table_schema=\'" + tblShapefiles->item( i, ColDBSCHEMA )->text() + "\' AND " +
"f_table_name=\'" + tblShapefiles->item( i, ColDBRELATIONNAME )->text() + "\'";
qWarning( query );
res = PQexec( pd, ( const char * ) query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
pro.setValue( pro.value() + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
continue;
}
else
{
PQclear( res );
}
}
}
else
{
query = "ROLLBACK";
res = PQexec( pd, query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
}
else
{
PQclear( res );
}
pro.setValue( pro.value() + tblShapefiles->item( i, 2 )->text().toInt() );
continue;
}
}
// importing file here
int temp_progress = pro.value();
cancelled = false;
if ( fileList[ i ] ->insertLayer( settings.readEntry( gl_key + connName + "/database" ), tblShapefiles->item( i, ColDBSCHEMA )->text(),
txtGeomName->text(), QString( "%1" ).arg( spinSrid->value() ), pd, pro, cancelled ) && !cancelled )
{ // if file has been imported successfully
query = "COMMIT";
res = PQexec( pd, query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
continue;
}
else
{
PQclear( res );
}
// remove file
for ( int j = 0; j < tblShapefiles->rowCount(); j++ )
{
if ( tblShapefiles->item( j, ColFILENAME )->text() == QString( fileList[ i ] ->getName() ) )
{
tblShapefiles->selectRow( j );
removeFile();
i--;
break;
}
}
}
else if ( !cancelled )
{ // if problem importing file occured
pro.setValue( temp_progress + tblShapefiles->item( i, ColFEATURECOUNT )->text().toInt() );
QMessageBox::warning( this, tr("Import Shapefiles"), error );
query = "ROLLBACK";
res = PQexec( pd, query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
qWarning( PQresultErrorMessage( res ) );
QMessageBox::warning( &pro, tr("Import Shapefiles"), error );
}
else
{
PQclear( res );
}
}
else
{ // if import was actually cancelled
break;
}
}
}
PQfinish( pd );
}
void QgsSpit::editColumns( int row, int col, int button, const QPoint &mousePos )
{
// get the shapefile - table row maps directly to the fileList array
QgsPgUtil * pgu = QgsPgUtil::instance();
// show the dialog for adjusting reserved words. Reserved
// words are displayed differently so they are easy to spot
QgsEditReservedWordsDialog *srw = new QgsEditReservedWordsDialog( this );
srw->setCaption( fileList[ row ] ->getTable().upper() + tr(" - Edit Column Names") );
// set the description to indicate that we are editing column names, not
// necessarily dealing with reserved words (although that is a possibility too)
srw->setDescription(tr("Use the table below to edit column names. Make sure that none of the columns are named using a PostgreSQL reserved word"));
// load the reserved words list
srw->setReservedWords( pgu->reservedWords() );
// load the columns and set their status
for ( int i = 0; i < fileList[ row ] ->column_names.size(); i++ )
{
srw->addColumn( fileList[ row ] ->column_names[ i ],
pgu->isReserved( fileList[ row ] ->column_names[ i ] ), i );
}
if ( srw->exec() )
{
// get the new column specs from the listview control
// and replace the existing column spec for the shapefile
fileList[ row ] ->setColumnNames( srw->columnNames() );
}
}
void QgsSpit::editShapefile(int row, int col, int button, const QPoint& mousePos)
{
// FIXME Is this necessary any more?
/*
if (ColFEATURECLASS == col || ColDBRELATIONNAME == col)
{
tblShapefiles->editCell(row, col, FALSE);
}
*/
}
QWidget *ShapefileTableDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &,
const QModelIndex & index) const
{
switch(index.column())
{
case 4:
{
QComboBox* editor = new QComboBox(parent);
editor->setSizeAdjustPolicy(QComboBox::AdjustToContents);
editor->installEventFilter(const_cast<ShapefileTableDelegate*>(this));
return editor;
break;
}
case 1:
case 3:
{
QLineEdit* editor = new QLineEdit(parent);
editor->installEventFilter(const_cast<ShapefileTableDelegate*>(this));
return editor;
break;
}
}
}
void ShapefileTableDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
switch(index.column())
{
case 4:
{
// Create a combobox and populate with the list of schemas
QComboBox *comboBox = static_cast<QComboBox*>(editor);
comboBox->insertItems(0, mSchemaList);
// Get the text from the table and use to set the selected text
// in the combo box.
QString text = index.model()->data(index, Qt::DisplayRole).toString();
comboBox->setCurrentIndex(mSchemaList.indexOf(text));
break;
}
case 1:
case 3:
{
QString text = index.model()->data(index, Qt::DisplayRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setText(text);
break;
}
}
}
void ShapefileTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
switch(index.column())
{
case 4:
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString text = comboBox->currentText();
model->setData(index, text);
break;
}
case 1:
case 3:
{
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
QString text = lineEdit->text();
model->setData(index, text);
break;
}
}
}
void ShapefileTableDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}