This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
forked from wonder-sk/postgis_manager
/
DlgTableProperties.py
424 lines (312 loc) · 11.7 KB
/
DlgTableProperties.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
from ui.DlgTableProperties_ui import Ui_DlgTableProperties
from DlgFieldProperties import DlgFieldProperties
from DlgAddGeometryColumn import DlgAddGeometryColumn
from DlgCreateConstraint import DlgCreateConstraint
from DlgCreateIndex import DlgCreateIndex
from DlgDbError import DlgDbError
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import postgis_utils
class SimpleTableModel(QStandardItemModel):
def __init__(self, parent, header):
QStandardItemModel.__init__(self, 0, len(header), parent)
self.header = header
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[section])
return QVariant()
class TableFieldsModel(SimpleTableModel):
def __init__(self, parent):
SimpleTableModel.__init__(self, parent, ['#', 'Name', 'Type', 'Null', 'Default'])
class TableConstraintsModel(SimpleTableModel):
def __init__(self, parent):
SimpleTableModel.__init__(self, parent, ['Name', 'Type', 'Column(s)'])
class TableIndexesModel(SimpleTableModel):
def __init__(self, parent):
SimpleTableModel.__init__(self, parent, ['Name', 'Column(s)'])
class DlgTableProperties(QDialog, Ui_DlgTableProperties):
def __init__(self, db, schema, table, parent=None):
QDialog.__init__(self, parent)
self.setupUi(self)
self.db = db
self.schema = schema
self.table = table
m = TableFieldsModel(self)
self.viewFields.setModel(m)
self.populateFields()
m = TableConstraintsModel(self)
self.viewConstraints.setModel(m)
self.populateConstraints()
m = TableIndexesModel(self)
self.viewIndexes.setModel(m)
self.populateIndexes()
self.connect(self.btnAddColumn, SIGNAL("clicked()"), self.addColumn)
self.connect(self.btnAddGeometryColumn, SIGNAL("clicked()"), self.addGeometryColumn)
self.connect(self.btnEditColumn, SIGNAL("clicked()"), self.editColumn)
self.connect(self.btnDeleteColumn, SIGNAL("clicked()"), self.deleteColumn)
self.connect(self.btnAddConstraint, SIGNAL("clicked()"), self.addConstraint)
self.connect(self.btnDeleteConstraint, SIGNAL("clicked()"), self.deleteConstraint)
self.connect(self.btnAddIndex, SIGNAL("clicked()"), self.createIndex)
self.connect(self.btnAddSpatialIndex, SIGNAL("clicked()"), self.createSpatialIndex)
self.connect(self.btnDeleteIndex, SIGNAL("clicked()"), self.deleteIndex)
def populateFields(self):
""" load field information from database """
m = self.viewFields.model()
m.clear()
self.fields = self.db.get_table_fields(self.table, self.schema)
for fld in self.fields:
item_num = QStandardItem(str(fld.num))
item_name = QStandardItem(fld.name)
item_type = QStandardItem(fld.data_type if fld.modifier == -1 else "%s(%d)" % (fld.data_type,fld.modifier))
item_null = QStandardItem(str(not fld.notnull))
if fld.hasdefault:
item_default = QStandardItem(fld.default)
else:
item_default = QStandardItem()
m.appendRow( [ item_num, item_name, item_type, item_null, item_default ] )
for col in range(4):
self.viewFields.resizeColumnToContents(col)
def currentColumn(self):
""" returns row index of selected column """
sel = self.viewFields.selectionModel()
indexes = sel.selectedRows()
if len(indexes) == 0:
QMessageBox.information(self, "sorry", "nothing selected")
return -1
return indexes[0].row()
def addColumn(self):
""" open dialog to set column info and add column to table """
dlg = DlgFieldProperties(self)
if not dlg.exec_():
return
name = unicode(dlg.editName.text())
data_type = unicode(dlg.cboType.currentText())
is_null = dlg.chkNull.isChecked()
default = unicode(dlg.editDefault.text())
if dlg.editLength.text().count() > 0:
x = dlg.editLength.text().toInt()
modifier = x[0] if x[1] else None
else:
modifier = None
new_field = postgis_utils.TableField(name, data_type, is_null, default, modifier)
self.emit(SIGNAL("aboutToChangeTable()"))
try:
# add column to table
self.db.table_add_column(self.table, new_field, self.schema)
self.populateFields()
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
def addGeometryColumn(self):
""" open dialog to add geometry column """
dlg = DlgAddGeometryColumn(self)
if not dlg.exec_():
return
name = unicode(dlg.editName.text())
geom_type = str(dlg.cboType.currentText())
dim = dlg.spinDim.value()
try:
srid = int(dlg.editSrid.text())
except ValueError:
srid = -1
self.emit(SIGNAL("aboutToChangeTable()"))
try:
self.db.add_geometry_column(self.table, geom_type, self.schema, name, srid, dim)
self.populateFields()
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
def editColumn(self):
""" open dialog to change column info and alter table appropriately """
num = self.currentColumn()
if num == -1:
return
m = self.viewFields.model()
# get column in table
# (there can be missing number if someone deleted a column)
column = unicode(m.item(num, 1).text())
for col in self.fields:
if col.name == column:
break
print col.num, col.name
dlg = DlgFieldProperties(self, col)
if not dlg.exec_():
return
new_name = unicode(dlg.editName.text())
new_data_type = unicode(dlg.cboType.currentText())
new_is_null = dlg.chkNull.isChecked()
new_default = unicode(dlg.editDefault.text())
if dlg.editLength.text().count() > 0:
x = dlg.editLength.text().toInt()
new_modifier = x[0] if x[1] else -1
else:
new_modifier = -1
self.emit(SIGNAL("aboutToChangeTable()"))
try:
if new_name != col.name:
self.db.table_column_rename(self.table, col.name, new_name, self.schema)
if new_data_type != col.data_type or new_modifier != col.modifier:
if new_modifier >= 0:
new_data_type += "(%d)" % new_modifier
self.db.table_column_set_type(self.table, new_name, new_data_type, self.schema)
if new_is_null == col.notnull:
self.db.table_column_set_null(self.table, new_name, new_is_null, self.schema)
if len(new_default) > 0 and new_default != col.default:
self.db.table_column_set_default(self.table, new_name, new_default, self.schema)
if len(new_default) == 0 and col.hasdefault:
self.db.table_column_set_default(self.table, new_name, None, self.schema)
self.populateFields()
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
def deleteColumn(self):
""" delete currently selected column """
num = self.currentColumn()
if num == -1:
return
m = self.viewFields.model()
column = m.item(num, 1).text()
data_type = m.item(num, 2).text()
res = QMessageBox.question(self, "are you sure", "really delete column '%s' ?" % column, QMessageBox.Yes | QMessageBox.No)
if res != QMessageBox.Yes:
return
self.emit(SIGNAL("aboutToChangeTable()"))
try:
if data_type == "geometry":
self.db.table_delete_geometry_column(self.table, column, self.schema)
else:
self.db.table_delete_column(self.table, column, self.schema)
self.populateFields()
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
def _field_by_number(self, num):
""" return field specified by its number or None if doesn't exist """
for fld in self.fields:
if fld.num == num:
return fld
return None
def populateConstraints(self):
m = self.viewConstraints.model()
m.clear()
self.constraints = self.db.get_table_constraints(self.table, self.schema)
for con in self.constraints:
# name
item_name = QStandardItem(con.name)
# type
if con.con_type == con.TypeCheck: con_type = "Check"
elif con.con_type == con.TypeForeignKey: con_type = "Foreign key"
elif con.con_type == con.TypePrimaryKey: con_type = "Primary key"
elif con.con_type == con.TypeUnique: con_type = "Unique"
item_type = QStandardItem(con_type)
# key(s)
cols = ""
for col in con.keys:
if len(cols) != 0: cols += ", "
cols += self._field_by_number(col).name
item_columns = QStandardItem(cols)
m.appendRow( [ item_name, item_type, item_columns ] )
for col in range(3):
self.viewConstraints.resizeColumnToContents(col)
def addConstraint(self):
""" add primary key or unique constraint """
dlg = DlgCreateConstraint(self, self.db, self.table, self.schema)
if not dlg.exec_():
return
column = unicode(dlg.cboColumn.currentText())
self.emit(SIGNAL("aboutToChangeTable()"))
try:
if dlg.radPrimaryKey.isChecked():
self.db.table_add_primary_key(self.table, column, self.schema)
else:
self.db.table_add_unique_constraint(self.table, column, self.schema)
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
return
# refresh constraints
self.populateConstraints()
def deleteConstraint(self):
""" delete a constraint """
num = self.currentConstraint()
if num == -1:
return
m = self.viewConstraints.model()
con_name = m.item(num, 0).text()
res = QMessageBox.question(self, "are you sure", "really delete constraint '%s' ?" % con_name, QMessageBox.Yes | QMessageBox.No)
if res != QMessageBox.Yes:
return
self.emit(SIGNAL("aboutToChangeTable()"))
try:
self.db.table_delete_constraint(self.table, con_name, self.schema)
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
return
# refresh constraints
self.populateConstraints()
def currentConstraint(self):
""" returns row index of selected index """
sel = self.viewConstraints.selectionModel()
indexes = sel.selectedRows()
if len(indexes) == 0:
QMessageBox.information(self, "sorry", "nothing selected")
return -1
return indexes[0].row()
def populateIndexes(self):
m = self.viewIndexes.model()
m.clear()
self.indexes = self.db.get_table_indexes(self.table, self.schema)
for idx in self.indexes:
item_name = QStandardItem(idx.name)
cols = ""
for col in idx.columns:
if len(cols) != 0: cols += ", "
cols += self._field_by_number(col).name
item_columns = QStandardItem(cols)
m.appendRow( [ item_name, item_columns ] )
for col in range(2):
self.viewIndexes.resizeColumnToContents(col)
def createIndex(self):
""" create an index """
self.emit(SIGNAL("aboutToChangeTable()"))
dlg = DlgCreateIndex(self, self.db, self.table, self.schema)
if not dlg.exec_():
return
# refresh indexes
self.populateIndexes()
def createSpatialIndex(self):
""" asks for every geometry column whether it should create an index for it """
# TODO: first check whether the index doesn't exist already
self.emit(SIGNAL("aboutToChangeTable()"))
try:
for fld in self.fields:
if fld.data_type == 'geometry':
res = QMessageBox.question(self, "create?", "create spatial index for field "+fld.name+"?", QMessageBox.Yes | QMessageBox.No)
if res == QMessageBox.Yes:
self.db.create_spatial_index(self.table, self.schema, fld.name)
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
return
# refresh indexes
self.populateIndexes()
def currentIndex(self):
""" returns row index of selected index """
sel = self.viewIndexes.selectionModel()
indexes = sel.selectedRows()
if len(indexes) == 0:
QMessageBox.information(self, "sorry", "nothing selected")
return -1
return indexes[0].row()
def deleteIndex(self):
""" delete currently selected index """
num = self.currentIndex()
if num == -1:
return
m = self.viewIndexes.model()
idx_name = m.item(num, 0).text()
res = QMessageBox.question(self, "are you sure", "really delete index '%s' ?" % idx_name, QMessageBox.Yes | QMessageBox.No)
if res != QMessageBox.Yes:
return
self.emit(SIGNAL("aboutToChangeTable()"))
try:
self.db.delete_index(idx_name, self.schema)
except postgis_utils.DbError, e:
DlgDbError.showError(e, self)
return
# refresh indexes
self.populateIndexes()