-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathddui.py
More file actions
5179 lines (4131 loc) · 201 KB
/
ddui.py
File metadata and controls
5179 lines (4131 loc) · 201 KB
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 -*-
"""
ddui
--------
Classes that make up or steer the DataDrivenUI
"""
from __future__ import absolute_import
"""
/***************************************************************************
DataDrivenInputMask
A QGIS plugin
Applies a data-driven input mask to any PostGIS-Layer
-------------------
begin : 2012-06-21
copyright : (C) 2012 by Bernhard Ströbl / Kommunale Immobilien Jena
email : bernhard.stroebl@jena.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from builtins import str
from builtins import range
from builtins import object
# Import the PyQt and QGIS libraries
from qgis.PyQt import QtCore, QtGui, QtSql, QtWidgets
from qgis.core import *
from .dderror import DdError, DbError
from .ddattribute import *
from .dddialog import DdDialog, DdSearchDialog
from . import ddtools
import xml.etree.ElementTree as ET
from . import icons
class DdFormHelper(object):
def __init__(self, thisDialog, layerId, featureId):
app = QgsApplication.instance()
ddManager = app.ddManager
lIface = ddManager.iface.legendInterface()
for aLayer in lIface.layers():
if aLayer.id() == layerId:
#QtWidgets.QMessageBox.information(None, "", aLayer.name())
#thisDialog.hide()
feat = QgsFeature()
featureFound = aLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId).setFlags(QgsFeatureRequest.NoGeometry)).nextFeature(feat)
if featureFound:
result = ddManager.showFeatureForm(aLayer, feat)
#QtWidgets.QMessageBox.information(None, "", str(thisDialog))
thisDialog.setVisible(False)
if result == 1:
thisDialog.accept()
else:
thisDialog.reject()
break
#self.prntWidget = self.thisDialog.parentWidget()
def ddFormInit1(dialog, layerId, featureId):
dialog.setProperty("helper", DdFormHelper(dialog, layerId, featureId))
def ddFormInit(dialog, layerId, featureId):
app = QgsApplication.instance()
ddManager = app.ddManager
lIface = ddManager.iface.legendInterface()
for aLayer in lIface.layers():
if aLayer.id() == layerId:
feat = QgsFeature()
featureFound = aLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId).setFlags(QgsFeatureRequest.NoGeometry)).nextFeature(feat)
if featureFound:
try:
layerValues = ddManager.ddLayers[aLayer.id()]
except KeyError:
ddManager.initLayer(aLayer, skip = [], labels = {}, fieldOrder = [], fieldGroups = {}, minMax = {}, noSearchFields = [], \
showParents = True, createAction = True, db = None, inputMask = True, searchMask = True, \
inputUi = None, searchUi = None, helpText = "")
layerValues = ddManager.ddLayers[aLayer.id()]
db = layerValues[1]
ui = layerValues[2]
dlg = DdDialog(ddManager, ui, aLayer, feat, db, dialog)
dlg.show()
result = dlg.exec_()
if result == 1:
layer.setModified()
class DdEventFilter(QtCore.QObject):
'''Event filter class to be applied to DdLineEdit's input widgets
throws a signal even when the input widget is not enabled'''
doubleClicked = QtCore.pyqtSignal()
def eventFilter(self, watchedObject, event):
typ = event.type()
if typ == QtCore.QEvent.MouseButtonDblClick:
self.doubleClicked.emit()
return False # if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.
class DataDrivenUi(object):
'''Creates the DataDrivenUi
When subclassing this class, you want to rewrite createUi and use DdManager's setUi
method to apply your custom ui to the layer'''
def __init__(self, iface):
self.iface = iface
def __str__(self):
return "<ddui.DataDrivenUi>"
def __debug(self, title, str):
QgsMessageLog.logMessage(title + "\n" + str)
def configureLayer(self, ddTable, skip, labels, fieldOrder, fieldGroups,
minMax, noSearchFields, db, createAction, helpText, fieldDisable):
'''read configuration from db'''
multilineFields = []
lookupFields = {}
whereClauses = {}
#check if config tables exist in db
configOid = ddtools.getOid(DdTable(schemaName = "public", tableName = "dd_table"), db)
if configOid != None:
# read values for this table from config tables
query = QtSql.QSqlQuery(db)
sQuery = "SELECT COALESCE(\"table_help\", \'\'), \
\"table_action\", \
COALESCE(\"tab_alias\", \'\'), \
COALESCE(\"tab_tooltip\", \'\'), \
\"field_name\", \
COALESCE(\"field_alias\", \'\'), \
\"field_skip\", \
\"field_search\", \
\"field_min\", \
\"field_max\", \
COALESCE(\"field_enabled\",true)::varchar, \
COALESCE(\"field_multiline\",false)::varchar, \
trim(COALESCE(\"lookup_expression\",\'\')), \
trim(COALESCE(\"where_clause\",\'\')) \
FROM \"public\".\"dd_table\" t \
LEFT JOIN \"public\".\"dd_tab\" tb ON t.id = tb.\"dd_table_id\" \
LEFT JOIN \"public\".\"dd_field\" f ON tb.id = f.\"dd_tab_id\" \
WHERE \"table_schema\" = :schema AND \"table_name\" = :table\
ORDER BY \"tab_order\", \"field_order\""
query.prepare(sQuery)
query.bindValue(":schema", ddTable.schemaName)
query.bindValue(":table", ddTable.tableName)
query.exec_()
if query.isActive():
lastTab = None
firstDataSet = True
while query.next():
if firstDataSet:
helpText += query.value(0)
firstDataSet = False
createAction = query.value(1)
tabAlias = query.value(2)
tabTooltip = query.value(3)
fieldName = query.value(4)
fieldAlias = query.value(5)
fieldSkip = query.value(6)
fieldSearch = query.value(7)
fieldMin = query.value(8)
fieldMax = query.value(9)
fieldEnable = query.value(10)
fieldMultiline = query.value(11)
lookupField = query.value(12)
whereClause = query.value(13)
if tabAlias != lastTab and not fieldSkip:
if tabAlias != "":
lastTab = tabAlias
fieldGroups[fieldName] = [tabAlias, tabTooltip]
fieldOrder.append(fieldName)
if fieldAlias != "":
labels[fieldName] = fieldAlias
if fieldSkip:
skip.append(fieldName)
if not fieldSearch:
noSearchFields.append(fieldName)
if fieldMin != None or fieldMax != None:
minMax[fieldName] = [fieldMin, fieldMax]
if fieldEnable == "false":
if fieldDisable.count(fieldName) == 0:
fieldDisable.append(fieldName)
if fieldMultiline == "true":
multilineFields.append(fieldName)
if lookupField != "":
lookupFields[fieldName] = lookupField
if whereClause != "":
whereClauses[fieldName] = whereClause
else:
DbError(query)
query.finish()
return [skip, labels, fieldOrder, fieldGroups, minMax, noSearchFields,
createAction, helpText, fieldDisable, multilineFields, lookupFields,
whereClauses]
def __createForms(self, thisTable, db, skip, labels, fieldOrder,
fieldGroups, minMax, noSearchFields, showParents,
showChildren, readConfigTables, createAction, fieldDisable,
multilineFields, lookupFields, whereClauses):
"""create the forms (DdFom instances) shown in the tabs of the Dialog (DdDialog instance)"""
ddForms = []
ddSearchForms = []
ddAttributes = self.getAttributes(
thisTable, db, labels, minMax, fieldDisable = fieldDisable, \
multilineFields = multilineFields, lookupFields = lookupFields,
whereClauses = whereClauses)
# do not pass skip here otherwise pk fields might not be included
for anAtt in ddAttributes:
if anAtt.isPK:
n2mAttributes = self.getN2mAttributes(db, thisTable, anAtt.name,
anAtt.num, labels, showChildren, skip, fieldDisable, whereClauses)
ddAttributes = ddAttributes + n2mAttributes
#check if we need a QToolBox
needsToolBox = (len(ddAttributes) > 5)
unorderedAttributes = []
msg = ""
# loop through the attributes and get one-line types (QLineEdit, QComboBox) first
for anAttribute in ddAttributes:
msg = msg + " " + anAttribute.name
nextAtt = False
#check if this attribute is supposed to be skipped
for skipName in skip:
if skipName == anAttribute.name:
nextAtt = True
break
if nextAtt:
continue # skip it
if (anAttribute.type == "text" and anAttribute.multiLine != False) or \
anAttribute.type == "n2m" or anAttribute.type == "table":
needsToolBox = True
unorderedAttributes.append(anAttribute)
# create an ordered list of attributes
if len(fieldOrder) > 0:
orderedAttributes = []
for aFieldName in fieldOrder:
counter = 0
while counter < len(unorderedAttributes):
anAttribute = unorderedAttributes.pop()
if aFieldName == anAttribute.name:
orderedAttributes.append(anAttribute)
break
else:
unorderedAttributes.insert(0, anAttribute)
counter += 1
# put the rest in
orderedAttributes.extend(unorderedAttributes)
else:
orderedAttributes = unorderedAttributes
defaultFormWidget = DdFormWidget(thisTable, needsToolBox)
defaultSearchFormWidget = DdFormWidget(thisTable, needsToolBox)
useFieldGroups = (len(fieldGroups) > 0 and len(fieldOrder) > 0)
if not useFieldGroups:
# we only need one form
ddFormWidget = defaultFormWidget
ddSearchFormWidget = defaultSearchFormWidget
else:
ddFormWidget = None
for anAttribute in orderedAttributes:
addToSearch = True
for key in list(fieldGroups.keys()):
if key == anAttribute.name:
# we need a new form
if ddFormWidget != None:
# there is one active, add them to the lists
ddForms.append(ddFormWidget)
ddSearchForms.append(ddSearchFormWidget)
tabTitle = fieldGroups[key][0]
try:
tabToolTip = fieldGroups[key][1]
except:
tabToolTip = ""
aTable = DdTable(thisTable.oid, thisTable.schemaName, thisTable.tableName, tabToolTip, tabTitle)
ddFormWidget = DdFormWidget(aTable, needsToolBox)
ddSearchFormWidget = DdFormWidget(aTable, needsToolBox)
break
if anAttribute.type == "n2m":
if anAttribute.subType == "list":
ddInputWidget = DdN2mListWidget(anAttribute)
elif anAttribute.subType == "tree":
ddInputWidget = DdN2mTreeWidget(anAttribute)
elif anAttribute.type == "table":
ddInputWidget = DdN2mTableWidget(anAttribute)
#addToSearch = False
else: # one line attributes
if anAttribute.isFK:
ddInputWidget = DdComboBox(anAttribute)
else:
if anAttribute.isTypeFloat():
if anAttribute.isArray:
ddInputWidget = DdArrayTableWidgetDouble(anAttribute)
else:
ddInputWidget = DdLineEditDouble(anAttribute)
elif anAttribute.isTypeInt():
if anAttribute.isArray:
ddInputWidget = DdArrayTableWidgetInt(anAttribute)
else:
ddInputWidget = DdLineEditInt(anAttribute)
else:
if anAttribute.type == "bool":
if anAttribute.isArray:
ddInputWidget = DdArrayTableWidgetBool(anAttribute)
else:
ddInputWidget = DdLineEditBoolean(anAttribute)
elif anAttribute.type == "date":
if anAttribute.isArray:
ddInputWidget = DdArrayTableWidgetDate(anAttribute)
else:
ddInputWidget = DdDateEdit(anAttribute)
elif anAttribute.type == "geometry":
ddInputWidget = DdLineEditGeometry(anAttribute)
addToSearch = False
else:
if anAttribute.isArray:
ddInputWidget = DdArrayTableWidget(anAttribute)
else:
if anAttribute.multiLine or \
((anAttribute.type == "text" or (\
anAttribute.type == "varchar" and anAttribute.length > 256))
and anAttribute.multiLine == None):
ddInputWidget = DdTextEdit(anAttribute)
else:
ddInputWidget = DdLineEdit(anAttribute)
if ddFormWidget == None:
# fallback in case fieldOrder and fieldGroups do not match
ddFormWidget = defaultFormWidget
ddSearchFormWidget = defaultSearchFormWidget
ddFormWidget.addInputWidget(ddInputWidget)
if addToSearch:
if len(noSearchFields) > 0:
addToSearch = (noSearchFields.count(anAttribute.name) == 0)
if addToSearch:
ddSearchFormWidget.addInputWidget(ddInputWidget)
ddForms.append(ddFormWidget)
ddSearchForms.append(ddSearchFormWidget)
if showParents:
# do not show this table in the parent's form
skip.append(thisTable.tableName)
# go recursivly into thisTable's parents
for aParent in self.getParents(thisTable, db):
if readConfigTables:
pSkip, pLabels, pFieldOrder, pFieldGroups, pMinMax, \
pNoSearchFields, pCreateAction, pHelpText, pFieldDisable, \
pMultilineFields, pLookupFields, pWhereClauses = \
self.configureLayer(aParent, [], {}, [], {}, {}, [], db, createAction, "", [])
if pSkip == []:
pSkip = skip
if pLabels == {}:
pLabels = labels
if pFieldOrder == []:
pFieldOrder = fieldOrder
if pFieldGroups == {}:
pFieldGroups = fieldGroups
if pMinMax == {}:
pMinMax = minMax
if pNoSearchFields == []:
pNoSearchFields = noSearchFields
if pFieldDisable == []:
pFieldDisable = fieldDisable
parentForms, parentSearchForms = self.__createForms(aParent, db,
pSkip, pLabels, pFieldOrder, pFieldGroups, pMinMax,
pNoSearchFields, showParents, False, readConfigTables,
pCreateAction, pFieldDisable, pMultilineFields, pLookupFields, pWhereClauses)
ddForms = ddForms + parentForms
ddSearchForms = ddSearchForms + parentSearchForms
return [ddForms, ddSearchForms]
def createUi(self, thisTable, db, skip = [], labels = {}, fieldOrder = [], fieldGroups = {}, minMax = {}, \
noSearchFields = [], showParents = True, showChildren = True, inputMask = True, searchMask = True, \
helpText = "", createAction = True, readConfigTables = False, fieldDisable = []):
'''creates default uis for this table (DdTable instance)
showChildren [Boolean]: show tabs for 1-to-1 relations (children)
see ddmanager.initLayer for other parameters
'''
if readConfigTables:
skip, labels, fieldOrder, fieldGroups, minMax, noSearchFields, \
createAction, helpText, fieldDisable, multilineFields, lookupFields, \
whereClauses \
= self.configureLayer( \
thisTable, skip, labels, fieldOrder, fieldGroups, minMax, \
noSearchFields, db, createAction, \
helpText, fieldDisable)
forms, searchForms = self.__createForms(
thisTable, db, skip, labels, fieldOrder, fieldGroups,
minMax, noSearchFields, showParents, showChildren,
readConfigTables, createAction, fieldDisable, multilineFields,
lookupFields, whereClauses)
if inputMask:
ui = DdDialogWidget()
ui.setHelpText(helpText)
for ddFormWidget in forms:
ui.addFormWidget(ddFormWidget)
else:
ui = None
if searchMask:
searchUi = DdDialogWidget()
for ddFormWidget in searchForms:
searchUi.addFormWidget(ddFormWidget)
else:
searchUi = None
return [ui, searchUi]
def getParent(self, thisTable, db):
''' deprecated'''
#Problem: eine Tabelle kann mehrere Eltern haben
query = QtSql.QSqlQuery(db)
sQuery = "SELECT c.oid, n.nspname, c.relname \
FROM pg_inherits i \
JOIN pg_class c ON i.inhparent = c.oid \
JOIN pg_namespace n ON c.relnamespace = n.oid \
WHERE i.inhrelid = :oid"
query.prepare(sQuery)
query.bindValue(":oid", thisTable.oid)
query.exec_()
parentTable = DdTable()
if query.isActive():
if query.size() == 0:
query.finish()
else:
while query.next():
oid = query.value(0)
schema = query.value(1)
table = query.value(2)
parentTable.oid = oid
parentTable.schemaName = schema
parentTable.tableName = table
break
query.finish()
else:
DbError(query)
return parentTable
def getParents(self, thisTable, db):
''' query the DB to get a table's parents if any
A table has a parent if its primary key is defined on one field only and is at the same time
a foreign key to another table's primary key. Thus there is a 1:1
relationship between the two.'''
query = QtSql.QSqlQuery(db)
sQuery = "SELECT \
c.oid, ns.nspname, c.relname, COALESCE(d.description,'') \
FROM pg_attribute att \
JOIN (SELECT * FROM pg_constraint WHERE contype = 'f') fcon ON att.attrelid = fcon.conrelid AND att.attnum = ANY (fcon.conkey) \
JOIN (SELECT * FROM pg_constraint WHERE contype = 'p') pcon ON att.attrelid = pcon.conrelid AND att.attnum = ANY (pcon.conkey) \
JOIN pg_class c ON fcon.confrelid = c.oid \
JOIN pg_namespace ns ON c.relnamespace = ns.oid \
LEFT JOIN (SELECT * FROM pg_description WHERE objsubid = 0) d ON c.oid = d.objoid \
WHERE att.attnum > 0 \
AND att.attisdropped = false \
AND att.attrelid = :oid \
AND array_length(pcon.conkey, 1) = 1"
# AND array_length(pcon.conkey, 1) = 1:
# if we have a combined PK we are in a n-to-m relational table
# pg_description.objsubid = 0 for description on tables
query.prepare(sQuery)
query.bindValue(":oid", thisTable.oid)
query.exec_()
parents = []
if query.isActive():
if query.size() == 0:
query.finish()
else:
while query.next():
oid = query.value(0)
schema = query.value(1)
table = query.value(2)
comment = query.value(3)
parentTable = DdTable(oid, schema, table, comment)
parents.append(parentTable)
query.finish()
else:
DbError(query)
return parents
def getN2mAttributes(self, db, thisTable, attName, attNum, labels,
showChildren, skip = [], fieldDisable = [], whereClauses = {}):
'''find those tables (n2mtable) where our pk is a fk'''
n2mAttributes = []
pkQuery = QtSql.QSqlQuery(db)
sPkQuery = "SELECT array_length(pk.conkey, 1), att.attname, att.attnum, c.oid as table_oid,n.nspname,c.relname, f.numfields, COALESCE(d.description,'') as comment, COALESCE(inpk.in,0) as inpk \
FROM pg_attribute att \
JOIN (SELECT * FROM pg_constraint WHERE contype = 'f') fk ON att.attrelid = fk.conrelid AND att.attnum = ANY (fk.conkey) \
JOIN (SELECT * FROM pg_constraint WHERE contype = 'p') pk ON pk.conrelid = fk.conrelid \
LEFT JOIN (SELECT 1 AS in, conrelid, conkey FROM pg_constraint where contype = 'p') inpk ON inpk.conrelid = fk.conrelid AND att.attnum = ANY (inpk.conkey) \
JOIN pg_class c ON fk.conrelid = c.oid \
JOIN pg_namespace n ON c.relnamespace = n.oid \
LEFT JOIN pg_description d ON c.oid = d.objoid AND 0 = d.objsubid \
JOIN(SELECT attrelid, count(attrelid) as numfields \
FROM pg_attribute \
WHERE attnum > 0 \
AND attisdropped = false \
GROUP BY attrelid) f ON c.oid = f.attrelid \
WHERE fk.confrelid = :oid \
AND :attNum = ANY(fk.confkey) "
# 0 = d.objsubid: comment on table only, not on its columns
pkQuery.prepare(sPkQuery)
pkQuery.bindValue(":oid", thisTable.oid)
pkQuery.bindValue(":attNum", attNum)
pkQuery.exec_()
if pkQuery.isActive():
while pkQuery.next():
numPkFields = pkQuery.value(0)
relationFeatureIdField = pkQuery.value(1)
fkAttNum = pkQuery.value(2) #is the attribute number in n2mtable
relationOid = pkQuery.value(3)
relationSchema = pkQuery.value(4)
relationTable = pkQuery.value(5)
numFields = pkQuery.value(6)
relationComment = pkQuery.value(7)
inPk = bool(pkQuery.value(8))
ddRelationTable = DdTable(relationOid, relationSchema, relationTable)
if inPk: # either n:m or 1:1
if numPkFields == 1: # 1:1 relation
if showChildren:
# show 1:1 related tables, too
subType = "table"
maxRows = 1
showParents = False
else:
continue
elif numPkFields > 1: # n:m relation
if numFields == 2:
# get the related table i.e. the table where the other FK field is the PK
relatedQuery = QtSql.QSqlQuery(db)
sRelatedQuery = "SELECT c.oid, n.nspname, c.relname, att.attname \
FROM pg_constraint con \
JOIN pg_class c ON con.confrelid = c.oid \
JOIN pg_namespace n ON c.relnamespace = n.oid \
JOIN (\
SELECT * \
FROM pg_attribute \
WHERE attnum > 0 \
AND attisdropped = false \
AND attnum != :attNum1 \
) att ON con.conrelid = att.attrelid \
WHERE conrelid = :relationOid \
AND contype = 'f' \
AND :attNum2 != ANY(conkey)"
# we do not want the table where we came from in the results, therefore :attNum != ANY(confkey)
# JOIN pg_class c ON con.confrelid = c.oid -- referenced table
# WHERE conrelid = :relationOid -- table this constraint is on
# AND contype = 'f' -- foreign key constraint
# AND :attNum2 != ANY(conkey) -- list of constrained columns
relatedQuery.prepare(sRelatedQuery)
relatedQuery.bindValue(":relationOid", relationOid)
relatedQuery.bindValue(":attNum1", fkAttNum)
relatedQuery.bindValue(":attNum2", fkAttNum)
relatedQuery.exec_()
if relatedQuery.isActive():
if relatedQuery.size() == 0: #no relatedTable but a Table with two PK columns
subType = "table"
maxRows = 1
showParents = False
elif relatedQuery.size() == 1:
while relatedQuery.next():
relatedOid = relatedQuery.value(0)
relatedSchema = relatedQuery.value(1)
relatedTable = relatedQuery.value(2)
relationRelatedIdField = relatedQuery.value(3)
ddRelatedTable = DdTable(relatedOid, relatedSchema, relatedTable)
relatedQuery.finish()
relatedFieldsQuery = QtSql.QSqlQuery(db)
relatedFieldsQuery.prepare(self.__attributeQuery("att.attnum"))
relatedFieldsQuery.bindValue(":oid", relatedOid)
relatedFieldsQuery.exec_()
if relatedFieldsQuery.isActive():
if relatedFieldsQuery.size() == 2:
subType = "list"
else:
subType = "tree"
relatedIdField = None
relatedDisplayCandidate = None
relatedDisplayField = None
i = 0
fieldList = []
while relatedFieldsQuery.next():
relatedAttName = relatedFieldsQuery.value(0)
relatedAttNum = relatedFieldsQuery.value(1)
relatedAttNotNull = bool(relatedFieldsQuery.value(2))
relatedAttHasDefault = bool(relatedFieldsQuery.value(3))
relatedAttIsChild = bool(relatedFieldsQuery.value(4))
relatedAttLength = relatedFieldsQuery.value(5)
relatedAttTyp = relatedFieldsQuery.value(6)
relatedAttComment = relatedFieldsQuery.value(7)
relatedAttDefault = relatedFieldsQuery.value(8)
relatedAttConstraint = relatedFieldsQuery.value(9)
if relatedAttConstraint == "p": # PK of the related table
relatedIdField = relatedAttName
if relatedAttTyp == "varchar" or relatedAttTyp == "char":
if relatedAttNotNull and not relatedDisplayField: # we use the first one
relatedDisplayField = relatedAttName
#we display only char attributes
fieldList.append(relatedAttName)
relatedFieldsQuery.finish()
if not relatedDisplayCandidate: # there was no string field
relatedDisplayCandidate = relatedIdField
if not relatedDisplayField: # there was no notNull string field
relatedDisplayField = relatedDisplayCandidate
else:
DbError(relatedFieldsQuery)
else:
subType = "table"
maxRows = None
showParents = False
relatedQuery.finish()
else:
DbError(relatedQuery)
elif numFields > 2:
subType = "table"
maxRows = None
showParents = False
try:
attLabel = labels[str(relationTable)]
except KeyError:
attLabel = None
else: # 1:n relation
subType = "table"
maxRows = None
showParents = True
try:
attLabel = labels[str(relationTable) + " (" + str(relationFeatureIdField) + ")"]
except KeyError:
attLabel = str(relationTable) + " (" + str(relationFeatureIdField) + ")"
attEnableWidget = fieldDisable.count(ddRelationTable.tableName) == 0
if subType == "table":
configList = self.configureLayer(
ddRelationTable, [], {}, [], {}, {}, [], db, True, "", [])
skipThese = configList[0]
rLabels = configList[1]
rMinMax = configList[4]
multilineFields = configList[9]
lookupFields = configList[10]
whereClauses = configList[11]
attributes = self.getAttributes(
ddRelationTable, db, rLabels, rMinMax, skipThese, \
multilineFields = multilineFields, lookupFields = lookupFields,
whereClauses = whereClauses)
attrsToKeep = []
for aRelAtt in attributes:
if aRelAtt.type != "geometry":
attrsToKeep.append(aRelAtt)
ddAtt = DdTableAttribute(
ddRelationTable, relationComment, attLabel, relationFeatureIdField,
attrsToKeep, maxRows, showParents, attName, attEnableWidget)
else:
relatedForeignKeys = self.getForeignKeys(ddRelatedTable, db)
try:
whereClause = whereClauses[ddRelationTable.tableName]
except:
whereClause = ""
ddAtt = DdN2mAttribute(
ddRelationTable, ddRelatedTable, subType, relationComment,
attLabel, relationFeatureIdField, relationRelatedIdField,
relatedIdField, relatedDisplayField, fieldList, relatedForeignKeys,
attEnableWidget, whereClause)
try:
skip.index(ddAtt.name)
addAtt = False
except:
addAtt = True
if addAtt:
n2mAttributes.append(ddAtt)
pkQuery.finish()
else:
DbError(pkQuery)
return n2mAttributes
def getAttributes(self, thisTable, db, labels, minMax, skip = [], fieldDisable = [],
multilineFields= [], lookupFields = {}, whereClauses = {}):
''' query the DB and create DdAttributes'''
ddAttributes = []
query = QtSql.QSqlQuery(db)
sQuery = self.__attributeQuery("att.attnum")
query.prepare(sQuery)
query.bindValue(":oid", thisTable.oid)
query.exec_()
retValue = dict()
if query.isActive():
if query.size() == 0:
query.finish()
else:
foreignKeys = self.getForeignKeys(thisTable, db)
while query.next():
attName = query.value(0)
nextResult = False
for skipName in skip:
if skipName == attName:
nextResult = True
break
if nextResult:
continue
attNum = query.value(1)
attNotNull = query.value(2)
attHasDefault = query.value(3)
attIsChild = query.value(4)
attLength = query.value(5)
attTyp = query.value(6)
attComment = query.value(7)
attDefault = query.value(8)
attConstraint = query.value(9)
constrainedAttNums = query.value(10)
attCategory = query.value(11)
arrayDelim = query.value(12)
attTyp = attTyp.replace("_", "") # if array type is e.g. _varchar
if not self.isSupportedType(attTyp):
continue
attEnableWidget = fieldDisable.count(attName) == 0
isPK = attConstraint == "p" # PrimaryKey
isArray = attCategory == "A"
if isArray:
normalAtt = True
else:
if isPK:
constrainedAttNums = constrainedAttNums.replace("{", "").replace("}", "").split(",")
else:
constrainedAttNums = []
if isPK and len(constrainedAttNums) == 1:
# if table has a single PK we do not care if it is a FK, too because we
# do not treat a parent in a 1:1 relation as lookup table
normalAtt = True
else:
try: # is this attribute a FK
fk = foreignKeys[attName]
queryForCbx = fk[1]
valueField = fk[2]
try:
lookupExpression = lookupFields[str(attName)]
queryForCbx = queryForCbx.replace("\"" + valueField + "\" as value", \
lookupExpression + " as value")
queryForCbx = queryForCbx.replace(valueField + " as value", \
lookupExpression + " as value") # we do not know if the field is quoted
except:
lookupExpression = None
try:
attLabel = labels[str(attName)]
except KeyError:
if lookupExpression == None:
attLabel = attName + " (" + valueField + ")"
else:
attLabel = attName + " (" + lookupExpression + ")"
try:
whereClause = whereClauses[str(attName)]
except:
whereClause = ""
try:
fkComment = fk[3]
except IndexError:
fkComment = ""
if attComment == "":
attComment = fkComment
else:
if not fkComment == "":
attComment = attComment + "\n(" + fkComment + ")"
ddAtt = DdFkLayerAttribute(
thisTable, attTyp, attNotNull, attName, attComment,
attNum, isPK, attDefault, attHasDefault, queryForCbx, attLabel,
attEnableWidget, whereClause)
normalAtt = False
except KeyError:
# no fk defined
normalAtt = True
if normalAtt:
try:
attLabel = labels[str(attName)]
except KeyError:
attLabel = None
try:
thisMinMax = minMax[str(attName)]
except KeyError:
thisMinMax = None
if thisMinMax == None:
thisMin = None
thisMax = None
else:
thisMin = thisMinMax[0]
thisMax = thisMinMax[1]
if attTyp == "date":
ddAtt = DdDateLayerAttribute(
thisTable, attTyp, attNotNull, attName, attComment, attNum,
isPK, False, attDefault, attHasDefault, attLength, attLabel,
thisMin, thisMax, enableWidget = attEnableWidget,
isArray = isArray, arrayDelim = arrayDelim)
elif attTyp == "geometry":
ddAtt = DdGeometryAttribute(
thisTable, attTyp, attName, attComment, attNum)
else:
multiLine = multilineFields.count(str(attName)) != 0
ddAtt = DdLayerAttribute(
thisTable, attTyp, attNotNull, attName, attComment, attNum,
isPK, False, attDefault, attHasDefault, attLength, attLabel,
thisMin, thisMax, attEnableWidget, isArray, arrayDelim, multiLine)
ddAttributes.append(ddAtt)
query.finish()
else:
DbError(query)
return ddAttributes
def isSupportedType(self, typ):
supportedAttributeTypes = ["int2", "int4", "int8",
"bpchar", "varchar", "float4", "float8", "text",
"bool", "date", "geometry"]
supported = False
for aTyp in supportedAttributeTypes:
if aTyp == typ:
supported = True
break
return supported
def getForeignKeys(self, thisTable, db):
'''querys this table's foreign keys and returns a dict
attnum: [str: Type of the lookup field, str: sql to query lookup values, str: Name of the value field in the lookup table, str: Comment on lookup table]'''
query = QtSql.QSqlQuery(db)
sQuery = "SELECT \
att.attname, \
t.typname as typ, \
CAST(valatt.attnotnull as integer) as notnull, \
valatt.attname, \
((((((('SELECT ' || quote_ident(valatt.attname)) || ' as value, ') || quote_ident(refatt.attname)) || ' as key FROM ') \
|| quote_ident(ns.nspname)) || '.') || quote_ident(c.relname)) || ' ;' AS sql_key, \
((((((('SELECT ' || quote_ident(refatt.attname)) || ' as value, ') || quote_ident(refatt.attname)) || ' as key FROM ') \
|| quote_ident(ns.nspname)) || '.') || quote_ident(c.relname)) || ' ;' AS default_sql, \
COALESCE(d.description, '') as comment, \
COALESCE(valcon.contype, 'x') as valcontype \
FROM pg_attribute att \
JOIN (SELECT * FROM pg_constraint WHERE contype = 'f') con ON att.attrelid = con.conrelid AND att.attnum = ANY (con.conkey) \
JOIN pg_class c ON con.confrelid = c.oid \
JOIN pg_namespace ns ON c.relnamespace = ns.oid \
JOIN pg_attribute refatt ON con.confrelid = refatt.attrelid AND con.confkey[1] = refatt.attnum \
JOIN pg_attribute valatt ON con.confrelid = valatt.attrelid \
LEFT JOIN pg_constraint valcon ON valatt.attrelid = valcon.conrelid AND valatt.attnum = ANY (valcon.conkey)\
JOIN pg_type t ON valatt.atttypid = t.oid \
LEFT JOIN pg_description d ON con.confrelid = d.objoid AND 0 = d.objsubid \
WHERE att.attnum > 0 \
AND att.attisdropped = false \
AND valatt.attnum > 0 \
AND valatt.attisdropped = false \
AND att.attrelid = :oid \
ORDER BY att.attnum, valatt.attnum"
# Query returns all fields in the lookup table for each attnum
# JOIN valcon in order to not display any fields that are FKs themsselves
# add "AND valatt.attnum != con.confkey[1]" if you want to keep PKs out
query.prepare(sQuery)
query.bindValue(":oid", thisTable.oid)
query.exec_()
foreignKeys = dict()
if query.isActive():
while query.next():
attName = query.value(0)
fieldType = query.value(1)
notNull = query.value(2)
valAttName = query.value(3)
keySql = query.value(4)
defaultSql = query.value(5)
comment = query.value(6)
contype = query.value(7)
if contype == "f":
continue
try:
fk = foreignKeys[attName]
if fk[0] != "varchar": # we do not already have a varchar field as value field
# find a field with a suitable type
if notNull and (fieldType == "varchar" or fieldType == "char"):
foreignKeys[attName] = [fieldType, keySql, valAttName, comment]
except KeyError:
if notNull and (fieldType == "varchar" or fieldType == "char"):
foreignKeys[attName] = [fieldType, keySql, valAttName, comment]