forked from 3liz/QgisCadastrePlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cadastre_dialogs.py
2862 lines (2448 loc) · 102 KB
/
cadastre_dialogs.py
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Cadastre - Dialog classes
A QGIS plugin
This plugins helps users to import the french land registry ('cadastre')
into a database. It is meant to ease the use of the data in QGIs
by providing search tools and appropriate layer symbology.
-------------------
begin : 2013-06-11
copyright : (C) 2013 by 3liz
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import csv
import os.path
import operator
import re
import tempfile
from qgis.PyQt.QtCore import (
Qt,
pyqtSignal,
QObject,
QSettings,
QRegExp,
QFileInfo,
QStringListModel
)
from qgis.PyQt.QtWidgets import (
QDialog,
QFileDialog,
QApplication,
qApp,
QCompleter,
QDockWidget,
QMessageBox
)
from qgis.PyQt.QtGui import (
QCursor,
QTextCursor,
QPixmap
)
from qgis.PyQt.QtCore import QSortFilterProxyModel
from qgis.core import (
QgsProject,
QgsMessageLog,
QgsLogger,
QgsExpression,
QgsDataSourceUri,
QgsMapLayer,
QgsFeatureRequest,
QgsCoordinateTransform,
QgsCoordinateReferenceSystem,
QgsMapSettings
)
from qgis.gui import (
QgsProjectionSelectionTreeWidget,
QgsProjectionSelectionDialog
)
import unicodedata
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/forms")
# db_manager scripts
from db_manager.db_plugins.plugin import (
DBPlugin,
Schema,
Table,
BaseError
)
from db_manager.db_plugins import createDbPlugin
from db_manager.dlg_db_error import DlgDbError
from db_manager.db_plugins.postgis.connector import PostGisDBConnector
import subprocess
from functools import partial
# --------------------------------------------------------
# import - Import data from EDIGEO and MAJIC files
# --------------------------------------------------------
class cadastre_common(object):
def __init__(self, dialog):
self.dialog = dialog
# plugin directory path
self.plugin_dir = os.path.dirname(os.path.abspath(__file__))
# default auth id for layers
self.defaultAuthId = '2154'
@staticmethod
def hasSpatialiteSupport():
'''
Check whether or not
spatialite support is ok
'''
try:
from db_manager.db_plugins.spatialite.connector import SpatiaLiteDBConnector
return True
except ImportError:
return False
pass
def updateLog(self, msg):
'''
Update the log
'''
t = self.dialog.txtLog
t.ensureCursorVisible()
prefix = '<span style="font-weight:normal;">'
suffix = '</span>'
t.append( '%s %s %s' % (prefix, msg, suffix) )
c = t.textCursor()
c.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
t.setTextCursor(c)
qApp.processEvents()
@staticmethod
def openFile(filename):
'''
Opens a file with default system app
'''
if sys.platform == "win32":
os.startfile(filename)
else:
opener ="open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, filename])
def updateProgressBar(self):
'''
Update the progress bar
'''
if self.dialog.go:
self.dialog.step+=1
self.dialog.pbProcess.setValue(int(self.dialog.step * 100/self.dialog.totalSteps))
qApp.processEvents()
def updateConnectionList(self):
'''
Update the combo box containing the database connection list
'''
QApplication.setOverrideCursor(Qt.WaitCursor)
dbType = str(self.dialog.liDbType.currentText()).lower()
self.dialog.liDbConnection.clear()
if self.dialog.liDbType.currentIndex() != 0:
self.dialog.dbType = dbType
# instance of db_manager plugin class
dbpluginclass = createDbPlugin( dbType )
self.dialog.dbpluginclass = dbpluginclass
# fill the connections combobox
self.dialog.connectionDbList = []
for c in dbpluginclass.connections():
self.dialog.liDbConnection.addItem( str(c.connectionName()))
self.dialog.connectionDbList.append(str(c.connectionName()))
# Show/Hide database specific pannel
if hasattr(self.dialog, 'databaseSpecificOptions'):
if dbType == 'postgis':
self.dialog.databaseSpecificOptions.setCurrentIndex(0)
else:
self.dialog.databaseSpecificOptions.setCurrentIndex(1)
self.toggleSchemaList(False)
else:
if hasattr(self.dialog, "inDbCreateSchema"):
self.dialog.databaseSpecificOptions.setTabEnabled(0, False)
self.dialog.databaseSpecificOptions.setTabEnabled(1, False)
QApplication.restoreOverrideCursor()
def toggleSchemaList(self, t):
'''
Toggle Schema list and inputs
'''
self.dialog.liDbSchema.setEnabled(t)
if hasattr(self.dialog, "inDbCreateSchema"):
self.dialog.inDbCreateSchema.setEnabled(t)
self.dialog.btDbCreateSchema.setEnabled(t)
self.dialog.databaseSpecificOptions.setTabEnabled(0, t)
self.dialog.databaseSpecificOptions.setTabEnabled(1, not t)
self.dialog.btCreateNewSpatialiteDb.setEnabled(not t)
def updateSchemaList(self):
'''
Update the combo box containing the schema list if relevant
'''
self.dialog.liDbSchema.clear()
QApplication.setOverrideCursor(Qt.WaitCursor)
connectionName = str(self.dialog.liDbConnection.currentText())
self.dialog.connectionName = connectionName
dbType = str(self.dialog.liDbType.currentText()).lower()
# Deactivate schema fields
self.toggleSchemaList(False)
connection = None
if connectionName:
# Get schema list
dbpluginclass = createDbPlugin( dbType, connectionName )
self.dialog.dbpluginclass = dbpluginclass
try:
connection = dbpluginclass.connect()
except BaseError as e:
DlgDbError.showError(e, self.dialog)
self.dialog.go = False
self.updateLog(e.msg)
QApplication.restoreOverrideCursor()
return
except:
self.dialog.go = False
msg = u"Impossible de récupérer les schémas de la base. Vérifier les informations de connexion."
self.updateLog(msg)
QApplication.restoreOverrideCursor()
return
finally:
QApplication.restoreOverrideCursor()
if connection:
self.dialog.connection = connection
db = dbpluginclass.database()
if db:
self.dialog.db = db
self.dialog.schemaList = []
if dbType == 'postgis':
# Activate schema fields
self.toggleSchemaList(True)
for s in db.schemas():
self.dialog.liDbSchema.addItem( str(s.name))
self.dialog.schemaList.append(str(s.name))
else:
self.toggleSchemaList(False)
else:
self.toggleSchemaList(False)
QApplication.restoreOverrideCursor()
def checkDatabaseForExistingStructure(self):
'''
Search among a database / schema
if there are alreaday Cadastre structure tables
in it
'''
hasStructure = False
hasData = False
hasMajicData = False
hasMajicDataProp = False
hasMajicDataParcelle = False
hasMajicDataVoie = False
searchTable = u'geo_commune'
majicTableParcelle = u'parcelle'
majicTableProp = u'proprietaire'
majicTableVoie = u'voie'
if self.dialog.db:
if self.dialog.dbType == 'postgis':
schemaSearch = [s for s in self.dialog.db.schemas() if s.name == self.dialog.schema]
schemaInst = schemaSearch[0]
getSearchTable = [a for a in self.dialog.db.tables(schemaInst) if a.name == searchTable]
if self.dialog.dbType == 'spatialite':
getSearchTable = [a for a in self.dialog.db.tables() if a.name == searchTable]
if getSearchTable:
hasStructure = True
# Check for data in it
sql = 'SELECT * FROM "%s" LIMIT 1' % searchTable
if self.dialog.dbType == 'postgis':
sql = cadastre_common.setSearchPath(sql, self.dialog.schema)
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.dialog.db.connector, sql)
if ok and rowCount >= 1:
hasData = True
# Check for Majic data in it
sql = 'SELECT * FROM "%s" LIMIT 1' % majicTableParcelle
if self.dialog.dbType == 'postgis':
sql = cadastre_common.setSearchPath(sql, self.dialog.schema)
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.dialog.db.connector, sql)
if ok and rowCount >= 1:
hasMajicData = True
hasMajicDataParcelle = True
# Check for Majic data in it
sql = 'SELECT * FROM "%s" LIMIT 1' % majicTableProp
if self.dialog.dbType == 'postgis':
sql = cadastre_common.setSearchPath(sql, self.dialog.schema)
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.dialog.db.connector, sql)
if ok and rowCount >= 1:
hasMajicData = True
hasMajicDataProp = True
# Check for Majic data in it
sql = 'SELECT * FROM "%s" LIMIT 1' % majicTableVoie
if self.dialog.dbType == 'postgis':
sql = cadastre_common.setSearchPath(sql, self.dialog.schema)
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.dialog.db.connector, sql)
if ok and rowCount >= 1:
hasMajicData = True
hasMajicDataVoie = True
# Set global properties
self.dialog.hasStructure = hasStructure
self.dialog.hasData = hasData
self.dialog.hasMajicData = hasMajicData
self.dialog.hasMajicDataParcelle = hasMajicDataParcelle
self.dialog.hasMajicDataProp = hasMajicDataProp
self.dialog.hasMajicData = hasMajicDataVoie
def checkDatabaseForExistingTable(self, tableName, schemaName=''):
'''
Check if the given table
exists in the database
'''
tableExists = False
if not self.dialog.db:
return False
if self.dialog.dbType == 'postgis':
sql = "SELECT * FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'" % (schemaName, tableName)
if self.dialog.dbType == 'spatialite':
sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='%s'" % tableName
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.dialog.db.connector, sql)
if ok and rowCount >= 1:
tableExists = True
return tableExists
@staticmethod
def getLayerFromLegendByTableProps(tableName, geomCol='geom', sql=''):
'''
Get the layer from QGIS legend
corresponding to a database
table name (postgis or sqlite)
'''
layer = None
lr = QgsProject.instance()
for lid,l in list(lr.mapLayers().items()):
if not hasattr(l, 'providerType'):
continue
if hasattr(l, 'type') and l.type() != 0:
continue
if not l.providerType() in (u'postgres', u'spatialite'):
continue
connectionParams = cadastre_common.getConnectionParameterFromDbLayer(l)
import re
reg = r'(\.| )?(%s)' % tableName
if connectionParams and \
( \
connectionParams['table'] == tableName or \
( re.findall(reg, '%s' % connectionParams['table']) and re.findall(reg, '%s' % connectionParams['table'])[0] ) \
) and \
connectionParams['geocol'] == geomCol:
#and connectionParams['sql'] == sql:
return l
return layer
@staticmethod
def getConnectionParameterFromDbLayer(layer):
'''
Get connection parameters
from the layer datasource
'''
connectionParams = None
# Get params via regex
uri = layer.dataProvider().dataSourceUri()
reg = "(?:service='([^ ]+)' )?(?:dbname='([^ ]+)' )?(?:host=([^ ]+) )?(?:port=([0-9]+) )?(?:user='([^ ]+)' )?(?:password='([^ ]+)' )?(?:sslmode=([^ ]+) )?(?:key='([^ ]+)' )?(?:estimatedmetadata=([^ ]+) )?(?:checkPrimaryKeyUnicity='([0-1]+)' )?(?:srid=([0-9]+) )?(?:type=([a-zA-Z]+) )?(?:table=\"(.+)\" \()?(?:([^ ]+)\) )?(?:sql=(.*))?"
result = re.findall(r'%s' % reg, uri)
if not result:
print('no result')
return None
res = result[0]
if not res:
return None
service = res[0]
dbname = res[1]
host = res[2]
port = res[3]
user = res[4]
password = res[5]
sslmode = res[6]
key = res[7]
estimatedmetadata = res[8]
checkPrimaryKeyUnicity = res[9]
srid = res[10]
gtype = res[11]
table = res[12]
geocol = res[13]
sql = res[14]
schema = ''
if ' FROM ' not in table:
if re.search('"\."', table):
table = '"' + table + '"'
sp = table.replace('"', '').split('.')
schema = sp[0]
table = sp[1]
else:
reg = r'\* FROM ([^\)]+)?(\))?'
f = re.findall(r'%s' % reg, table)
if f and f[0]:
sp = f[0][0].replace('"', '').split('.')
if len(sp) > 1:
schema = sp[0].replace('\\', '')
table = sp[1]
else:
table = sp[0]
else:
return None
if layer.providerType() == u'postgres':
dbType = 'postgis'
else:
dbType = 'spatialite'
connectionParams = {
'service' : service,
'dbname' : dbname,
'host' : host,
'port': port,
'user' : user,
'password': password,
'sslmode' : sslmode,
'key': key,
'estimatedmetadata' : estimatedmetadata,
'checkPrimaryKeyUnicity' : checkPrimaryKeyUnicity,
'srid' : srid,
'type': gtype,
'schema': schema,
'table' : table,
'geocol' : geocol,
'sql' : sql,
'dbType': dbType
}
return connectionParams
@staticmethod
def setSearchPath(sql, schema):
'''
Set the search_path parameters if postgis database
'''
prefix = u'SET search_path = "%s", public, pg_catalog;' % schema
if re.search('^BEGIN;', sql):
sql = sql.replace('BEGIN;', 'BEGIN;%s' % prefix)
else:
sql = prefix + sql
return sql
@staticmethod
def fetchDataFromSqlQuery(connector, sql, schema=None):
'''
Execute a SQL query and
return [header, data, rowCount]
NB: commit qgis/QGIS@14ab5eb changes QGIS DBmanager behaviour
'''
# print(sql)
data = []
header = []
rowCount = 0
c = None
ok = True
#print "run query"
try:
c = connector._execute(None,str(sql))
data = []
header = connector._get_cursor_columns(c)
if header == None:
header = []
if len(header) > 0:
data = connector._fetchall(c)
rowCount = c.rowcount
if rowCount == -1:
rowCount = len(data)
except UnicodeDecodeError as e:
try:
c = connector._execute(None,str(sql))
data = []
header = connector._get_cursor_columns(c)
if header == None:
header = []
if len(header) > 0:
data = connector._fetchall(c)
rowCount = c.rowcount
if rowCount == -1:
rowCount = len(data)
except BaseError as e:
ok = False
error_message = e.msg
except BaseError as e:
ok = False
error_message = e.msg
finally:
if c:
#print "close connection"
c.close()
del c
# Log errors
if not ok:
print(error_message)
QgsMessageLog.logMessage( "cadastre debug - error while fetching data from database" )
print(sql)
return [header, data, rowCount, ok]
@staticmethod
def getConnectorFromUri(connectionParams):
'''
Set connector property
for the given database type
and parameters
'''
connector = None
uri = QgsDataSourceUri()
if connectionParams['dbType'] == 'postgis':
if connectionParams['host']:
uri.setConnection(
connectionParams['host'],
connectionParams['port'],
connectionParams['dbname'],
connectionParams['user'],
connectionParams['password']
)
if connectionParams['service']:
uri.setConnection(
connectionParams['service'],
connectionParams['dbname'],
connectionParams['user'],
connectionParams['password']
)
connector = PostGisDBConnector(uri)
if connectionParams['dbType'] == 'spatialite':
uri.setConnection('', '', connectionParams['dbname'], '', '')
if cadastre_common.hasSpatialiteSupport():
from db_manager.db_plugins.spatialite.connector import SpatiaLiteDBConnector
connector = SpatiaLiteDBConnector(uri)
return connector
def normalizeString(self, s):
'''
Removes all accents from
the given string and
replace e dans l'o
'''
p = re.compile( '(œ)')
s = p.sub('oe', s)
s=unicodedata.normalize('NFD',s)
s = s.encode('ascii','ignore')
s = s.upper()
s = s.decode().strip(' \t\n')
r = re.compile(r"[^ -~]")
s = r.sub(' ', s)
s = s.replace("'", " ")
return s
@staticmethod
def postgisToSpatialite(sql, targetSrid='2154'):
'''
Convert postgis SQL statement
into spatialite compatible
statements
'''
# delete some incompatible options
# replace other by spatialite syntax
replaceDict = [
# delete
{'in': r'with\(oids=.+\)', 'out': ''},
{'in': r'comment on [^;]+;', 'out': ''},
{'in': r'alter table ([^;]+) add primary key( )+\(([^;]+)\);',
'out': r'create index idx_\1_\3 on \1 (\3);'},
{'in': r'alter table ([^;]+) add constraint [^;]+ primary key( )+\(([^;]+)\);',
'out': r'create index idx_\1_\3 on \1 (\3);'},
{'in': r'alter table [^;]+drop column[^;]+;', 'out': ''},
{'in': r'alter table [^;]+drop constraint[^;]+;', 'out': ''},
#~ {'in': r'^analyse [^;]+;', 'out': ''},
# replace
{'in': r'truncate (bati|fanr|lloc|nbat|pdll|prop)',
'out': r'drop table \1;create table \1 (tmp text)'},
{'in': r'truncate ', 'out': 'delete from '},
{'in': r'distinct on *\([a-z, ]+\)', 'out': 'distinct'},
{'in': r'serial', 'out': 'INTEGER PRIMARY KEY AUTOINCREMENT'},
{'in': r'string_agg', 'out': 'group_concat'},
{'in': r'current_schema::text, ', 'out': ''},
{'in': r'substring', 'out': 'SUBSTR'},
{'in': r"(to_char\()([^']+) *, *'[09]+' *\)", 'out': r"CAST(\2 AS TEXT)"},
{'in': r"(to_number\()([^']+) *, *'[09]+' *\)", 'out': r"CAST(\2 AS float)"},
{'in': r"(to_date\()([^']+) *, *'DDMMYYYY' *\)",
'out': r"date(substr(\2, 5, 4) || '-' || substr(\2, 3, 2) || '-' || substr(\2, 1, 2))"},
{'in': r"(to_date\()([^']+) *, *'DD/MM/YYYY' *\)",
'out': r"date(substr(\2, 7, 4) || '-' || substr(\2, 4, 2) || '-' || substr(\2, 1, 2))"},
{'in': r"(to_date\()([^']+) *, *'YYYYMMDD' *\)",
'out': r"date(substr(\2, 1, 4) || '-' || substr(\2, 5, 2) || '-' || substr(\2, 7, 2))"},
{'in': r"(to_char\()([^']+) *, *'dd/mm/YYYY' *\)",
'out': r"strftime('%d/%m/%Y', \2)"},
{'in': r"ST_MakeValid\(geom\)",
'out': r"CASE WHEN ST_IsValid(geom) THEN geom ELSE ST_Buffer(geom,0) END"},
{'in': r"ST_MakeValid\(p\.geom\)",
'out': r"CASE WHEN ST_IsValid(p.geom) THEN p.geom ELSE ST_Buffer(p.geom,0) END"},
{'in': r' ~ ', 'out': ' regexp '}
]
for a in replaceDict:
r = re.compile(a['in'], re.IGNORECASE|re.MULTILINE)
sql = r.sub(a['out'], sql)
#self.updateLog(sql)
# index spatiaux
r = re.compile(r'(create index [^;]+ ON )([^;]+)( USING +)(gist +)?\(([^;]+)\);', re.IGNORECASE|re.MULTILINE)
sql = r.sub(r"SELECT createSpatialIndex('\2', '\5');", sql)
# replace postgresql "update from" statement
r = re.compile(r'(update [^;=]+)(=)([^;=]+ FROM [^;]+)(;)', re.IGNORECASE|re.MULTILINE)
sql = r.sub(r'\1=(SELECT \3);', sql)
#self.updateLog(sql)
return sql
@staticmethod
def postgisToSpatialiteLocal10(sql, dataYear):
# majic formatage : replace multiple column update for loca10
r = re.compile(r'update local10 set[^;]+;', re.IGNORECASE|re.MULTILINE)
res = r.findall(sql)
replaceBy = ''
for statement in res:
replaceBy = '''
CREATE TABLE ll AS
SELECT DISTINCT l.invar, l.ccopre , l.ccosec, l.dnupla, l.ccoriv, l.ccovoi, l.dnvoiri, l10.annee || l10.ccodep || l10.ccodir || l10.invar AS local00, REPLACE(l10.annee || l10.ccodep || l10.ccodir || l10.ccocom || l.ccopre || l.ccosec || l.dnupla,' ', '0') AS parcelle, REPLACE(l10.annee || l10.ccodep || l10.ccodir || l10.ccocom || l.ccovoi,' ', '0') AS voie
FROM local00 l
INNER JOIN local10 AS l10 ON l.invar = l10.invar AND l.annee = l10.annee
WHERE l10.annee='?';
CREATE INDEX idx_ll_invar ON ll (invar);
UPDATE local10 SET ccopre = (SELECT DISTINCT ll.ccopre FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET ccosec = (SELECT DISTINCT ll.ccosec FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET dnupla = (SELECT DISTINCT ll.dnupla FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET ccoriv = (SELECT DISTINCT ll.ccoriv FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET ccovoi = (SELECT DISTINCT ll.ccovoi FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET dnvoiri = (SELECT DISTINCT ll.dnvoiri FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET local00 = (SELECT DISTINCT ll.local00 FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET parcelle = (SELECT DISTINCT ll.parcelle FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
UPDATE local10 SET voie = (SELECT DISTINCT ll.voie FROM ll WHERE ll.invar = local10.invar)
WHERE local10.annee = '?';
DROP TABLE ll;
'''
replaceBy = replaceBy.replace('?', dataYear)
sql = sql.replace(statement, replaceBy)
#self.updateLog(sql)
return sql
def createNewSpatialiteDatabase(self):
'''
Choose a file path to save
create the sqlite database with
spatial tools and create QGIS connection
'''
# Let the user choose new file path
ipath, __ = QFileDialog.getSaveFileName (
None,
u"Choisir l'emplacement du nouveau fichier",
str(os.path.expanduser("~").encode('utf-8')).strip(' \t'),
"Sqlite database (*.sqlite)"
)
if not ipath:
self.updateLog(u"Aucune base de données créée (annulation)")
return None
# Delete file if exists (question already asked above)
if os.path.exists(str(ipath)):
os.remove(str(ipath))
# Create the spatialite database
try:
# Create a connection (which will create the file automatically)
from qgis.utils import spatialite_connect
con = spatialite_connect(str(ipath), isolation_level=None)
cur = con.cursor()
sql = "SELECT InitSpatialMetadata(1)"
cur.execute(sql)
con.close()
del con
except:
self.updateLog(u"Échec lors de la création du fichier Spatialite !")
return None
# Create QGIS connexion
baseKey = "/SpatiaLite/connections/"
settings = QSettings()
myName = os.path.basename(ipath);
baseKey+= myName;
myFi = QFileInfo(ipath)
settings.setValue( baseKey + "/sqlitepath", myFi.canonicalFilePath());
# Update connections combo box and set new db selected
self.updateConnectionList()
listDic = { self.dialog.connectionDbList[i]:i for i in range(0, len(self.dialog.connectionDbList)) }
self.dialog.liDbConnection.setCurrentIndex(listDic[myName])
@staticmethod
def getCompteCommunalFromParcelleId(parcelleId, connectionParams, connector):
comptecommunal = None
sql = "SELECT comptecommunal FROM parcelle WHERE parcelle = '%s'" % parcelleId
if connectionParams['dbType'] == 'postgis':
sql = cadastre_common.setSearchPath(sql, connectionParams['schema'])
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(connector, sql)
if ok:
for line in data:
comptecommunal = line[0]
return comptecommunal
@staticmethod
def getProprietaireComptesCommunaux(comptecommunal, connectionParams, connector):
'''
Get the list of "comptecommunal" for all cities
for a owner given one single comptecommunal
'''
cc = comptecommunal
sql = " SELECT trim(ddenom) AS k, MyStringAgg(comptecommunal, ',') AS cc, dnuper"
sql+= " FROM proprietaire p"
sql+= " WHERE 2>1"
sql+= " AND trim(p.ddenom) IN (SELECT trim(ddenom) FROM proprietaire WHERE comptecommunal = '%s')" % comptecommunal
sql+= " GROUP BY dnuper, ddenom, dlign4"
sql+= " ORDER BY ddenom"
if connectionParams['dbType'] == 'postgis':
sql = cadastre_common.setSearchPath(sql, connectionParams['schema'])
sql = sql.replace('MyStringAgg', 'string_agg')
if connectionParams['dbType'] == 'spatialite':
sql = sql.replace('MyStringAgg', 'group_concat')
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(connector,sql)
ccs = []
if ok:
for line in data:
ccs = ccs + line[1].split(',')
return ccs
from .cadastre_import import cadastreImport
from qgis.PyQt import uic
IMPORT_FORM_CLASS, _ = uic.loadUiType(
os.path.join(
os.path.dirname(__file__),
'forms/cadastre_import_form.ui'
)
)
class cadastre_import_dialog(QDialog, IMPORT_FORM_CLASS):
def __init__(self, iface, parent=None):
self.iface = iface
super(cadastre_import_dialog, self).__init__(parent)
self.setupUi(self)
self.connectionDbList = []
# common cadastre methods
from .cadastre_dialogs import cadastre_common
self.qc = cadastre_common(self)
# first disable database specifi tabs
self.databaseSpecificOptions.setTabEnabled(0, False)
self.databaseSpecificOptions.setTabEnabled(1, False)
# spatialite support
self.hasSpatialiteSupport = cadastre_common.hasSpatialiteSupport()
if not self.hasSpatialiteSupport:
self.liDbType.removeItem(2)
self.databaseSpecificOptions.setTabEnabled(1, False)
self.btCreateNewSpatialiteDb.setEnabled(False)
# Signals/Slot Connections
self.liDbType.currentIndexChanged[str].connect(self.qc.updateConnectionList)
self.liDbConnection.currentIndexChanged[str].connect(self.qc.updateSchemaList)
self.btDbCreateSchema.clicked.connect(self.createSchema)
self.btCreateNewSpatialiteDb.clicked.connect(self.qc.createNewSpatialiteDatabase)
self.btProcessImport.clicked.connect(self.processImport)
self.rejected.connect(self.onClose)
self.buttonBox.rejected.connect(self.onClose)
# path buttons selectors
# paths needed to be chosen by user
self.pathSelectors = {
"edigeoSourceDir" : {
"button" : self.btEdigeoSourceDir,
"input" : self.inEdigeoSourceDir
},
"majicSourceDir" : {
"button" : self.btMajicSourceDir,
"input" : self.inMajicSourceDir
}
}
for key, item in list(self.pathSelectors.items()):
control = item['button']
slot = partial(self.chooseDataPath, key)
control.clicked.connect(slot)
# Set initial values
self.doMajicImport = False
self.doEdigeoImport = False
self.dataVersion = None
self.dataYear = None
self.dbType = None
self.dbpluginclass = None
self.connectionName = None
self.connection = None
self.db = None
self.schema = None
self.schemaList = None
self.hasStructure = None
self.hasData = None
self.hasMajicData = None
self.hasMajicDataParcelle = None
self.hasMajicDataVoie = None
self.hasMajicDataProp = None
self.edigeoSourceProj = None
self.edigeoTargetProj = None
self.edigeoDepartement = None
self.edigeoDirection = None
self.edigeoLot = None
self.majicSourceDir = None
self.edigeoSourceDir = None
self.edigeoMakeValid = False
# set input values from settings
self.sList = {
'dataVersion': {
'widget': self.inDataVersion,
'wType': 'spinbox',
'property': self.dataVersion
},
'dataYear': {
'widget': self.inDataYear,
'wType': 'spinbox',
'property': self.dataYear
} ,
'schema': {
'widget': None
} ,
'majicSourceDir': {
'widget': self.inMajicSourceDir,
'wType': 'text',
'property': self.majicSourceDir
},
'edigeoSourceDir': {
'widget': self.inEdigeoSourceDir,
'wType': 'text',
'property': self.edigeoSourceDir
},
'edigeoDepartement': {
'widget': self.inEdigeoDepartement,
'wType': 'text',
'property': self.edigeoDepartement
},
'edigeoDirection': {
'widget': self.inEdigeoDirection,
'wType': 'spinbox',
'property': self.edigeoDirection
},
'edigeoLot': {
'widget': self.inEdigeoLot,
'wType': 'text',
'property': self.edigeoLot
},
'edigeoSourceProj': {
'widget': self.inEdigeoSourceProj,
'wType': 'crs',
'property': self.edigeoSourceProj
},
'edigeoTargetProj': {
'widget': self.inEdigeoTargetProj,
'wType': 'crs',
'property': self.edigeoTargetProj
}
}
self.getValuesFromSettings()
def onClose(self):
'''
Close dialog
'''
if self.db:
self.db.connector.__del__()
# Store settings
msg = self.checkImportInputData()
if not msg:
self.storeSettings()
self.close()
def chooseDataPath(self, key):
'''
Ask the user to select a folder
and write down the path to appropriate field
'''
ipath = QFileDialog.getExistingDirectory(
None,
u"Choisir le répertoire contenant les fichiers",
str(self.pathSelectors[key]['input'].text().encode('utf-8')).strip(' \t')
)
if os.path.exists(str(ipath)):
self.pathSelectors[key]['input'].setText(str(ipath))
def getValuesFromSettings(self):
'''
get values from QGIS settings
and set input fields appropriately
'''
s = QSettings()
for k,v in list(self.sList.items()):
value = s.value("cadastre/%s" % k, '', type=str)
if value and value != 'None' and v['widget']:
if v['wType'] == 'text':
v['widget'].setText(value)
if v['wType'] == 'spinbox':
v['widget'].setValue(int(value))
if v['wType'] == 'combobox':
listDic = {v['list'][i]:i for i in range(0, len(v['list']))}
v['widget'].setCurrentIndex(listDic[value])
if v['wType'] == 'crs':
v['widget'].setCrs(QgsCoordinateReferenceSystem(value))
def createSchema(self):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
if self.db == None:
QMessageBox.warning(
self,
QApplication.translate("DBManagerPlugin", "Sorry"),
QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it.")
)
return
schema = self.inDbCreateSchema.text()