Skip to content
Permalink
Browse files
dbmanager: allow to import layer from canvas (fix #6824),
add dialog to choose vector file to be imported (fix #6825),
allow to export table to vector file (fix #6826)

Thanks to Silvio Grosso for the sponsorship!
  • Loading branch information
brushtyler committed Dec 5, 2012
1 parent fcf108d commit de3ea74ab6c96bae54166dd891d93223475f3643
@@ -144,6 +144,30 @@ def refreshActionSlot(self):
self.preview.setDirty()
self.refreshItem()

def importActionSlot(self):
db = self.tree.currentDatabase()
if db is None:
QMessageBox.information(self, "Sorry", "No database selected or you are not connected to it.")
return

from .dlg_import_vector import DlgImportVector
dlg = DlgImportVector(None, db, db.uri(), self)
dlg.exec_()

def exportActionSlot(self):
table = self.tree.currentTable()
if table is None:
QMessageBox.information(self, "Sorry", "Select the table you want export to file.")
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 == None:
@@ -289,7 +313,6 @@ def unregisterAction(self, action, menuName):
menuActions[i].setVisible(False)
break


action.deleteLater()
return True

@@ -365,13 +388,17 @@ def setupUi(self):

# 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"), "&Import layer/file", self.importActionSlot )
self.actionExport = self.menuTable.addAction( QIcon(":/db_manager/actions/export"), "&Export to file", self.exportActionSlot )
self.menuTable.addSeparator()
#self.actionShowSystemTables = self.menuTable.addAction("Show system tables/views", self.showSystemTables)
#self.actionShowSystemTables.setCheckable(True)
#self.actionShowSystemTables.setChecked(True)
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)

# 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 )

@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-

"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QuantumGIS
Date : Oct 13, 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 *

import qgis.core
from qgis.utils import iface

from .ui.ui_DlgExportVector import Ui_DlgExportVector

class DlgExportVector(QDialog, Ui_DlgExportVector):

def __init__(self, inLayer, inDb, parent=None):
QDialog.__init__(self, parent)
self.inLayer = inLayer
self.db = inDb
self.setupUi(self)

# update UI
self.setupWorkingMode()
self.populateEncodings()

def setupWorkingMode(self):
# set default values
inCrs = self.inLayer.crs()
srid = inCrs.postgisSrid() if inCrs.isValid() else 4236
self.editSourceSrid.setText( "%s" % srid )
self.editTargetSrid.setText( "%s" % srid )

QObject.connect( self.btnChooseOutputFile, SIGNAL("clicked()"), self.chooseOutputFile )
self.checkSupports()

def checkSupports(self):
""" update options available for the current input layer """
allowSpatial = self.db.connector.hasSpatialSupport()
hasGeomType = self.inLayer and self.inLayer.hasGeometryType()
self.chkSourceSrid.setEnabled(allowSpatial and hasGeomType)
self.chkTargetSrid.setEnabled(allowSpatial and hasGeomType)
self.chkSpatialIndex.setEnabled(allowSpatial and hasGeomType)


def chooseOutputFile(self):
# get last used dir and format
settings = QSettings()
lastDir = settings.value("/db_manager/lastUsedDir", "").toString()
# ask for a filename
filename = QFileDialog.getSaveFileName(self, "Choose where to save the file", lastDir, "Shapefiles (*.shp)")
if filename == "":
return
if filename[:-4] != ".shp":
filename += ".shp"
# store the last used dir and format
settings.setValue("/db_manager/lastUsedDir", QFileInfo(filename).filePath())

self.editOutputFile.setText( filename )

def populateEncodings(self):
# populate the combo with supported encodings
self.cboEncoding.addItems(qgis.core.QgsVectorDataProvider.availableEncodings())

# set the last used encoding
settings = QSettings()
enc = self.inLayer.dataProvider().encoding()
idx = self.cboEncoding.findText( enc )
if idx < 0:
self.cboEncoding.insertItem( 0, enc )
idx = 0
self.cboEncoding.setCurrentIndex( idx )

def accept(self):
# sanity checks
if self.editOutputFile.text() == "":
QMessageBox.information(self, "Export to file", "Output table name is required")
return

if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid, ok = self.editSourceSrid.text().toInt()
if not ok:
QMessageBox.information(self, "Export to file", "Invalid source srid: must be an integer")
return

if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid, ok = self.editTargetSrid.text().toInt()
if not ok:
QMessageBox.information(self, "Export to file", "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"
driverName = "ESRI Shapefile"

options = {}

# set the OGR driver will be used
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.radCreate.isChecked() and self.chkDropTable.isChecked():
options['overwrite'] = True
elif self.radAppend.isChecked():
options['append'] = True

outCrs = None
if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid = self.editTargetSrid.text().toInt()[0]
outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

# update input layer crs
if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid = self.editSourceSrid.text().toInt()[0]
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, "Export to file", u"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, "Export to file", "Export finished.")
return QDialog.accept(self)


if __name__ == '__main__':
import sys
a = QApplication(sys.argv)
dlg = DlgLoadData()
dlg.show()
sys.exit(a.exec_())

0 comments on commit de3ea74

Please sign in to comment.