def createSpatialIndex(self): """ create spatial index for the geometry column """ if self.table.type != self.table.VectorType: QMessageBox.information( self, self.tr("DB Manager"), self.tr("The selected table has no geometry")) return res = QMessageBox.question( self, self.tr("Create?"), self.tr("Create spatial index for field %s?") % self.table.geomColumn, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: return # TODO: first check whether the index doesn't exist already QApplication.setOverrideCursor(Qt.WaitCursor) self.aboutToChangeTable.emit() try: self.table.createSpatialIndex() self.populateViews() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def deleteIndex(self): """ delete currently selected index """ index = self.currentIndex() if index == -1: return m = self.viewIndexes.model() idx = m.getObject(index) res = QMessageBox.question( self, self.tr("Are you sure"), self.tr("really delete index '%s'?") % idx.name, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: return QApplication.setOverrideCursor(Qt.WaitCursor) self.aboutToChangeTable.emit() try: idx.delete() self.populateViews() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def deleteConstraint(self): """ delete a constraint """ index = self.currentConstraint() if index == -1: return m = self.viewConstraints.model() constr = m.getObject(index) res = QMessageBox.question( self, self.tr("Are you sure"), self.tr("really delete constraint '%s'?") % constr.name, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: return QApplication.setOverrideCursor(Qt.WaitCursor) self.aboutToChangeTable.emit() try: constr.delete() self.populateViews() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def spatialInfo(self): ret = [] if self.table.geomType is None: return ret tbl = [ (QApplication.translate("DBManagerPlugin", "Column:"), self.table.geomColumn), (QApplication.translate("DBManagerPlugin", "Geometry:"), self.table.geomType) ] # only if we have info from geometry_columns srid = self.table.srid if self.table.srid is not None else -1 sr_info = self.table.database().connector.getSpatialRefInfo(srid) if srid != -1 else QApplication.translate( "DBManagerPlugin", "Undefined") if sr_info: tbl.append((QApplication.translate("DBManagerPlugin", "Spatial ref:"), u"%s (%d)" % (sr_info, srid))) # extent if self.table.extent is not None and self.table.extent[0] is not None: extent_str = '%.5f, %.5f - %.5f, %.5f' % self.table.extent else: extent_str = QApplication.translate("DBManagerPlugin", '(unknown) (<a href="action:extent/get">find out</a>)') tbl.append((QApplication.translate("DBManagerPlugin", "Extent:"), extent_str)) ret.append(HtmlTable(tbl)) return ret
def spatialInfo(self): ret = [] info = self.db.connector.getSpatialInfo() if not info: return tbl = [ (QApplication.translate("DBManagerPlugin", "Oracle\ Spatial:"), info[0]) ] ret.append(HtmlTable(tbl)) if not self.db.connector.has_geometry_columns: ret.append( HtmlParagraph( QApplication.translate( "DBManagerPlugin", (u"<warning> ALL_SDO_GEOM_METADATA" u" view doesn't exist!\n" u"This view is essential for many" u"GIS applications for enumeration of tables.")))) return ret
def spatialInfo(self): ret = [] info = self.db.connector.getSpatialInfo() if info is None: return tbl = [(QApplication.translate("DBManagerPlugin", "Library:"), info[0]), ("GEOS:", info[1]), ("Proj:", info[2])] ret.append(HtmlTable(tbl)) if self.db.connector.is_gpkg: pass elif not self.db.connector.has_geometry_columns: ret.append( HtmlParagraph( QApplication.translate( "DBManagerPlugin", "<warning> geometry_columns table doesn't exist!\n" "This table is essential for many GIS applications for enumeration of tables." ))) return ret
def getSpatialInfo(self): ret = [] info = self.db.connector.getSpatialInfo() if info is None: return tbl = [ (QApplication.translate("DBManagerPlugin", "Library:"), info[0]), (QApplication.translate("DBManagerPlugin", "Scripts:"), info[3]), ("GEOS:", info[1]), ("Proj:", info[2]) ] ret.append(HtmlTable(tbl)) if info[1] is not None and info[1] != info[2]: ret.append(HtmlParagraph(QApplication.translate("DBManagerPlugin", "<warning> Version of installed scripts doesn't match version of released scripts!\n" "This is probably a result of incorrect PostGIS upgrade."))) if not self.db.connector.has_geometry_columns: ret.append(HtmlParagraph( QApplication.translate("DBManagerPlugin", "<warning> geometry_columns table doesn't exist!\n" "This table is essential for many GIS applications for enumeration of tables."))) elif not self.db.connector.has_geometry_columns_access: ret.append(HtmlParagraph(QApplication.translate("DBManagerPlugin", "<warning> This user doesn't have privileges to read contents of geometry_columns table!\n" "This table is essential for many GIS applications for enumeration of tables."))) return ret
def toHtml(self): ret = [] general_info = self.generalInfo() if general_info is None: pass else: ret.append( HtmlSection( QApplication.translate("DBManagerPlugin", 'Schema details'), general_info)) priv_details = self.privilegesDetails() if priv_details is None: pass else: priv_details = HtmlContent(priv_details) if not priv_details.hasContents(): priv_details = QApplication.translate( "DBManagerPlugin", '<warning> This user has no privileges to access this schema!' ) else: priv_details = [ QApplication.translate("DBManagerPlugin", "User has privileges:"), priv_details ] ret.append( HtmlSection( QApplication.translate("DBManagerPlugin", 'Privileges'), priv_details)) return HtmlContent(ret).toHtml()
def openScript(self): if self.hasChanged: ret = QMessageBox.warning(self, self.tr('Unsaved changes'), self.tr('There are unsaved changes in script. Continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = QFileDialog.getOpenFileName( self, self.tr('Save script'), scriptDir, filterName) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) with codecs.open(self.filename, 'r', encoding='utf-8') as f: txt = f.read() self.editor.setText(txt) self.hasChanged = False self.editor.setModified(False) self.editor.recolor() QApplication.restoreOverrideCursor()
def runAction(self, action): action = unicode(action) if action.startswith("vacuumanalyze/"): if action == "vacuumanalyze/run": self.runVacuumAnalyze() return True elif action.startswith("rule/"): parts = action.split('/') rule_name = parts[1] rule_action = parts[2] msg = u"Do you want to %s rule %s?" % (rule_action, rule_name) QApplication.restoreOverrideCursor() try: if QMessageBox.question(None, self.tr("Table rule"), msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return False finally: QApplication.setOverrideCursor(Qt.WaitCursor) if rule_action == "delete": self.aboutToChange.emit() self.database().connector.deleteTableRule(rule_name, (self.schemaName(), self.name)) self.refreshRules() return True return Table.runAction(self, action)
def constraintsDetails(self): if not self.table.constraints(): return None tbl = [] # define the table header header = (QApplication.translate("DBManagerPlugin", "Name"), QApplication.translate("DBManagerPlugin", "Type"), QApplication.translate("DBManagerPlugin", "Column"), QApplication.translate("DBManagerPlugin", "Status"), QApplication.translate("DBManagerPlugin", "Validated"), QApplication.translate("DBManagerPlugin", "Generated"), QApplication.translate("DBManagerPlugin", "Check condition"), QApplication.translate("DBManagerPlugin", "Foreign Table"), QApplication.translate("DBManagerPlugin", "Foreign column"), QApplication.translate("DBManagerPlugin", "On Delete")) tbl.append(HtmlTableHeader(header)) # add table contents for con in self.table.constraints(): tbl.append((con.name, con.type2String(), con.column, con.status, con.validated, con.generated, con.checkSource, con.foreignTable, con.foreignKey, con.foreignOnDelete)) return HtmlTable(tbl, {"class": "header"})
def openScript(self): if self.hasChanged: ret = QMessageBox.warning( self, self.tr('Unsaved changes'), self.tr('There are unsaved changes in script. Continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = QFileDialog.getOpenFileName(self, self.tr('Save script'), scriptDir, filterName) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) with codecs.open(self.filename, 'r', encoding='utf-8') as f: txt = f.read() self.editor.setText(txt) self.hasChanged = False self.editor.setModified(False) self.editor.recolor() QApplication.restoreOverrideCursor()
def editColumn(self): """ open dialog to change column info and alter table appropriately """ index = self.currentColumn() if index == -1: return m = self.viewFields.model() # get column in table # (there can be missing number if someone deleted a column) fld = m.getObject(index) dlg = DlgFieldProperties(self, fld, self.table) if not dlg.exec_(): return new_fld = dlg.getField(True) QApplication.setOverrideCursor(Qt.WaitCursor) self.aboutToChangeTable.emit() try: fld.update(new_fld.name, new_fld.type2String(), new_fld.notNull, new_fld.default2String()) self.populateViews() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def deleteConstraint(self): """ delete a constraint """ index = self.currentConstraint() if index == -1: return m = self.viewConstraints.model() constr = m.getObject(index) res = QMessageBox.question(self, self.tr("Are you sure"), self.tr("really delete constraint '%s'?") % constr.name, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: return QApplication.setOverrideCursor(Qt.WaitCursor) self.aboutToChangeTable.emit() try: constr.delete() self.populateViews() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def fetchAvailablePlugins(self, reloadMode): """ Fetch plugins from all enabled repositories.""" """ reloadMode = true: Fully refresh data from QSettings to mRepositories """ """ reloadMode = false: Fetch unready repositories only """ QApplication.setOverrideCursor(Qt.WaitCursor) if reloadMode: repositories.load() plugins.clearRepoCache() plugins.getAllInstalled() for key in repositories.allEnabled(): if reloadMode or repositories.all()[key]["state"] == 3: # if state = 3 (error or not fetched yet), try to fetch once again repositories.requestFetching(key) if repositories.fetchingInProgress(): fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow()) fetchDlg.exec_() del fetchDlg for key in repositories.all(): repositories.killConnection(key) QApplication.restoreOverrideCursor() # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier) if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled(): for key in repositories.allUnavailable(): if not keepQuiet: QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"]) if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier): keepQuiet = True # finally, rebuild plugins from the caches plugins.rebuild()
def treeLoaded(self, reply): """ update the tree of scripts/models whenever HTTP request is finished """ QApplication.restoreOverrideCursor() if reply.error() != QNetworkReply.NoError: self.popupError(reply.error(), reply.request().url().toString()) else: resources = unicode(reply.readAll()).splitlines() resources = [r.split(',') for r in resources] self.resources = {f: (v, n) for f, v, n in resources} for filename, version, name in sorted( resources, key=lambda kv: kv[2].lower()): treeBranch = self.getTreeBranchForState( filename, float(version)) item = TreeItem(filename, name, self.icon) treeBranch.addChild(item) if treeBranch != self.notinstalledItem: item.setCheckState(0, Qt.Checked) reply.deleteLater() self.tree.addTopLevelItem(self.toupdateItem) self.tree.addTopLevelItem(self.notinstalledItem) self.tree.addTopLevelItem(self.uptodateItem) self.webView.setHtml(self.HELP_TEXT)
def createGeomColumn(self): """ first check whether everything's fine """ if self.editName.text() == "": QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty")) return name = self.editName.text() geom_type = self.GEOM_TYPES[self.cboType.currentIndex()] dim = self.spinDim.value() try: srid = int(self.editSrid.text()) except ValueError: srid = -1 createSpatialIndex = False # now create the geometry column QApplication.setOverrideCursor(Qt.WaitCursor) try: self.table.addGeometryColumn(name, geom_type, srid, dim, createSpatialIndex) except DbError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() self.accept()
def setData(self, index, value, role): if role != Qt.EditRole or index.column() != 0: return False item = index.internalPointer() new_value = unicode(value) if isinstance(item, SchemaItem) or isinstance(item, TableItem): obj = item.getItemData() # rename schema or table or view if new_value == obj.name: return False QApplication.setOverrideCursor(Qt.WaitCursor) try: obj.rename(new_value) self._onDataChanged(index) except BaseError as e: DlgDbError.showError(e, self.treeView) return False finally: QApplication.restoreOverrideCursor() return True return False
def treeLoaded(self, reply): """ update the tree of scripts/models whenever HTTP request is finished """ QApplication.restoreOverrideCursor() if reply.error() != QNetworkReply.NoError: self.popupError(reply.error(), reply.request().url().toString()) else: resources = unicode(reply.readAll()).splitlines() resources = [r.split(',') for r in resources] self.resources = {f: (v, n) for f, v, n in resources} for filename, version, name in sorted(resources, key=lambda kv: kv[2].lower()): treeBranch = self.getTreeBranchForState(filename, float(version)) item = TreeItem(filename, name, self.icon) treeBranch.addChild(item) if treeBranch != self.notinstalledItem: item.setCheckState(0, Qt.Checked) reply.deleteLater() self.tree.addTopLevelItem(self.toupdateItem) self.tree.addTopLevelItem(self.notinstalledItem) self.tree.addTopLevelItem(self.uptodateItem) self.webView.setHtml(self.HELP_TEXT)
def resetGUI(self): QApplication.restoreOverrideCursor() self.lblProgress.setText('') self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.btnRun.setEnabled(True) self.btnClose.setEnabled(True)
def __unicode__(self): if self.query is None: return BaseError.__unicode__(self) msg = QApplication.translate("DBManagerPlugin", "Error:\n%s") % BaseError.__unicode__(self) if self.query: msg += QApplication.translate("DBManagerPlugin", "\n\nQuery:\n%s") % self.query return msg
def privilegesDetails(self): details = self.db.connector.getDatabasePrivileges() lst = [] if details[0]: lst.append(QApplication.translate("DBManagerPlugin", "create new schemas")) if details[1]: lst.append(QApplication.translate("DBManagerPlugin", "create temporary tables")) return HtmlList(lst)
def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.hasSelectedText(): text = self.selectedText() text = text.replace('>>> ', '').replace('... ', '').strip() # removing prompts QApplication.clipboard().setText(text) else: raise KeyboardInterrupt
def privilegesDetails(self): details = self.schema.database().connector.getSchemaPrivileges(self.schema.name) lst = [] if details[0]: lst.append(QApplication.translate("DBManagerPlugin", "create new objects")) if details[1]: lst.append(QApplication.translate("DBManagerPlugin", "access objects")) return HtmlList(lst)
def tabChanged(self, index): QApplication.setOverrideCursor(Qt.WaitCursor) try: self.refreshTabs() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor()
def generalInfo(self): tbl = [ # ("Tables:", self.schema.tableCount) ] if self.schema.owner: tbl.append((QApplication.translate("DBManagerPlugin", "Owner:"), self.schema.owner)) if self.schema.comment: tbl.append((QApplication.translate("DBManagerPlugin", "Comment:"), self.schema.comment)) return HtmlTable(tbl)
def createTable(self): """ create table with chosen fields, optionally add a geometry column """ if not self.hasSchemas: schema = None else: schema = unicode(self.cboSchema.currentText()) if len(schema) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("select schema!")) return table = unicode(self.editName.text()) if len(table) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("enter table name!")) return m = self.fields.model() if m.rowCount() == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("add some fields!")) return useGeomColumn = self.chkGeomColumn.isChecked() if useGeomColumn: geomColumn = unicode(self.editGeomColumn.text()) if len(geomColumn) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("set geometry column name")) return geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()] geomDim = self.spinGeomDim.value() try: geomSrid = int(self.editGeomSrid.text()) except ValueError: geomSrid = 0 useSpatialIndex = self.chkSpatialIndex.isChecked() flds = m.getFields() pk_index = self.cboPrimaryKey.currentIndex() if pk_index >= 0: flds[pk_index].primaryKey = True # commit to DB QApplication.setOverrideCursor(Qt.WaitCursor) try: if not useGeomColumn: self.db.createTable(table, flds, schema) else: geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex self.db.createVectorTable(table, flds, geom, schema) except (ConnectionError, DbError) as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() QMessageBox.information(self, self.tr("Good"), self.tr("everything went fine"))
def updateAlgsList(): """Call this method when there has been any change that requires the list of algorithms to be created again from algorithm providers. """ QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) Processing.loadFromProviders() Processing.fireAlgsListHasChanged() QApplication.restoreOverrideCursor()
def deleteActionSlot(self, item, action, parent): if isinstance(item, Schema): self.deleteSchemaActionSlot(item, action, parent) elif isinstance(item, Table): self.deleteTableActionSlot(item, action, parent) else: QApplication.restoreOverrideCursor() parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Cannot delete the selected item."), QgsMessageBar.INFO, parent.iface.messageTimeout()) QApplication.setOverrideCursor(Qt.WaitCursor)
def run(item, action, mainwindow): from .dlg_versioning import DlgVersioning dlg = DlgVersioning(item, mainwindow) QApplication.restoreOverrideCursor() try: dlg.exec_() finally: QApplication.setOverrideCursor(Qt.WaitCursor)
def restoreGui(self): self.progressBar.setRange(0, 100) self.progressBar.setValue(0) QApplication.restoreOverrideCursor() self.buttonBox.rejected.disconnect(self.stopProcessing) self.buttonBox.rejected.connect(self.reject) self.okButton.setEnabled(True)
def finish(self): for count, alg in enumerate(self.algs): self.loadHTMLResults(alg, count) self.createSummaryTable() QApplication.restoreOverrideCursor() self.mainWidget.setEnabled(True) QMessageBox.information(self, self.tr('Batch processing'), self.tr('Batch processing completed'))
def runVacuumAnalyzeActionSlot(self, item, action, parent): QApplication.restoreOverrideCursor() try: if not isinstance(item, Table) or item.isView: parent.infoBar.pushMessage(self.tr("Select a table for vacuum analyze."), QgsMessageBar.INFO, parent.iface.messageTimeout()) return finally: QApplication.setOverrideCursor(Qt.WaitCursor) item.runVacuumAnalyze()
def moveTableToSchemaActionSlot(self, item, action, parent, new_schema): QApplication.restoreOverrideCursor() try: if not isinstance(item, Table): parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Select a table/view."), QgsMessageBar.INFO, parent.iface.messageTimeout()) return finally: QApplication.setOverrideCursor(Qt.WaitCursor) item.moveToSchema(new_schema)
def loadSqlLayer(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: layer = self._getSqlLayer(self.filter) if layer is None: return from qgis.core import QgsMapLayerRegistry QgsMapLayerRegistry.instance().addMapLayers([layer], True) finally: QApplication.restoreOverrideCursor()
def createTableActionSlot(self, item, action, parent): QApplication.restoreOverrideCursor() if not hasattr(item, 'database') or item.database() is None: parent.infoBar.pushMessage( QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it."), QgsMessageBar.INFO, parent.iface.messageTimeout()) return from ..dlg_create_table import DlgCreateTable DlgCreateTable(item, parent).exec_() QApplication.setOverrideCursor(Qt.WaitCursor)
def type2String(self): if self.type == ORTableConstraint.TypeCheck: return QApplication.translate("DBManagerPlugin", "Check") if self.type == ORTableConstraint.TypePrimaryKey: return QApplication.translate("DBManagerPlugin", "Primary key") if self.type == ORTableConstraint.TypeForeignKey: return QApplication.translate("DBManagerPlugin", "Foreign key") if self.type == ORTableConstraint.TypeUnique: return QApplication.translate("DBManagerPlugin", "Unique") return QApplication.translate("DBManagerPlugin", 'Unknown')
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 runVacuumActionSlot(self, item, action, parent): QApplication.restoreOverrideCursor() try: if not isinstance(item, (DBPlugin, Table)) or item.database() is None: parent.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."), QgsMessageBar.INFO, parent.iface.messageTimeout()) return finally: QApplication.setOverrideCursor(Qt.WaitCursor) self.runVacuum()
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()