This repository has been archived by the owner on Feb 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
db_manager.py
400 lines (308 loc) · 12.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QuantumGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
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. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from .info_viewer import InfoViewer
from .table_viewer import TableViewer
from .layer_preview import LayerPreview
from .db_tree import DBTree
from .db_plugins import getDbPluginErrors
from .db_plugins.plugin import BaseError
from .dlg_db_error import DlgDbError
class DBManager(QMainWindow):
def __init__(self, iface, parent=None):
QMainWindow.__init__(self, parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setupUi()
self.iface = iface
# restore the window state
settings = QSettings()
self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry").toByteArray() )
self.restoreState( settings.value("/DB_Manager/mainWindow/windowState").toByteArray() )
self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged)
self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged)
self.itemChanged(None)
self.displayDbPluginErrors()
def displayDbPluginErrors(self):
if len(getDbPluginErrors()) <= 0:
return
if not hasattr(self, '_dbPluginErrorIndex') or self._dbPluginErrorIndex >= len(getDbPluginErrors()):
self._dbPluginErrorIndex = 0
msg = getDbPluginErrors()[self._dbPluginErrorIndex]
self._dbPluginErrorIndex += 1
self.statusBar.showMessage( msg, 5000 )
QTimer.singleShot( 6000, self.displayDbPluginErrors)
def closeEvent(self, e):
self.unregisterAllActions()
# save the window state
settings = QSettings()
settings.setValue( "/DB_Manager/mainWindow/windowState", QVariant(self.saveState()) )
settings.setValue( "/DB_Manager/mainWindow/geometry", QVariant(self.saveGeometry()) )
QMainWindow.closeEvent(self, e)
def refreshItem(self, item=None):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
if item == None:
item = self.tree.currentItem()
self.tree.refreshItem(item) # refresh item children in the db tree
except BaseError, e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def itemChanged(self, item):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.reloadButtons()
self.refreshTabs()
except BaseError, 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 != None:
self.unregisterAllActions()
# add actions of the selected database
self._lastDb = db
if self._lastDb != None:
self._lastDb.registerAllActions(self)
def tabChanged(self, index):
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.refreshTabs()
except BaseError, e:
DlgDbError.showError(e, self)
return
finally:
QApplication.restoreOverrideCursor()
def refreshTabs(self):
index = self.tabs.currentIndex()
item = self.tree.currentItem()
table = self.tree.currentTable()
# enable/disable tabs
self.tabs.setTabEnabled( self.tabs.indexOf(self.table), table != None )
self.tabs.setTabEnabled( self.tabs.indexOf(self.preview), table != None and table.type in [table.VectorType, table.RasterType] and table.geomColumn != 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 runSqlWindow(self):
db = self.tree.currentDatabase()
if db == None:
QMessageBox.information(self, "Sorry", "No database selected or you are not connected to it.")
return
from dlg_sql_window import DlgSqlWindow
dlg = DlgSqlWindow(self.iface, db, self)
#refreshDb = lambda x: self.refreshItem( db.connection() ) # refresh the database tree
#self.connect( dlg, SIGNAL( "queryExecuted(const QString &)" ), refreshDb )
dlg.show()
dlg.exec_()
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 != None:
invoke_callback = lambda x: self.invokeCallback( callback )
if menuName == None or menuName == "":
self.addAction( action )
if not self._registeredDbActions.has_key(menuName):
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback != None:
QObject.connect( action, SIGNAL("triggered(bool)"), 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 == None:
menu = QMenu(menuName, self)
if helpMenuAction != 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 not self._registeredDbActions.has_key(menuName):
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback != None:
QObject.connect( action, SIGNAL("triggered(bool)"), invoke_callback )
return True
def invokeCallback(self, callback, params=None):
""" 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:
if params is None:
callback( self.tree.currentItem(), self.sender(), self )
else:
callback( self.tree.currentItem(), self.sender(), self, *params )
except BaseError, 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 == None or menuName == "":
self.removeAction( action )
if self._registeredDbActions.has_key(menuName):
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 self._registeredDbActions.has_key(menuName):
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 about(self):
from .dlg_about import DlgAbout
DlgAbout(self).exec_()
def setupUi(self):
self.setWindowTitle("DB Manager")
self.setWindowIcon(QIcon(":/db_manager/icon"))
self.resize(QSize(700,500).expandedTo(self.minimumSizeHint()))
# create central tab widget
self.tabs = QTabWidget()
self.info = InfoViewer(self)
self.tabs.addTab(self.info, "Info")
self.table = TableViewer(self)
self.tabs.addTab(self.table, "Table")
self.preview = LayerPreview(self)
self.tabs.addTab(self.preview, "Preview")
self.setCentralWidget(self.tabs)
# 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("&Database", self)
actionMenuDb = self.menuBar.addMenu(self.menuDb)
self.menuSchema = QMenu("&Schema", self)
actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
self.menuTable = QMenu("&Table", self)
actionMenuTable = self.menuBar.addMenu(self.menuTable)
self.menuHelp = QMenu("&Help", self)
actionMenuHelp = self.menuBar.addMenu(self.menuHelp)
self.setMenuBar(self.menuBar)
# create toolbar
self.toolBar = QToolBar("Default", self)
self.toolBar.setObjectName("DB_Manager_ToolBar")
self.toolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
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"), "&Refresh", self.refreshActionSlot, QKeySequence("F5") )
self.actionSqlWindow = self.menuDb.addAction( QIcon(":/db_manager/actions/sql_window"), "&SQL window", self.runSqlWindow, QKeySequence("F2") )
self.menuDb.addSeparator()
self.actionClose = self.menuDb.addAction( QIcon(), "&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)
actionMenuTable.setVisible(False)
self.actionShowSystemTables = self.menuTable.addAction("Show system tables/views", self.showSystemTables)
self.actionShowSystemTables.setCheckable(True)
self.actionShowSystemTables.setChecked(True)
self.actionShowSystemTables.setVisible(False)
# menu HELP
self.actionAbout = self.menuHelp.addAction(QIcon(":/db_manager/about"), "&About", self.about)
# add actions to the toolbar
self.toolBar.addAction( self.actionRefresh )
self.toolBar.addAction( self.actionSqlWindow )