-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathddattribute.py
More file actions
429 lines (353 loc) · 18.6 KB
/
ddattribute.py
File metadata and controls
429 lines (353 loc) · 18.6 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
# -*- coding: utf-8 -*-
"""
ddattribute
---------------------
Each DdAttribute corresponds to an input widget in the mask or each input widget is based on exactly one DdAttribute.
General rules:
```````````````````````
#) every field has an input widget suitable for its type
#) no ARRAY typees are supported
#) supported types are: int4, int8, float, date, boolean, char, varchar, text
#) foreign keys are represented as comboboxes and are only supported if based on one field (exactly one fk field in the table references exactly one pk field in the referenced table)
#) the table referenced by a foreign key should have at least one field wit a notNull constraint apart from the primary key. This field will be used as display field in the combobox
#) if a varchar field is present in a table referenced by a foreign key it is used as display field in the combobox, if there are several the one defined earlier is used
#) if no varchar field is present any char field is used
#) if no varchar or char fields are available the pk field is used for display
#) table inheritance is not covered
#) if a table's pk is a fk to another table's pk the other table's mask is shown in a second tab
"""
"""
/***************************************************************************
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 object
from qgis.PyQt import QtWidgets, QtCore
class DdTable(object):
'''holds all information for a DB table relation'''
def __init__(self, oid = None, schemaName = "None", tableName = "None", comment = "", title = None):
self.oid = oid
self.schemaName = schemaName
self.tableName = tableName
self.comment = comment
self.title = title
def __str__(self):
return "<ddattribute.DdTable %s.%s>" % (self.schemaName, self.tableName)
class DdAttribute(object):
'''abstract super class for all DdAttributes'''
def __init__(self, table, type, notNull, name, comment , label,
min = None, max = None, enableWidget = True):
self.table = table
self.type = type
self.notNull = notNull
self.name = name
self.comment = comment
self.label = label
self.setMinMax(min, max)
self.enableWidget = enableWidget
def __str__(self):
return "<ddattribute.DdAttribute %s>" % self.name
def isTypeInt(self):
return (self.type == "int2") or (self.type == "int4") or (self.type == "int8")
def isTypeFloat(self):
return (self.type == "float4") or (self.type == "float8")
def isTypeChar(self):
return (self.type == "char") or (self.type == "varchar") or (self.type == "bpchar")
# bpchar "blank-padded char" = internal name of char type
def getLabel(self):
if self.label:
labelString = self.label
else:
labelString = self.name
return labelString
def setMinMax(self, min, max):
self.min = None
self.max = None
if self.isTypeInt:
if min != None:
try:
self.min = int(round(float(min)))
except:
self.min = None
else:
if self.type == "int2":
self.min = -32768
elif self.type == "int4":
self.min = -2147483648
elif self.type == "int8":
self.min = -9223372036854775808
if max != None:
try:
self.max = int(round(float(max)))
except:
self.max = None
else:
if self.type == "int2":
self.max = 32767
elif self.type == "int4":
self.max = 2147483647
elif self.type == "int8":
self.max = 9223372036854775807
elif self.isTypeFloat:
if min != None:
try:
self.min = float(min)
except:
self.min = None
if max != None:
try:
self.max = float(max)
except:
self.max = None
def debug(self, msg):
QtWidgets.QMessageBox.information(None, "Debug", msg)
class DdLayerAttribute(DdAttribute):
'''a DdAttribute for a field in a QGIS layer'''
def __init__(self, table, type, notNull, name, comment, attNum, isPK, isFK,
default, hasDefault, length, label = None, min = None, max = None,
enableWidget = True, isArray = False, arrayDelim = "", multiLine = None):
super().__init__(table, type, notNull, name, comment,
label, min, max, enableWidget)
self.isPK = isPK
self.isFK = isFK
self.default = default
self.hasDefault = hasDefault
self.length = length
self.num = attNum # number of the attribute in the table pg_attribute.attNum
self.isArray = isArray
self.arrayDelim = arrayDelim
self.multiLine = multiLine # multiLine == None: use default, i.e. textBox for text and long varchar
def __str__(self):
return "<ddattribute.DdLayerAttribute %s>" % self.name
class DdGeometryAttribute(DdLayerAttribute):
'''a DdAttribute for a geometry field in a QGIS layer'''
def __init__(self, table, type, name, comment, attNum):
super().__init__(table, type, True, name, comment,
attNum, False, False, None, False, 0, enableWidget = False)
def __str__(self):
return "<ddattribute.DdGeometryAttribute %s>" % self.name
class DdDateLayerAttribute(DdLayerAttribute):
'''a DdAttribute for a date field in a QGIS layer
if you want to specify today as min or max, simply pass "today"'''
def __init__(self, table, type, notNull, name, comment, attNum, isPK,
isFK, default, hasDefault, length, label = None, min = None,
max = None, dateFormat = "yyyy-MM-dd", enableWidget = True,
isArray = False, arrayDelim = ""):
self.dateFormat = dateFormat # set here because DdAttribute calls setMinMax on __init__
super().__init__(table, type, notNull, name,
comment, attNum, isPK, isFK, default, hasDefault, length,
label, min, max, enableWidget, isArray, arrayDelim)
def __str__(self):
return "<ddattribute.DdDateLayerAttribute %s>" % self.name
def setMinMax(self, min, max):
'''reimplemented from DdAttribute'''
self.min = self.formatDate(min)
self.max = self.formatDate(max)
def formatDate(self, thisDate):
'''thisDate may be either a QDate or a string'''
if thisDate != None:
if not isinstance(thisDate, QtCore.QDate):
# we assume a string
if thisDate.find("today") != -1:
if thisDate.find("-") != -1:
factor = -1
daysToAdd = thisDate.split("-")[1].strip()
else:
factor = 1
if thisDate.find("+") != -1:
daysToAdd = thisDate.split("+")[1].strip()
else:
daysToAdd = "0"
returnDate = QtCore.QDate.currentDate().addDays(int(daysToAdd) * factor)
else:
returnDate = QtCore.QDate.fromString(thisDate, self.dateFormat)
# returns a null date if string is not formatted as needed by dateFormat
if returnDate.isNull():
returnDate = None
else:
returnDate = None
return returnDate
class DdFkLayerAttribute(DdLayerAttribute):
'''a DdAttribute for field in a QGIS layer that represents a foreign key'''
def __init__(self, table, type, notNull, name, comment, attNum, isPK,
default , hasDefault, queryForCbx, label = None, enableWidget = True,
whereClause = ""):
super().__init__(table, type, notNull, name, comment,
attNum, isPK, True, default, hasDefault, -1, label,
enableWidget = enableWidget)
if whereClause == "":
self.setQueryForCbx(queryForCbx)
else:
self.setQueryForCbx(queryForCbx.replace(";", " WHERE " + whereClause + ";"))
def __str__(self):
return "<ddattribute.DdFkLayerAttribute %s>" % self.name
def getQueryForCbx(self):
return self.queryForCbx
def setQueryForCbx(self, newQuery):
self.queryForCbx = newQuery
class DdManyToManyAttribute(DdAttribute):
'''abstract class for any many2many attribute'''
def __init__(self, relationTable, type, relationFeatureIdField,
comment, label, enableWidget = True):
super().__init__(relationTable, type, False,
relationTable.tableName, comment, label, enableWidget = enableWidget)
self.relationFeatureIdField = relationFeatureIdField
self.setSubsetString()
def buildSubsetString(self, relationFeatureIdField):
'''builld the subset string to be applied as filter on the layer'''
subsetString = "\"" + relationFeatureIdField + "\" IN "
return subsetString
def setSubsetString(self, subsetString = None):
if not subsetString:
subsetString = self.buildSubsetString(self.relationFeatureIdField)
self.subsetString = subsetString
class DdTableAttribute(DdManyToManyAttribute):
'''a DdAttribute for a relationTable'''
def __init__(self, relationTable, comment, label, relationFeatureIdField,
attributes, maxRows, showParents, pkAttName, enableWidget = True):
super().__init__(relationTable, "table",
relationFeatureIdField, comment, label, enableWidget)
self.attributes = attributes # an array with DdAttributes
self.pkAttName = pkAttName
for anAtt in self.attributes:
if anAtt.name == self.relationFeatureIdField:
self.attributes.remove(anAtt)
break
self.maxRows = maxRows
self.showParents = showParents
class DdN2mAttribute(DdManyToManyAttribute):
'''a DdAttribute for a n2m relation, subtype can be list or tree
relationTable and relatedTable are DdTable objects'''
def __init__(self, relationTable, relatedTable, subType, comment , label,
relationFeatureIdField, relationRelatedIdField, relatedIdField,
relatedDisplayField, fieldList = [], relatedForeignKeys = [],
enableWidget = True, whereClause = ""):
super().__init__(relationTable, "n2m",
relationFeatureIdField, comment, label, enableWidget)
self.subType = subType
self.relatedTable = relatedTable
self.relationRelatedIdField = relationRelatedIdField
self.relatedIdField = relatedIdField
self.relatedDisplayField = relatedDisplayField
self.fieldList = fieldList # an array with fields names
self.relatedForeignKeys = relatedForeignKeys
self.whereClause = whereClause
# init statements
self.setDisplayStatement()
self.setInsertStatement()
self.setDeleteStatement()
def __str__(self):
return "<ddattribute.DdN2mAttribute %s>" % str(self.name)
def buildDisplayStatement(self, relationSchema, relationTable, relatedSchema, relatedTable, relationFeatureIdField, \
relatedIdField, relatedDisplayField, relationRelatedIdField, fieldList, whereClause):
displayStatement ="SELECT disp.\"" + relatedIdField + "\", disp.\"" + relatedDisplayField + "\","
displayStatement += " CASE COALESCE(lnk.\"" + relationFeatureIdField + "\", 0) WHEN 0 THEN 0 ELSE 2 END as checked"
# for "list" this is how it is supposed to look like
#SELECT disp."id", disp."eigenschaft", CASE COALESCE(lnk."polygon_gid", 0) WHEN 0 THEN 0 ELSE 2 END as checked
#FROM "alchemy"."eigenschaft" disp
#LEFT JOIN (SELECT * FROM "alchemy"."polygon_has_eigenschaft" WHERE "polygon_gid" = :featureId) lnk ON disp."id" = lnk."eigenschaft_id"
# optional, example WHERE disp.id IN (x,y)
#ORDER BY disp."eigenschaft"
if self.subType == "tree":
for aField in fieldList:
if aField != relatedDisplayField: # no doubles
displayStatement += ", \'" + aField + ": \' || COALESCE(disp.\"" + aField + "\", \'NULL\')"
if len(self.relatedForeignKeys) > 0:
for aKey, aValue in list(self.relatedForeignKeys.items()):
displayFieldName = aValue[2]
self.fieldList.append("fk_" + aKey + ".value")
displayStatement += ", \'" + displayFieldName + ": \' || fk_" + aKey + ".value"
displayStatement += " FROM \"" + relatedSchema + "\".\"" + relatedTable + "\" disp"
if self.enableWidget:
displayStatement += " LEFT"
displayStatement += " JOIN (SELECT * FROM \"" + relationSchema + "\".\"" + relationTable + "\""
displayStatement += " WHERE \"" + relationFeatureIdField + "\" = :featureId) lnk"
displayStatement += " ON disp.\"" + relatedIdField + "\" = lnk.\"" + relationRelatedIdField + "\""
if whereClause != "":
displayStatement += " WHERE disp." + whereClause
if len(self.relatedForeignKeys) > 0:
for aKey, aValue in list(self.relatedForeignKeys.items()):
fkSelectStatement = aValue[1]
#example: SELECT my_string as value, id as key FROM my_schema.my_lookup_table;
fkSelectStatement = fkSelectStatement[: len(fkSelectStatement) -1] # get rid of ;
displayStatement += " LEFT JOIN (" + fkSelectStatement + ") fk_" + aKey + " ON disp.\"" + aKey + "\" = fk_" + aKey + ".key"
displayStatement += " ORDER BY checked DESC, disp.\"" + relatedDisplayField + "\" NULLS LAST"
return displayStatement
def buildInsertStatement(self, relationSchema, relationTable, relationFeatureIdField, relationRelatedIdField, fieldList):
# INSERT INTO "alchemy"."polygon_has_eigenschaft"("polygon_gid", "eigenschaft_id") VALUES (:featureId, :itemId)
insertStatement = "INSERT INTO \"" + relationSchema + "\".\"" + relationTable + "\""
insertStatement += "(\"" + relationFeatureIdField + "\", \"" + relationRelatedIdField + "\")"
insertStatement += " VALUES (:featureId, :itemId)"
return insertStatement
def buildDeleteStatement(self, relationSchema, relationTable, relationFeatureIdField):
# DELETE FROM "alchemy"."polygon_has_eigenschaft" WHERE "polygon_gid" = :featureId
deleteStatement = "DELETE FROM \"" + relationSchema + "\".\"" + relationTable + "\""
deleteStatement += " WHERE \"" + relationFeatureIdField + "\" = :featureId"
return deleteStatement
def setDisplayStatement(self, displayStatement = None):
if not displayStatement:
displayStatement = self.buildDisplayStatement(self.table.schemaName, self.table.tableName, self.relatedTable.schemaName, \
self.relatedTable.tableName, self.relationFeatureIdField, self.relatedIdField, self.relatedDisplayField, \
self.relationRelatedIdField, self.fieldList, self.whereClause)
self.displayStatement = displayStatement
def setInsertStatement(self, insertStatement = None):
if not insertStatement:
insertStatement = self.buildInsertStatement(self.table.schemaName, self.table.tableName, self.relationFeatureIdField, self.relationRelatedIdField, self.fieldList)
self.insertStatement = insertStatement
def setDeleteStatement(self, deleteStatement = None):
if not deleteStatement:
deleteStatement = self.buildDeleteStatement(self.table.schemaName, self.table.tableName, self.relationFeatureIdField)
self.deleteStatement = deleteStatement
class DdPushButtonAttribute(DdAttribute):
'''a DdAttribute that draws a pushButton in the mask.
the button must be implemented as subclass of dduserclass.DdPushButton'''
def __init__(self, comment , label, enableWidget = True):
super().__init__(None, "pushButton", False, "", comment,
label, enableWidget = enableWidget)
pass
def __str__(self):
return "<ddattribute.DdPushButtonAttribute %s>" % self.name
class DdCheckableTableAttribute(DdN2mAttribute):
def __init__(self, relationTable, relatedTable, comment, label,
relationFeatureIdField, relationRelatedIdField,
relatedIdField, relatedDisplayField, attributes,
catalogTable = None, relatedCatalogIdField = None,
catalogIdField = None, catalogDisplayField = None,
catalogLabel = None, enableWidget = True):
super().__init__(relationTable, relatedTable,
"default", comment, label, relationFeatureIdField,
relationRelatedIdField, relatedIdField, relatedDisplayField,
enableWidget = enableWidget)
self.type = "checkableTable"
self.catalogTable = catalogTable
self.relatedCatalogIdField = relatedCatalogIdField
self.catalogIdField = catalogIdField
self.catalogDisplayField = catalogDisplayField
self.catalogLabel = catalogLabel
self.attributes = attributes # an array with DdAttributes
self.pkAttName = None
for anAtt in self.attributes:
if anAtt.name == self.relationFeatureIdField:
self.attributes.remove(anAtt)
break
self.maxRows = None
self.showParents = False
if self.catalogLabel == None:
self.catalogLabel = self.catalogDisplayField
def __str__(self):
return "<ddattribute.DdCheckableTableAttribute %s>" % str(self.name)