forked from 3liz/QgisCadastrePlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcadastre_import.py
1546 lines (1322 loc) · 58.2 KB
/
cadastre_import.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 - import main methods
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 os, glob
import io
import string, sys
import re
import time
import tempfile
import shutil
from distutils import dir_util
from qgis.PyQt.QtCore import Qt, QObject, QSettings
from qgis.PyQt.QtGui import QCursor, QPixmap
from qgis.PyQt.QtWidgets import QApplication, QMessageBox
from qgis.core import (
QgsMessageLog,
QgsLogger
)
from datetime import datetime
# 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 qgis.utils import spatialite_connect
import sqlite3 as sqlite
# Import ogr2ogr.py from processing plugin
try:
from processing.algs.gdal.pyogr.ogr2ogr import main as ogr2ogr
except ImportError:
pass
try:
from processing.gdal.pyogr.ogr2ogr import main as ogr2ogr
except ImportError:
pass
try:
from .scripts.pyogr.ogr2ogr import main as ogr2ogr
except ImportError:
pass
from .scripts.pyogr.ogr2ogr import main as ogr2ogr
from .cadastre_dialogs import cadastre_common
class cadastreImport(QObject):
def __init__(self, dialog):
self.dialog = dialog
# common cadastre methods
self.qc = self.dialog.qc
self.db = self.dialog.db
self.connector = self.db.connector
self.pScriptSourceDir = os.path.join(self.qc.plugin_dir, 'scripts/plugin')
# projections
if self.dialog.doEdigeoImport:
self.sourceSridFull = self.dialog.edigeoSourceProj
self.targetSridFull = self.dialog.edigeoTargetProj
self.sourceAuth = self.sourceSridFull.split(":")[0]
self.sourceSrid = self.sourceSridFull.split(":")[1]
self.targetSrid = self.targetSridFull.split(":")[1]
# Check IGNF code
if self.sourceAuth == 'IGNF':
sqlsearch = '%%AUTHORITY["IGNF","%s"]%%' % self.sourceSrid.upper()
sql = "SELECT auth_srid FROM spatial_ref_sys WHERE auth_name='IGNF' AND srtext LIKE '%s' LIMIT 1" % sqlsearch
[header, data, rowCount, ok] = cadastre_common.fetchDataFromSqlQuery(self.connector,sql)
if rowCount == 1:
for line in data:
self.sourceSrid = str(line[0])
else:
self.targetSrid = '2154'
# create temporary directories
s = QSettings()
tempDir = s.value("cadastre/tempDir", '%s' % tempfile.gettempdir(), type=str)
self.pScriptDir = tempfile.mkdtemp('', 'cad_p_script_', tempDir)
self.edigeoPlainDir = tempfile.mkdtemp('', 'cad_edigeo_plain_', tempDir)
self.replaceDict = {
'[VERSION]' : self.dialog.dataVersion,
'[ANNEE]' : self.dialog.dataYear,
'[LOT]' : self.dialog.edigeoLot
}
self.maxInsertRows = s.value("cadastre/maxInsertRows", 50000, type=int)
self.spatialiteTempStore = s.value("cadastre/spatialiteTempStore", 'MEMORY', type=str)
self.geoTableList = ['geo_zoncommuni', 'geo_ptcanv', 'geo_commune', 'geo_parcelle', 'geo_symblim', 'geo_tronfluv', 'geo_tronroute', 'geo_label', 'geo_subdsect', 'geo_batiment', 'geo_borne', 'geo_croix', 'geo_tpoint', 'geo_lieudit', 'geo_section', 'geo_subdfisc', 'geo_tsurf', 'geo_tline', 'geo_unite_fonciere']
s = QSettings()
self.majicSourceFileNames = [
{'key': '[FICHIER_BATI]',
'value': s.value("cadastre/batiFileName", 'REVBATI.800', type=str),
'table': 'bati',
'required': True
},
{'key': '[FICHIER_FANTOIR]',
'value': s.value("cadastre/fantoirFileName", 'TOPFANR.800', type=str),
'table': 'fanr',
'required': True
},
{'key': '[FICHIER_LOTLOCAL]',
'value': s.value("cadastre/lotlocalFileName", 'REVD166.800', type=str),
'table': 'lloc',
'required': False
},
{'key': '[FICHIER_NBATI]',
'value': s.value("cadastre/nbatiFileName", 'REVNBAT.800', type=str),
'table': 'nbat',
'required': True
},
{'key': '[FICHIER_PDL]',
'value': s.value("cadastre/pdlFileName", 'REVFPDL.800', type=str),
'table': 'pdll',
'required': False
},
{'key': '[FICHIER_PROP]',
'value': s.value("cadastre/propFileName", 'REVPROP.800', type=str),
'table': 'prop',
'required': True
}
]
if self.dialog.dbType == 'postgis':
self.replaceDict['[PREFIXE]'] = '"%s".' % self.dialog.schema
else:
self.replaceDict['[PREFIXE]'] = ''
self.go = True
self.startTime = datetime.now()
self.step = 0
self.totalSteps = 0
self.multiPolygonUpdated = 0
self.qc.checkDatabaseForExistingStructure()
self.hasConstraints = False
if self.dialog.hasStructure:
self.hasConstraints = True
# Remove MAJIC from tables bati|fanr|lloc|nbat|pdll|prop
self.removeMajicRawData = True
self.beginImport()
def beginJobLog(self, stepNumber, title):
'''
reinit progress bar
'''
self.totalSteps = stepNumber
self.step = 0
self.dialog.stepLabel.setText('<b>%s</b>' % title)
self.qc.updateLog('<h3>%s</h3>' % title)
def updateProgressBar(self):
'''
Update the progress bar
'''
if self.go:
self.step+=1
self.dialog.pbProcess.setValue(int(self.step * 100/self.totalSteps))
def updateTimer(self):
'''
Update the timer for each process
'''
if self.go:
b = datetime.now()
diff = b - self.startTime
self.qc.updateLog(u'%s s' % diff.seconds)
def beginImport(self):
'''
Process to run before importing data
'''
# Log
jobTitle = u'INITIALISATION'
self.beginJobLog(2, jobTitle)
# Set postgresql synchronous_commit to off
# to speed up bulk inserts
if self.dialog.dbType == 'postgis':
sql = "SET LOCAL synchronous_commit TO off;"
if self.dialog.dbType == 'spatialite':
sql = 'PRAGMA synchronous = OFF;PRAGMA journal_mode = OFF;PRAGMA temp_store = %s;PRAGMA cache_size = 500000' % self.spatialiteTempStore
self.executeSqlQuery(sql)
# copy SQL script files to temporary dir
self.updateProgressBar()
self.copyFilesToTemp(self.pScriptSourceDir, self.pScriptDir)
self.updateTimer()
self.updateProgressBar()
def installCadastreStructure(self):
'''
Create the empty db structure
'''
if not self.go:
return False
# Log
jobTitle = u'STRUCTURATION BDD'
self.beginJobLog(6, jobTitle)
# Replace dictionnary
replaceDict = self.replaceDict.copy()
replaceDict['2154'] = self.targetSrid
# Suppression des éventuelles tables edigeo import
# laissées suite à bug par exemple
self.dropEdigeoRawData()
# install cadastre structure
scriptList = [
{
'title' : u'Création des tables',
'script': '%s' % os.path.join(self.pScriptDir, 'commun_create_metier.sql')
},
{
'title': u'Création des tables edigeo',
'script': '%s' % os.path.join(self.pScriptDir, 'edigeo_create_import_tables.sql')
},
{
'title' : u'Ajout de la nomenclature',
'script': '%s' % os.path.join(self.pScriptDir, 'commun_insert_nomenclatures.sql')
}
]
for item in scriptList:
if self.go:
s = item['script']
self.dialog.subStepLabel.setText(item['title'])
self.qc.updateLog('%s' % item['title'])
self.updateProgressBar()
self.replaceParametersInScript(s, replaceDict)
self.executeSqlScript(s, 'constraints' in item)
if 'constraints' in item:
self.hasConstraints = item['constraints']
self.updateProgressBar()
self.updateTimer()
def updateCadastreStructure(self):
'''
Add some tables if they do not exists
This method is run only if structure already exists
and if each table is not already present
'''
# List all the tables which have been created between plugin versions
newTables = [
'geo_tronroute',
'commune_majic'
]
# Replace dictionnary
replaceDict = self.replaceDict.copy()
replaceDict['2154'] = self.targetSrid
# Run the table creation scripts
for table in newTables:
# Check if table already exists
if self.qc.checkDatabaseForExistingTable(table, self.dialog.schema):
continue
# Build path the the SQL creation file and continue if it does not exists
s = '%s' % os.path.join(self.pScriptDir, 'update/create_%s.sql' % table)
if not os.path.exists(s):
continue
self.replaceParametersInScript(s, replaceDict)
self.executeSqlScript(s, False)
def importMajic(self):
# Log
jobTitle = u'MAJIC'
self.beginJobLog(13, jobTitle)
# dict for parameters replacement
replaceDict = self.replaceDict.copy()
mandatoryFilesKeys = ['[FICHIER_BATI]', '[FICHIER_FANTOIR]', '[FICHIER_NBATI]', '[FICHIER_PROP]']
missingMajicFiles = False
scriptList = []
scriptList.append(
{
'title' : u'Suppression des contraintes',
'script' : os.path.join(self.pScriptDir, 'commun_suppression_contraintes.sql'),
'constraints': False,
'divide': True
}
)
# Remove previous data
if self.dialog.hasMajicData:
scriptList.append(
{
'title' : u'Purge des données MAJIC',
'script' : os.path.join(self.pScriptDir, 'majic3_purge_donnees.sql')
}
)
scriptList.append(
{
'title' : u'Purge des données brutes',
'script' : os.path.join(self.pScriptDir, 'majic3_purge_donnees_brutes.sql')
}
)
# Remove indexes
scriptList.append(
{
'title' : u'Suppression des indexes',
'script' : os.path.join(self.pScriptDir, 'majic3_drop_indexes.sql')
}
)
# Import MAJIC files into database
# No use of COPY FROM to allow import into distant databases
importScript = {
'title' : u'Import des fichiers majic',
'method' : self.importMajicIntoDatabase
}
scriptList.append(importScript)
# Format data
scriptList.append(
{
'title' : u'Mise en forme des données',
'script' : os.path.join(self.pScriptDir, '%s/majic3_formatage_donnees.sql' % self.dialog.dataVersion),
'divide': True
}
)
# Remove MAJIC raw data
if self.removeMajicRawData:
scriptList.append(
{
'title' : u'Purge des données brutes',
'script' : os.path.join(self.pScriptDir, 'majic3_purge_donnees_brutes.sql')
}
)
# If MAJIC but no EDIGEO afterward
# run SQL script to update link between EDI/MAJ
if not self.dialog.doEdigeoImport:
replaceDict['[DEPDIR]'] = '%s%s' % (self.dialog.edigeoDepartement, self.dialog.edigeoDirection)
scriptList.append(
{
'title' : u'Suppression des indexes',
'script' : os.path.join(self.pScriptDir, 'edigeo_drop_indexes.sql')
}
)
scriptList.append(
{
'title' : u'Mise à jour des liens EDIGEO',
'script' : os.path.join(self.pScriptDir, 'edigeo_update_majic_link.sql'),
'divide': True
}
)
scriptList.append(
{
'title' : u'Création des indexes spatiaux',
'script' : os.path.join(self.pScriptDir, 'edigeo_create_indexes.sql'),
'divide': True
}
)
# Ajout de la table parcelle_info
replaceDict['2154'] = self.targetSrid
scriptList.append(
{
'title' : u'Ajout de la table parcelle_info',
'script' : '%s' % os.path.join(self.pScriptDir, 'edigeo_create_table_parcelle_info_majic.sql'),
'divide': False
}
)
# Add constraints
scriptList.append(
{
'title' : u'Ajout des contraintes',
'script' : os.path.join(self.pScriptDir, 'commun_creation_contraintes.sql'),
'constraints': True,
'divide': True
}
)
# Run previously defined SQL queries
for item in scriptList:
if self.go:
self.dialog.subStepLabel.setText(item['title'])
self.qc.updateLog('%s' % item['title'])
if 'script' in item:
s = item['script']
self.replaceParametersInScript(s, replaceDict)
self.updateProgressBar()
if 'divide' in item:
self.executeSqlScript(s, True, 'constraints' in item)
else:
self.executeSqlScript(s, False, 'constraints' in item)
else:
self.updateProgressBar()
item['method']()
if 'constraints' in item \
and not self.dialog.dbType == 'spatialite':
self.hasConstraints = item['constraints']
self.updateTimer()
self.updateProgressBar()
return None
def chunk(self, iterable, n=100000, padvalue=None):
'''
Chunks an iterable (file, etc.)
into pieces
'''
from itertools import zip_longest
return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
def importMajicIntoDatabase(self):
'''
Method wich read each majic file
and bulk import data intp temp tables
Returns False if no file processed
'''
processedFilesCount = 0
majicFilesKey = []
majicFilesFound = {}
# Regex to remove all chars not in the range in ASCII table from space to ~
# http://www.catonmat.net/blog/my-favorite-regex/
r = re.compile(r"[^ -~]")
# Loop through all majic files
# 1st path to build the complet liste for each majic source type (nbat, bati, lloc, etc.)
# and read 1st line to get departement and direction to compare to inputs
depdirs = {}
for item in self.majicSourceFileNames:
table = item['table']
value = item['value']
# Get majic files for item
majList = []
for root, dirs, files in os.walk(self.dialog.majicSourceDir):
for i in files:
if os.path.split(i)[1] == value:
fpath = os.path.join(root, i)
# Add file path to the list
majList.append(fpath)
# Store depdir for this file
# avoid fantoir, as now it is given for the whole country
if table == 'fanr':
continue
# Get depdir : first line with content
with open(fpath) as fin:
for a in fin:
if len( a ) < 4 :
continue
depdir = a[0:3]
break
depdirs[depdir] = True
majicFilesFound[table] = majList
# Check if some important majic files are missing
fKeys = [ a for a in majicFilesFound if majicFilesFound[a] ]
rKeys = [ a['table'] for a in self.majicSourceFileNames if a['required'] ]
mKeys = [ a for a in rKeys if a not in fKeys ]
if mKeys:
msg = u"<b>Des fichiers MAJIC importants sont manquants: %s </b><br/>Vérifier le chemin des fichiers MAJIC:<br/>%s <br/>ainsi que les noms des fichiers configurés dans les options du plugin Cadastre:<br/>%s<br/><br/>Vous pouvez télécharger les fichiers fantoirs à cette adresse :<br/><a href='https://www.collectivites-locales.gouv.fr/mise-a-disposition-gratuite-fichier-des-voies-et-des-lieux-dits-fantoir'>https://www.collectivites-locales.gouv.fr/mise-a-disposition-gratuite-fichier-des-voies-et-des-lieux-dits-fantoir</a><br/>" % (
', '.join(mKeys),
self.dialog.majicSourceDir,
', '.join([a['value'].upper() for a in self.majicSourceFileNames])
)
missingMajicIgnore = QMessageBox.question(
self.dialog,
u'Cadastre',
msg + '\n\n' + u"Voulez-vous néanmoins continuer l'import ?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No
)
if missingMajicIgnore != QMessageBox.Yes:
self.go = False
self.qc.updateLog(msg)
return False
# Check if departement and direction are the same for every file
if len(list(depdirs.keys())) > 1:
self.go = False
lst = ",<br/> ".join( u"département : %s et direction : %s" % (a[0:2], a[2:3]) for a in depdirs)
self.qc.updateLog(
u"<b>ERREUR : MAJIC - Les données concernent des départements et codes direction différents :</b>\n<br/> %s" % lst
)
self.qc.updateLog(u"<b>Veuillez réaliser l'import en %s fois.</b>" % len( list(depdirs.keys()) ) )
return False
# Check if departement and direction are different from those given by the user in dialog
fDep = list(depdirs.keys())[0][0:2]
fDir = list(depdirs.keys())[0][2:3]
if self.dialog.edigeoDepartement != fDep or self.dialog.edigeoDirection != fDir:
msg = u"<b>ERREUR : MAJIC - Les numéros de département et de direction trouvés dans les fichiers ne correspondent pas à ceux renseignés dans les options du dialogue d'import:<b>\n<br/>* fichiers : %s et %s <br/>* options : %s et %s" % (
fDep,
fDir,
self.dialog.edigeoDepartement,
self.dialog.edigeoDirection
)
useFileDepDir = QMessageBox.question(
self.dialog,
u'Cadastre',
msg + '\n\n' + u"<br/><br/>Voulez-vous continuer l'import avec les numéros trouvés dans les fichiers ?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No
)
if useFileDepDir == QMessageBox.Yes:
self.dialog.edigeoDepartement = fDep
self.dialog.inEdigeoDepartement.setText(fDep)
self.dialog.edigeoDirection = fDir
self.dialog.inEdigeoDirection.setValue(int(fDir))
else:
self.go = False
self.qc.updateLog(msg)
return False
# 2nd path to insert data
depdir = '%s%s' % (self.dialog.edigeoDepartement, self.dialog.edigeoDirection)
for item in self.majicSourceFileNames:
table = item['table']
self.totalSteps+= len(majicFilesFound[table])
processedFilesCount+=len(majicFilesFound[table])
for fpath in majicFilesFound[table]:
self.qc.updateLog(fpath)
# read file content
with open(fpath) as fin:
# Divide file into chuncks
for a in self.chunk(fin, self.maxInsertRows):
# Build sql INSERT query depending on database
if self.dialog.dbType == 'postgis':
sql = "BEGIN;"
sql = cadastre_common.setSearchPath(sql, self.dialog.schema)
# Build INSERT list
sql+= '\n'.join(
[
"INSERT INTO \"%s\" VALUES (%s);" % (
table,
self.connector.quoteString( r.sub(' ', x.strip('\r\n')) )
) for x in a if x and x[0:3] == depdir
]
)
sql+= "COMMIT;"
self.executeSqlQuery(sql)
else:
c = self.connector._get_cursor()
c.executemany('INSERT INTO %s VALUES (?)' % table, [( r.sub(' ', x.strip('\r\n')) ,) for x in a if x and x[0:3] == depdir] )
self.connector._commit()
c.close()
del c
if not processedFilesCount:
self.qc.updateLog(
u"<b>ERREUR : MAJIC - aucun fichier trouvé. Vérifier les noms de fichiers dans les paramètres du plugin et que le répertoire </b>'%s' <b>contient bien des fichiers qui correspondent</b>\n : %s" % (
self.dialog.majicSourceDir,
', '.join( majicFilesKey )
)
)
self.go = False
def importEdigeo(self):
'''
Import EDIGEO data
into database
'''
if not self.go:
return False
# Log : Print connection parameters to database
jobTitle = u'EDIGEO'
self.beginJobLog(21, jobTitle)
self.qc.updateLog(u'Type de base : %s, Connexion: %s, Schéma: %s' % (
self.dialog.dbType,
self.dialog.connectionName,
self.dialog.schema
)
)
self.updateProgressBar()
if self.go:
# unzip edigeo files in temp dir
self.dialog.subStepLabel.setText('Extraction des fichiers')
self.updateProgressBar()
self.unzipFolderContent(self.dialog.edigeoSourceDir)
self.updateTimer()
self.updateProgressBar()
scriptList = []
replaceDict = self.replaceDict.copy()
# Add geo_unite_foncieres if needed
if not self.qc.checkDatabaseForExistingTable('geo_unite_fonciere', self.dialog.schema) \
and self.dialog.dbType == 'postgis':
scriptList.append(
{
'title' : u'Ajout de la table geo_unite_foncieres',
'script' : '%s' % os.path.join(self.pScriptDir, 'edigeo_create_table_unite_fonciere.sql'),
'constraints': False
}
)
# Drop constraints
scriptList.append(
{
'title' : u'Suppression des contraintes',
'script' : '%s' % os.path.join(self.pScriptDir, 'commun_suppression_contraintes.sql'),
'constraints': False,
'divide' : True
}
)
# Suppression et recréation des tables edigeo pour import
if self.dialog.hasData:
replaceDict['2154'] = self.targetSrid
# Drop edigeo data
self.dropEdigeoRawData()
scriptList.append(
{
'title': u'Création des tables edigeo',
'script': '%s' % os.path.join(self.pScriptDir, 'edigeo_create_import_tables.sql')
}
)
# Suppression des indexes
if self.dialog.hasData:
scriptList.append(
{
'title' : u'Suppression des indexes',
'script' : '%s' % os.path.join(self.pScriptDir, 'edigeo_drop_indexes.sql')
}
)
for item in scriptList:
if self.go:
self.dialog.subStepLabel.setText(item['title'])
self.qc.updateLog('%s' % item['title'])
s = item['script']
self.replaceParametersInScript(s, replaceDict)
self.updateProgressBar()
self.executeSqlScript(s, 'divide' in item, 'constraints' in item)
if 'constraints' in item:
self.hasConstraints = item['constraints']
self.updateTimer()
self.updateProgressBar()
# import edigeo *.thf and *.vec files into database
if self.go:
self.dialog.subStepLabel.setText('Import des fichiers')
self.updateProgressBar()
self.importAllEdigeoToDatabase()
self.updateTimer()
self.updateProgressBar()
# Format edigeo data
replaceDict = self.replaceDict.copy()
replaceDict['[DEPDIR]'] = '%s%s' % (self.dialog.edigeoDepartement, self.dialog.edigeoDirection)
scriptList = []
scriptList.append(
{
'title' : u'Mise en forme des données',
'script' : os.path.join(self.pScriptDir, 'edigeo_formatage_donnees.sql'),
'divide': True
}
)
scriptList.append(
{
'title' : u'Placement des étiquettes',
'script' : os.path.join(self.pScriptDir, 'edigeo_add_labels_xy.sql')
}
)
scriptList.append(
{
'title' : u'Création des indexes spatiaux',
'script' : os.path.join(self.pScriptDir, 'edigeo_create_indexes.sql' ),
'divide': True
}
)
scriptList.append(
{
'title' : u'Ajout des contraintes',
'script' : os.path.join(self.pScriptDir, 'commun_creation_contraintes.sql' ),
'constraints': True,
'divide': True
}
)
# ajout des unités foncières
# seulement si on a des données MAJIC de propriétaire
self.qc.checkDatabaseForExistingStructure()
if ( self.dialog.doMajicImport or self.dialog.hasMajicDataProp ) \
and self.dialog.dbType == 'postgis':
scriptList.append(
{ 'title' : u'Création Unités foncières',
'script' : os.path.join( self.pScriptDir, 'edigeo_unites_foncieres_%s.sql' % self.dialog.dbType)
}
)
# Ajout de la table parcelle_info
if ( self.dialog.doMajicImport or self.dialog.hasMajicDataProp ):
replaceDict['2154'] = self.targetSrid
scriptList.append(
{
'title' : u'Ajout de la table parcelle_info',
'script' : '%s' % os.path.join(self.pScriptDir, 'edigeo_create_table_parcelle_info_majic.sql')
}
)
else:
replaceDict['2154'] = self.targetSrid
scriptList.append(
{
'title' : u'Ajout de la table parcelle_info',
'script' : '%s' % os.path.join(self.pScriptDir, 'edigeo_create_table_parcelle_info_simple.sql')
}
)
for item in scriptList:
if self.go:
self.dialog.subStepLabel.setText(item['title'])
self.qc.updateLog('%s' % item['title'])
s = item['script']
self.replaceParametersInScript(s, replaceDict)
self.updateProgressBar()
self.executeSqlScript(s, 'divide' in item, 'constraints' in item)
if 'constraints' in item:
self.hasConstraints = item['constraints']
self.updateTimer()
self.updateProgressBar()
# drop edigeo raw data
self.dialog.subStepLabel.setText('Suppression des fichiers temporaires')
self.dropEdigeoRawData()
self.updateTimer()
self.updateProgressBar()
return None
def endImport(self):
'''
Actions done when import has finished
'''
# Log
jobTitle = u'FINALISATION'
self.beginJobLog(1, jobTitle)
# Debug spatialite
if self.dialog.dbType == 'spatialite':
sql = "SELECT RecoverGeometryColumn( 'parcelle_info', 'geom', %s, 'MULTIPOLYGON', 2 );" % self.targetSrid
sql+= "SELECT RecoverGeometryColumn( 'geo_batiment', 'geom', %s, 'MULTIPOLYGON', 2 );" % self.targetSrid
self.executeSqlQuery(sql)
# Re-set SQL optimization parameters to default
if self.dialog.dbType == 'postgis':
sql = "SET LOCAL synchronous_commit TO on;"
self.executeSqlQuery(sql)
else:
sql = 'PRAGMA journal_mode = MEMORY;'
self.executeSqlQuery(sql)
# Remove the temp folders
self.dialog.subStepLabel.setText(u'Suppression des données temporaires')
self.updateProgressBar()
tempFolderList = [
self.pScriptDir,
self.edigeoPlainDir,
]
delmsg = ""
try:
for rep in tempFolderList:
if os.path.exists(rep):
shutil.rmtree(rep)
rmt = 1
except IOError as e:
delmsg = u"<b>Erreur lors de la suppression des répertoires temporaires: %s</b>" % e
self.qc.updateLog(delmsg)
self.go = False
# Delete labels outside commune bbox
if self.dialog.dbType == 'spatialite':
sql = 'DELETE FROM geo_label WHERE NOT MbrWithin(geom, ( SELECT ST_Buffer(ST_Envelope(Collect(geom)), 100 ) AS geom FROM geo_commune ));'
else:
sql = 'DELETE FROM geo_label WHERE NOT ST_Within(geom, ( SELECT ST_Buffer(ST_Envelope(ST_Collect(geom)), 100 ) AS geom FROM geo_commune ));'
sql = self.qc.setSearchPath(sql, self.dialog.schema)
self.executeSqlQuery(sql)
# Add parcelle_info index for postgis only (not capability of that type for spatialite)
if self.dialog.dbType == 'postgis':
sql = 'DROP INDEX IF EXISTS parcelle_info_geo_parcelle_sub;CREATE INDEX parcelle_info_geo_parcelle_sub ON parcelle_info( substr("geo_parcelle", 1, 10));'
sql = self.qc.setSearchPath(sql, self.dialog.schema)
self.executeSqlQuery(sql)
# Refresh spatialite layer statistics
if self.dialog.dbType == 'spatialite':
sql = ''
for layer in self.geoTableList:
sql+= "SELECT UpdateLayerStatistics('%s', 'geom');" % layer
self.executeSqlQuery(sql)
if self.go:
msg = u"Import terminé"
else:
msg = u"Des erreurs ont été rencontrées pendant l'import. Veuillez consulter le log."
self.updateProgressBar()
self.updateTimer()
QMessageBox.information(self.dialog, "Cadastre", msg)
return None
#
# TOOLS
#
def copyFilesToTemp(self, source, target):
'''
Copy cadastre scripts
into a temporary folder
'''
if self.go:
self.qc.updateLog(u'* Copie du répertoire %s' % source)
QApplication.setOverrideCursor(Qt.WaitCursor)
# copy script directory
try:
dir_util.copy_tree(source, target)
os.chmod(target, 0o777)
except IOError as e:
msg = u"<b>Erreur lors de la copie des scripts d'import: %s</b>" % e
QMessageBox.information(self.dialog,
"Cadastre", msg)
self.go = False
return msg
finally:
QApplication.restoreOverrideCursor()
return None
def listFilesInDirectory(self, path, extensionList=[], invert=False):
'''
List all files from folder and subfolder
for a specific extension if given ( via the list extensionList ).
If invert is True, then get all files
but those corresponding to the given extensions.
'''
fileList = []
for root, dirs, files in os.walk(path):
for i in files:
if not invert:
if os.path.splitext(i)[1][1:].lower() in extensionList:
fileList.append(os.path.join(root, i))
else:
if os.path.splitext(i)[1][1:].lower() not in extensionList:
fileList.append(os.path.join(root, i))
return fileList
def unzipFolderContent(self, path):
'''
Scan content of specified path
and unzip all content into a single folder
'''
if self.go:
QApplication.setOverrideCursor(Qt.WaitCursor)
self.qc.updateLog(u'* Décompression des fichiers')
# get all the zip files
zipFileList = self.listFilesInDirectory(path, ['zip'])
# unzip all files
import zipfile
import tarfile
try:
# unzip all zip in source folder
for z in zipFileList:
# Extract file from edigeoDir into edigeoPlainDir
with zipfile.ZipFile(z) as azip:
azip.extractall(self.edigeoPlainDir)
# unzip all new zip in edigeoPlainDir
inner_zips_pattern = os.path.join(self.edigeoPlainDir, "*.zip")
i=0
for filename in glob.glob(inner_zips_pattern):
inner_folder = filename[:-4] + '_%s' % i
with zipfile.ZipFile(filename) as myzip:
myzip.extractall(inner_folder)
try:
os.remove(filename)
except OSError as e:
self.qc.updateLog( "<b>Erreur lors de la suppression de %s</b>" % str(filename))
pass # in Windows, sometime file is not unlocked
i+=1
i=0
# untar all tar.bz2 in source folder
tarFileListA = self.listFilesInDirectory(path, ['bz2'])
for z in tarFileListA:
with tarfile.open(z) as t:
tar = t.extractall(os.path.join(self.edigeoPlainDir, 'tar_%s' % i))
i+=1
t.close()
# untar all new tar.bz2 found in self.edigeoPlainDir
tarFileListB = self.listFilesInDirectory(self.edigeoPlainDir, ['bz2'])
for z in tarFileListB:
with tarfile.open(z) as t:
tar = t.extractall(os.path.join(self.edigeoPlainDir, 'tar_%s' % i))
i+=1
t.close()
try:
os.remove(z)
except OSError as e:
self.qc.updateLog( "<b>Erreur lors de la suppression de %s</b>" % str(z))
pass # in Windows, sometime file is not unlocked
except IOError as e:
msg = u"<b>Erreur lors de l'extraction des fichiers EDIGEO</b>"
self.go = False
self.qc.updateLog(msg)
return msg
finally:
QApplication.restoreOverrideCursor()