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 batchFinished(self): self.base.stop() if len(self.errors) > 0: msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join(self.errors) QErrorMessage(self).showMessage(msg) inDir = self.getInputFileName() outDir = self.getOutputFileName() if outDir is None or inDir == outDir: self.outFiles = self.inFiles # load layers managing the render flag to avoid waste of time canvas = self.iface.mapCanvas() previousRenderFlag = canvas.renderFlag() canvas.setRenderFlag(False) notCreatedList = [] for item in self.outFiles: fileInfo = QFileInfo(item) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) else: notCreatedList.append(item) canvas.setRenderFlag(previousRenderFlag) if len(notCreatedList) == 0: QMessageBox.information(self, self.tr("Finished"), self.tr("Operation completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("The following files were not created: \n{0}").format(', '.join(notCreatedList)))
def currentColumn(self): """ returns row index of selected column """ sel = self.viewFields.selectionModel() indexes = sel.selectedRows() if len(indexes) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("nothing selected")) return -1 return indexes[0].row()
def deleteField(self): """ delete selected field """ row = self.selectedField() if row is None: QMessageBox.information(self, self.tr("DB Manager"), self.tr("no field selected")) else: self.fields.model().removeRows(row, 1) self.updatePkeyCombo()
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 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 navigate(self): """manage navigation / paging""" caller = self.sender().objectName() if caller == 'btnFirst': self.startfrom = 0 elif caller == 'btnLast': self.startfrom = self.catalog.results['matches'] - self.maxrecords elif caller == 'btnNext': self.startfrom += self.maxrecords if self.startfrom >= self.catalog.results["matches"]: msg = self.tr('End of results. Go to start?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = 0 else: return elif caller == "btnPrev": self.startfrom -= self.maxrecords if self.startfrom <= 0: msg = self.tr('Start of results. Go to end?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = (self.catalog.results['matches'] - self.maxrecords) else: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: self.catalog.getrecords2(constraints=self.constraints, maxrecords=self.maxrecords, startposition=self.startfrom, esn='full') except ExceptionReport as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Search error'), self.tr('Search error: %s') % err) return except Exception as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Connection error'), self.tr('Connection error: %s') % err) return QApplication.restoreOverrideCursor() self.display_results()
def finished(self): outFn = self.getOutputFileName() if self.needOverwrite: oldFile = QFile(outFn) newFile = QFile(self.tempFile) if oldFile.remove(): newFile.rename(outFn) fileInfo = QFileInfo(outFn) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("{0} not created.").format(outFn))
def accept(self): if not self.preloadAPI.isChecked() and \ not self.groupBoxPreparedAPI.isChecked(): if self.tableWidget.rowCount() == 0: QMessageBox.information(self, self.tr("Warning!"), self.tr('Please specify API file or check "Use preloaded API files"')) return if self.groupBoxPreparedAPI.isChecked() and \ not self.lineEdit.text(): QMessageBox.information(self, self.tr("Warning!"), self.tr('The APIs file was not compiled, click on "Compile APIs..."')) return self.saveSettings() self.listPath = [] QDialog.accept(self)
def exportAsPython(self): filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save Model As Python Script'), '', self.tr('Python files (*.py *.PY)'))) if not filename: return if not filename.lower().endswith('.py'): filename += '.py' text = self.alg.toPython() with codecs.open(filename, 'w', encoding='utf-8') as fout: fout.write(text) QMessageBox.information(self, self.tr('Model exported'), self.tr('Model was correctly exported.'))
def onOK(self): # execute and commit the code QApplication.setOverrideCursor(Qt.WaitCursor) try: sql = u"\n".join(self.updateSql()) self.db.connector._execute_and_commit(sql) except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() QMessageBox.information(self, "good!", "everything went fine!") self.accept()
def finished(self, load): outFn = self.getOutputFileName() if outFn is None: return if outFn == '': QMessageBox.warning(self, self.tr("Warning"), self.tr("No output file created.")) return fileInfo = QFileInfo(outFn) if fileInfo.exists(): if load: self.addLayerIntoCanvas(fileInfo) QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) else: #QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) ) QMessageBox.warning(self, self.tr("Warning"), self.tr("%s not created.") % outFn)
def exportAsPython(self): filename = unicode( QFileDialog.getSaveFileName(self, self.tr('Save Model As Python Script'), '', self.tr('Python files (*.py *.PY)'))) if not filename: return if not filename.lower().endswith('.py'): filename += '.py' text = self.alg.toPython() with codecs.open(filename, 'w', encoding='utf-8') as fout: fout.write(text) QMessageBox.information(self, self.tr('Model exported'), self.tr('Model was correctly exported.'))
def saveModel(self, saveAs): if unicode(self.textGroup.text()).strip() == '' \ or unicode(self.textName.text()).strip() == '': QMessageBox.warning( self, self.tr('Warning'), self.tr('Please enter group and model names before saving')) return self.alg.name = unicode(self.textName.text()) self.alg.group = unicode(self.textGroup.text()) if self.alg.descriptionFile is not None and not saveAs: filename = self.alg.descriptionFile else: filename = unicode( QFileDialog.getSaveFileName( self, self.tr('Save Model'), ModelerUtils.modelsFolder(), self.tr('Processing models (*.model)'))) if filename: if not filename.endswith('.model'): filename += '.model' self.alg.descriptionFile = filename if filename: text = self.alg.toJson() try: fout = codecs.open(filename, 'w', encoding='utf-8') except: if saveAs: QMessageBox.warning( self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1])) else: QMessageBox.warning( self, self.tr("Can't save model"), self.tr("This model can't be saved in its " "original location (probably you do not " "have permission to do it). Please, use " "the 'Save as...' option.")) return fout.write(text) fout.close() self.update = True QMessageBox.information(self, self.tr('Model saved'), self.tr('Model was correctly saved.')) self.hasChanged = False
def fieldDown(self): """ move selected field down """ row = self.selectedField() if row is None: QMessageBox.information(self, self.tr("DB Manager"), self.tr("No field selected")) return if row == self.fields.model().rowCount() - 1: QMessageBox.information(self, self.tr("DB Manager"), self.tr("field is at bottom already")) return # take row and reinsert it rowdata = self.fields.model().takeRow(row) self.fields.model().insertRow(row + 1, rowdata) # set selection again index = self.fields.model().index(row + 1, 0, QModelIndex()) self.fields.selectionModel().select(index, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect) self.updatePkeyCombo()
def save(self, connections): """save connections ops""" doc = etree.Element('qgsCSWConnections') doc.attrib['version'] = '1.0' for conn in connections: url = self.settings.value('/MetaSearch/%s/url' % conn) if url is not None: connection = etree.SubElement(doc, 'csw') connection.attrib['name'] = conn connection.attrib['url'] = url # write to disk with open(self.filename, 'w') as fileobj: fileobj.write(prettify_xml(etree.tostring(doc))) QMessageBox.information(self, self.tr('Save Connections'), self.tr('Saved to %s') % self.filename) self.reject()
def saveModel(self, saveAs): if unicode(self.textGroup.text()).strip() == '' \ or unicode(self.textName.text()).strip() == '': QMessageBox.warning( self, self.tr('Warning'), self.tr('Please enter group and model names before saving') ) return self.alg.name = unicode(self.textName.text()) self.alg.group = unicode(self.textGroup.text()) if self.alg.descriptionFile is not None and not saveAs: filename = self.alg.descriptionFile else: filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolder(), self.tr('Processing models (*.model)'))) if filename: if not filename.endswith('.model'): filename += '.model' self.alg.descriptionFile = filename if filename: text = self.alg.toJson() try: fout = codecs.open(filename, 'w', encoding='utf-8') except: if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1])) else: QMessageBox.warning(self, self.tr("Can't save model"), self.tr("This model can't be saved in its " "original location (probably you do not " "have permission to do it). Please, use " "the 'Save as...' option.")) return fout.write(text) fout.close() self.update = True QMessageBox.information(self, self.tr('Model saved'), self.tr('Model was correctly saved.')) self.hasChanged = False
def get_connections_from_file(parent, filename): """load connections from connection file""" error = 0 try: doc = etree.parse(filename).getroot() if doc.tag != 'qgsCSWConnections': error = 1 msg = parent.tr('Invalid CSW connections XML.') except etree.ParseError as err: error = 1 msg = parent.tr('Cannot parse XML file: %s' % err) except IOError as err: error = 1 msg = parent.tr('Cannot open file: %s' % err) if error == 1: QMessageBox.information(parent, parent.tr('Loading Connections'), msg) return return doc
def _prepareAPI(self): if self.tableWidget.rowCount() != 0: pap_file = QFileDialog().getSaveFileName(self, "", '*.pap', "Prepared APIs file (*.pap)") else: QMessageBox.information(self, self.tr("Warning!"), self.tr('You need to add some APIs file in order to compile')) return if pap_file: api_lexer = 'QsciLexerPython' api_files = [] count = self.tableWidget.rowCount() for i in range(0, count): api_files.append(self.tableWidget.item(i, 1).text()) api_dlg = PrepareAPIDialog(api_lexer, api_files, pap_file, self) api_dlg.show() api_dlg.activateWindow() api_dlg.raise_() api_dlg.prepareAPI() self.lineEdit.setText(pap_file)
def fieldDown(self): """ move selected field down """ row = self.selectedField() if row is None: QMessageBox.information(self, self.tr("DB Manager"), self.tr("No field selected")) return if row == self.fields.model().rowCount() - 1: QMessageBox.information(self, self.tr("DB Manager"), self.tr("field is at bottom already")) return # take row and reinsert it rowdata = self.fields.model().takeRow(row) self.fields.model().insertRow(row + 1, rowdata) # set selection again index = self.fields.model().index(row + 1, 0, QModelIndex()) self.fields.selectionModel().select( index, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect) self.updatePkeyCombo()
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 fillOutputFileEdit(self): lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter() # rasterize supports output file creation for GDAL 1.8 gdalVersion = Utils.GdalConfig.versionNum() if gdalVersion >= 1800: fileDialogFunc = Utils.FileDialog.getSaveFileName filters = Utils.FileFilter.saveRastersFilter() else: fileDialogFunc = Utils.FileDialog.getOpenFileName filters = Utils.FileFilter.allRastersFilter() outputFile = fileDialogFunc(self, self.tr("Select the raster file to save the results to"), filters, lastUsedFilter) if not outputFile: return Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter) self.outSelector.setFilename(outputFile) # required either -ts or -tr to create the output file if gdalVersion >= 1800: if not QFileInfo(outputFile).exists(): QMessageBox.information(self, self.tr("Output size or resolution required"), self.tr("The output file doesn't exist. You must set up the output size or resolution to create it.")) self.radioSetSize.setChecked(True)
def delete_connection(self): """delete connection""" current_text = self.cmbConnectionsServices.currentText() key = '/MetaSearch/%s' % current_text msg = self.tr('Remove service %s?') % current_text result = QMessageBox.information(self, self.tr('Confirm delete'), msg, QMessageBox.Ok | QMessageBox.Cancel) if result == QMessageBox.Ok: # remove service from list self.settings.remove(key) index_to_delete = self.cmbConnectionsServices.currentIndex() self.cmbConnectionsServices.removeItem(index_to_delete) self.cmbConnectionsSearch.removeItem(index_to_delete) self.set_connection_list_position()
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.information(self, self.tr("Import to database"), self.tr("Input layer missing or not valid")) return if self.cboTable.currentText() == "": QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = self.editSourceSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = self.editTargetSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled() else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = qgis.core.QgsDataSourceURI(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled(): geom = srcUri.geometryColumn() if not self.chkGeomColumn.isChecked() else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) uri = self.outUri.uri(False) providerName = self.db.dbplugin().providerName() options = {} if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(): options['forceSinglePartGeometryType'] = True outCrs = None if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid) # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): sourceSrid = int(self.editSourceSrid.text()) inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer(self.inLayer, uri, providerName, outCrs, onlySelected, False, options) except Exception as e: ret = -1 errMsg = unicode(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: output = qgis.gui.QgsMessageViewer() output.setTitle(self.tr("Import to database")) output.setMessageAsPlainText(self.tr("Error %d\n%s") % (ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): self.db.connector.createSpatialIndex((schema, table), geom) QMessageBox.information(self, self.tr("Import to database"), self.tr("Import was successful.")) return QDialog.accept(self)
def accept(self): # sanity checks if self.editOutputFile.text() == "": QMessageBox.information(self, self.tr("Export to file"), self.tr("Output file name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = int(self.editSourceSrid.text()) except ValueError: QMessageBox.information( self, self.tr("Export to file"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = int(self.editTargetSrid.text()) except ValueError: QMessageBox.information( self, self.tr("Export to file"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs, so I can restore it later prevInCrs = self.inLayer.crs() try: uri = self.editOutputFile.text() providerName = "ogr" options = {} # set the OGR driver will be used driverName = self.cboFileFormat.itemData( self.cboFileFormat.currentIndex()) options['driverName'] = driverName # set the output file encoding if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() options['fileEncoding'] = enc if self.chkDropTable.isChecked(): options['overwrite'] = True outCrs = None if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked( ): targetSrid = int(self.editTargetSrid.text()) outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid) # update input layer crs if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked( ): sourceSrid = int(self.editSourceSrid.text()) inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) # do the export! ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer( self.inLayer, uri, providerName, outCrs, False, False, options) except Exception as e: ret = -1 errMsg = unicode(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: QMessageBox.warning(self, self.tr("Export to file"), self.tr("Error %d\n%s") % (ret, errMsg)) return # create spatial index # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): # self.db.connector.createSpatialIndex( (schema, table), geom ) QMessageBox.information(self, self.tr("Export to file"), self.tr("Export finished.")) return QDialog.accept(self)
def showHelp(self): helpText = u"""In this dialog you can set up versioning support for a table. The table will be modified so that all changes will be recorded: there will be a column with start time and end time. Every row will have its start time, end time is assigned when the feature gets deleted. When a row is modified, the original data is marked with end time and new row is created. With this system, it's possible to get back to state of the table any time in history. When selecting rows from the table, you will always have to specify at what time do you want the rows.""" QMessageBox.information(self, "Help", helpText)
def processingFinished(self): self.stopProcessing() QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed."))
def accept(self): # sanity checks if self.editOutputFile.text() == "": QMessageBox.information(self, self.tr("Export to file"), self.tr("Output file name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = int(self.editSourceSrid.text()) except ValueError: QMessageBox.information(self, self.tr("Export to file"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = int(self.editTargetSrid.text()) except ValueError: QMessageBox.information(self, self.tr("Export to file"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs, so I can restore it later prevInCrs = self.inLayer.crs() try: uri = self.editOutputFile.text() providerName = "ogr" options = {} # set the OGR driver will be used driverName = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex()) options['driverName'] = driverName # set the output file encoding if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() options['fileEncoding'] = enc if self.chkDropTable.isChecked(): options['overwrite'] = True outCrs = None if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid) # update input layer crs if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): sourceSrid = int(self.editSourceSrid.text()) inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) # do the export! ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer(self.inLayer, uri, providerName, outCrs, False, False, options) except Exception as e: ret = -1 errMsg = unicode(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: QMessageBox.warning(self, self.tr("Export to file"), self.tr("Error %d\n%s") % (ret, errMsg)) return # create spatial index # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): # self.db.connector.createSpatialIndex( (schema, table), geom ) QMessageBox.information(self, self.tr("Export to file"), self.tr("Export finished.")) return QDialog.accept(self)
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.information( self, self.tr("Import to database"), self.tr("Input layer missing or not valid")) return if self.cboTable.currentText() == "": QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = self.editSourceSrid.text() except ValueError: QMessageBox.information( self, self.tr("Import to database"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = self.editTargetSrid.text() except ValueError: QMessageBox.information( self, self.tr("Import to database"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled( ) else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = qgis.core.QgsDataSourceURI(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked( ) else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled( ): geom = srcUri.geometryColumn( ) if not self.chkGeomColumn.isChecked( ) else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) uri = self.outUri.uri(False) providerName = self.db.dbplugin().providerName() options = {} if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked( ): options['forceSinglePartGeometryType'] = True outCrs = None if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked( ): targetSrid = int(self.editTargetSrid.text()) outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid) # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked( ): sourceSrid = int(self.editSourceSrid.text()) inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer( self.inLayer, uri, providerName, outCrs, onlySelected, False, options) except Exception as e: ret = -1 errMsg = unicode(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: output = qgis.gui.QgsMessageViewer() output.setTitle(self.tr("Import to database")) output.setMessageAsPlainText( self.tr("Error %d\n%s") % (ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked( ): self.db.connector.createSpatialIndex((schema, table), geom) QMessageBox.information(self, self.tr("Import to database"), self.tr("Import was successful.")) return QDialog.accept(self)