-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_manager.py
560 lines (452 loc) · 21.3 KB
/
db_manager.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : [email protected]
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
/***************************************************************************
* *
* 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 functools
from qgis.PyQt.QtCore import Qt, QSettings, QByteArray, QSize
from qgis.PyQt.QtWidgets import QMainWindow, QApplication, QMenu, QTabWidget, QGridLayout, QSpacerItem, QSizePolicy, QDockWidget, QStatusBar, QMenuBar, QToolBar, QTabBar, QMessageBox
from qgis.PyQt.QtGui import QIcon, QKeySequence, QAction
from qgis.gui import QgsMessageBar
from .info_viewer import InfoViewer
from .table_viewer import TableViewer
from .layer_preview import LayerPreview
from .db_tree import DBTree
from .db_plugins.plugin import BaseError
from .dlg_db_error import DlgDbError
# CHX
from inspect import getmembers
from pprint import pprint
class DBManager(QMainWindow):
def __init__(self, iface, parent=None):
QMainWindow.__init__(self, parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.iface = iface
self.setupUi()
# CHX
# QMessageBox.information(None, "OK", "CHX".decode('utf-8'))
print("DBManager CHX ---")
# restore the window state
settings = QSettings()
self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray))
self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray))
self.tabs.currentChanged.connect(self.tabChanged)
self.tree.selectedItemChanged.connect(self.itemChanged)
self.itemChanged(None)
def closeEvent(self, e):
self.unregisterAllActions()
# clear preview, this will delete the layer in preview tab
self.preview.loadPreview(None)
# save the window state
settings = QSettings()
settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState())
settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry())
QMainWindow.closeEvent(self, e)
def refreshItem(self, item=None):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
if item is None:
item = self.tree.currentItem()
self.tree.refreshItem(item) # refresh item children in the db tree
except BaseError as e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def itemChanged(self, item):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.reloadButtons()
# clear preview, this will delete the layer in preview tab
self.preview.loadPreview(None)
self.refreshTabs()
except BaseError as e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def reloadButtons(self):
db = self.tree.currentDatabase()
if not hasattr(self, '_lastDb'):
self._lastDb = db
elif db == self._lastDb:
return
# remove old actions
if self._lastDb is not None:
self.unregisterAllActions()
# add actions of the selected database
self._lastDb = db
if self._lastDb is not None:
self._lastDb.registerAllActions(self)
def tabChanged(self, index):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.refreshTabs()
except BaseError as e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def refreshTabs(self):
index = self.tabs.currentIndex()
item = self.tree.currentItem()
table = self.tree.currentTable()
# CHX ?
# self.infoBar.pushMessage(self.tr("Version CHX"), # CHX
# QgsMessageBar.INFO, self.iface.messageTimeout())
# enable/disable tabs
self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None)
self.tabs.setTabEnabled(self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType,
table.RasterType] and table.geomColumn is not None)
# show the info tab if the current tab is disabled
if not self.tabs.isTabEnabled(index):
self.tabs.setCurrentWidget(self.info)
current_tab = self.tabs.currentWidget()
if current_tab == self.info:
self.info.showInfo(item)
elif current_tab == self.table:
self.table.loadData(item)
elif current_tab == self.preview:
self.preview.loadPreview(item)
def refreshActionSlot(self):
self.info.setDirty()
self.table.setDirty()
self.preview.setDirty()
self.refreshItem()
def importActionSlot(self):
db = self.tree.currentDatabase()
if db is None:
self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it. CHX2"), # CHX
QgsMessageBar.INFO, self.iface.messageTimeout())
return
outUri = db.uri()
schema = self.tree.currentSchema()
if schema:
outUri.setDataSource(schema.name, "", "", "")
from .dlg_import_vector import DlgImportVector
dlg = DlgImportVector(None, db, outUri, self)
dlg.exec_()
def minimizeActionSlot(self):
db = self.tree.currentDatabase()
if db is not None:
print(db.connName())
item = self.tree.currentItem()
# pprint(getmembers(item)) # CHX
pprint(item.self.selectedIndexes())
print("LLL")
self.tree.collapseAll()
schema = self.tree.currentSchema()
if schema is None:
self.infoBar.pushMessage(self.tr("CHX:Select the schema you want minimize.."), QgsMessageBar.INFO,
self.iface.messageTimeout())
return
def exportActionSlot(self):
table = self.tree.currentTable()
if table is None:
self.infoBar.pushMessage(self.tr("Select the table you want export to file."), QgsMessageBar.INFO,
self.iface.messageTimeout())
return
inLayer = table.toMapLayer()
from .dlg_export_vector import DlgExportVector
dlg = DlgExportVector(inLayer, table.database(), self)
dlg.exec_()
inLayer.deleteLater()
def runSqlWindow(self):
db = self.tree.currentDatabase()
if db is None:
self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
QgsMessageBar.INFO, self.iface.messageTimeout())
# force displaying of the message, it appears on the first tab (i.e. Info)
self.tabs.setCurrentIndex(0)
return
from .dlg_sql_window import DlgSqlWindow
query = DlgSqlWindow(self.iface, db, self)
dbname = db.connection().connectionName()
tabname = self.tr("Query") + u" (%s)" % dbname
index = self.tabs.addTab(query, tabname)
self.tabs.setTabIcon(index, db.connection().icon())
self.tabs.setCurrentIndex(index)
query.nameChanged.connect(functools.partial(self.update_query_tab_name, index, dbname))
def runSqlLayerWindow(self, layer):
from dlg_sql_layer_window import DlgSqlLayerWindow
query = DlgSqlLayerWindow(self.iface, layer, self)
lname = layer.name()
tabname = self.tr("Layer") + u" (%s)" % lname
index = self.tabs.addTab(query, tabname)
#self.tabs.setTabIcon(index, db.connection().icon())
self.tabs.setCurrentIndex(index)
def update_query_tab_name(self, index, dbname, queryname):
if not queryname:
queryname = self.tr("Query")
tabname = u"%s (%s)" % (queryname, dbname)
self.tabs.setTabText(index, tabname)
def showSystemTables(self):
self.tree.showSystemTables(self.actionShowSystemTables.isChecked())
def registerAction(self, action, menuName, callback=None):
""" register an action to the manager's main menu """
if not hasattr(self, '_registeredDbActions'):
self._registeredDbActions = {}
if callback is not None:
def invoke_callback(x):
return self.invokeCallback(callback)
if menuName is None or menuName == "":
self.addAction(action)
if menuName not in self._registeredDbActions:
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback is not None:
action.triggered.connect(invoke_callback)
return True
# search for the menu
actionMenu = None
helpMenuAction = None
for a in self.menuBar.actions():
if not a.menu() or a.menu().title() != menuName:
continue
if a.menu() != self.menuHelp:
helpMenuAction = a
actionMenu = a
break
# not found, add a new menu before the help menu
if actionMenu is None:
menu = QMenu(menuName, self)
if helpMenuAction is not None:
actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
else:
actionMenu = self.menuBar.addMenu(menu)
menu = actionMenu.menu()
menuActions = menu.actions()
# get the placeholder's position to insert before it
pos = 0
for pos in range(len(menuActions)):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
menuActions[pos].setVisible(True)
break
if pos < len(menuActions):
before = menuActions[pos]
menu.insertAction(before, action)
else:
menu.addAction(action)
actionMenu.setVisible(True) # show the menu
if menuName not in self._registeredDbActions:
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback is not None:
action.triggered.connect(invoke_callback)
return True
def invokeCallback(self, callback, *params):
""" Call a method passing the selected item in the database tree,
the sender (usually a QAction), the plugin mainWindow and
optionally additional parameters.
This method takes care to override and restore the cursor,
but also catches exceptions and displays the error dialog.
"""
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
callback(self.tree.currentItem(), self.sender(), self, *params)
except BaseError as e:
# catch database errors and display the error dialog
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def unregisterAction(self, action, menuName):
if not hasattr(self, '_registeredDbActions'):
return
if menuName is None or menuName == "":
self.removeAction(action)
if menuName in self._registeredDbActions:
if self._registeredDbActions[menuName].count(action) > 0:
self._registeredDbActions[menuName].remove(action)
action.deleteLater()
return True
for a in self.menuBar.actions():
if not a.menu() or a.menu().title() != menuName:
continue
menu = a.menu()
menuActions = menu.actions()
menu.removeAction(action)
if menu.isEmpty(): # hide the menu
a.setVisible(False)
if menuName in self._registeredDbActions:
if self._registeredDbActions[menuName].count(action) > 0:
self._registeredDbActions[menuName].remove(action)
# hide the placeholder if there're no other registered actions
if len(self._registeredDbActions[menuName]) <= 0:
for i in range(len(menuActions)):
if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
menuActions[i].setVisible(False)
break
action.deleteLater()
return True
return False
def unregisterAllActions(self):
if not hasattr(self, '_registeredDbActions'):
return
for menuName in self._registeredDbActions:
for action in list(self._registeredDbActions[menuName]):
self.unregisterAction(action, menuName)
del self._registeredDbActions
def close_tab(self, index):
widget = self.tabs.widget(index)
if widget not in [self.info, self.table, self.preview]:
self.tabs.removeTab(index)
widget.deleteLater()
def setupUi(self):
self.setWindowTitle(self.tr("DB Manager - New CHX"))
self.setWindowIcon(QIcon(":/db_manager/actions/import"))
self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))
# create central tab widget and add the first 3 tabs: info, table and preview
self.tabs = QTabWidget()
self.info = InfoViewer(self)
self.tabs.addTab(self.info, self.tr("Info"))
self.table = TableViewer(self)
self.tabs.addTab(self.table, self.tr("Table"))
self.preview = LayerPreview(self)
self.tabs.addTab(self.preview, self.tr("Preview"))
self.setCentralWidget(self.tabs)
# display close button for all tabs but the first 3 ones, i.e.
# HACK: just hide the close button where not needed (GS)
self.tabs.setTabsClosable(True)
self.tabs.tabCloseRequested.connect(self.close_tab)
tabbar = self.tabs.tabBar()
for i in range(3):
btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
btn.resize(0, 0)
btn.hide()
# Creates layout for message bar
self.layout = QGridLayout(self.info)
self.layout.setContentsMargins(0, 0, 0, 0)
spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.layout.addItem(spacerItem, 1, 0, 1, 1)
# init messageBar instance
self.infoBar = QgsMessageBar(self.info)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
self.infoBar.setSizePolicy(sizePolicy)
self.layout.addWidget(self.infoBar, 0, 0, 1, 1)
# create database tree
self.dock = QDockWidget("Tree", self)
self.dock.setObjectName("DB_Manager_DBView")
self.dock.setFeatures(QDockWidget.DockWidgetMovable)
self.tree = DBTree(self)
self.dock.setWidget(self.tree)
self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)
# create status bar
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
# create menus
self.menuBar = QMenuBar(self)
self.menuDb = QMenu(self.tr("&Database CHX"), self)
self.menuBar.addMenu(self.menuDb)
self.menuSchema = QMenu(self.tr("&Schema"), self)
actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
self.menuTable = QMenu(self.tr("&Table"), self)
actionMenuTable = self.menuBar.addMenu(self.menuTable)
self.menuHelp = None # QMenu(self.tr("&Help"), self)
# actionMenuHelp = self.menuBar.addMenu(self.menuHelp)
self.setMenuBar(self.menuBar)
# create toolbar
self.toolBar = QToolBar("Default CHX", self)
self.toolBar.setObjectName("DB_Manager_ToolBar")
self.addToolBar(self.toolBar)
# create menus' actions
# menu DATABASE
sep = self.menuDb.addSeparator()
sep.setObjectName("DB_Manager_DbMenu_placeholder")
sep.setVisible(False)
self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
self.refreshActionSlot, QKeySequence("F5"))
self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
self.runSqlWindow, QKeySequence("F2"))
self.menuDb.addSeparator()
self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))
# menu SCHEMA
sep = self.menuSchema.addSeparator()
sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
sep.setVisible(False)
actionMenuSchema.setVisible(False)
# menu TABLE
sep = self.menuTable.addSeparator()
sep.setObjectName("DB_Manager_TableMenu_placeholder")
sep.setVisible(False)
self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
self.tr("&Import layer/file"), self.importActionSlot)
self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
self.exportActionSlot)
self.actionMinimize = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&CHX:Minimize"),
self.minimizeActionSlot)
self.menuTable.addSeparator()
#self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
#self.actionShowSystemTables.setCheckable(True)
#self.actionShowSystemTables.setChecked(True)
actionMenuTable.setVisible(False)
# add actions to the toolbar
self.toolBar.addAction(self.actionRefresh)
self.toolBar.addAction(self.actionSqlWindow)
self.toolBar.addAction(self.actionImport)
self.toolBar.addAction(self.actionExport)
self.toolBar.addAction(self.actionMinimize)
# CHX
self.actionRun = QAction(
QIcon(":/plugins/plugin_reloader/reload.png"),
u"DBManagerChxAction",
self.iface.mainWindow()
)
self.actionRun.setWhatsThis(u"DBManagerChxAction")
self.iface.addPluginToMenu("&DBManagerChxAction", self.actionRun)
self.iface.registerMainWindowAction(self.actionRun, self.theBestShortcutForDBManager())
# theBestShortcutForPluginReload
def theBestShortcutForDBManager(self):
''' Try to find the best saved setting.
Note **the action name is variable**, so the "Keyboard Shortcuts" window
tends to save concurrent shortcuts:
.../shortcuts/Reload plugin: plugin Foo=F5
.../shortcuts/Reload plugin: plugin Bar=Ctrl+F5
.../shortcuts/Reload plugin: plugin HelloWorld=Ctrl+Alt+Del
so we should find the recent one (not always possible) and remove the rest.
'''
DEFAULT = "Ctrl+B"
settings = QSettings()
settings.beginGroup('shortcuts')
# Find all saved shortcuts:
newKeyMe = 'DBManagerChx plugin'
keys = [key for key in settings.childKeys() if key.startswith(newKeyMe)]
if settings.contains(newKeyMe):
keys.append(newKeyMe)
if not len(keys):
# Nothing found in settings - fallback to default:
key = None
shortcut = DEFAULT
elif len(keys) == 1:
# Just one setting found, take that!
shortcut = settings.value(keys[0])
else:
# More then one old setting found. Take the best one and remove the rest.
if self.actionRun.text() in keys:
# The current action text found - let's hope it's the recent one...
key = self.actionRun.text()
shortcut = settings.value(key)
else:
# Otherwise take the first one
key = keys[0]
shortcut = settings.value(key)
# Remove redundant settings
for i in keys:
if i != key:
settings.remove(i)
return shortcut