118 changes: 59 additions & 59 deletions python/console/console_sci.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
/***************************************************************************
Python Conosle for QGIS
-------------------
begin : 2012-09-10
begin : 2012-09-10
copyright : (C) 2012 by Salvatore Larosa
email : lrssvtml (at) gmail (dot) com
email : lrssvtml (at) gmail (dot) com
***************************************************************************/
/***************************************************************************
Expand All @@ -22,8 +22,8 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import (QsciScintilla,
QsciScintillaBase,
QsciLexerPython,
QsciScintillaBase,
QsciLexerPython,
QsciAPIs)

import sys
Expand All @@ -38,42 +38,42 @@ def __init__(self, parent=None):
#QsciScintilla.__init__(self, parent)
super(PythonEdit,self).__init__(parent)
code.InteractiveInterpreter.__init__(self, locals=None)

# Enable non-ascii chars for editor
self.setUtf8(True)
self.new_input_line = True

self.new_input_line = True

self.setMarginWidth(0, 0)
self.setMarginWidth(1, 0)
self.setMarginWidth(2, 0)

self.buffer = []

self.displayPrompt(False)

for line in _init_commands:
self.runsource(line)

self.history = QStringList()
self.historyIndex = 0
# Read history command file
self.readHistoryFile()

# Brace matching: enable for a brace immediately before or after
# the current position
self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
#self.moveToMatchingBrace()
#self.selectToMatchingBrace()

# Current line visible with special background color
#self.setCaretLineVisible(True)
#self.setCaretLineBackgroundColor(QColor("#ffe4e4"))
self.setCaretWidth(2)

# Set Python lexer
self.setLexers()

# Indentation
#self.setAutoIndent(True)
#self.setIndentationsUseTabs(False)
Expand All @@ -96,7 +96,7 @@ def __init__(self, parent=None):

self.setWrapMode(QsciScintilla.WrapCharacter)
self.SendScintilla(QsciScintilla.SCI_EMPTYUNDOBUFFER)

## Disable command key
ctrl, shift = self.SCMOD_CTRL<<16, self.SCMOD_SHIFT<<16
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L')+ ctrl)
Expand All @@ -105,21 +105,21 @@ def __init__(self, parent=None):
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('Z')+ ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('Y')+ ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L')+ ctrl+shift)

## New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
self.newShortcutCS = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self)
self.newShortcutCAS = QShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_Space), self)
self.newShortcutCS.activated.connect(self.autoComplete)
self.newShortcutCAS.activated.connect(self.showHistory)
self.connect(self, SIGNAL('userListActivated(int, const QString)'),
self.completion_list_selected)

def showHistory(self):
self.showUserList(1, QStringList(self.history))

def autoComplete(self):
self.autoCompleteFromAll()

def commandConsole(self, command):
if not self.is_cursor_on_last_line():
self.move_cursor_to_end()
Expand All @@ -145,47 +145,47 @@ def commandConsole(self, command):

def setLexers(self):
from qgis.core import QgsApplication

self.lexer = QsciLexerPython()
settings = QSettings()
loadFont = settings.value("pythonConsole/fontfamilytext", "Monospace").toString()
fontSize = settings.value("pythonConsole/fontsize", 10).toInt()[0]

font = QFont(loadFont)
font.setFixedPitch(True)
font.setPointSize(fontSize)
font.setStyleHint(QFont.TypeWriter)
font.setStretch(QFont.SemiCondensed)
font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
font.setBold(False)

self.lexer.setDefaultFont(font)
self.lexer.setColor(Qt.red, 1)
self.lexer.setColor(Qt.darkGreen, 5)
self.lexer.setColor(Qt.darkBlue, 15)
self.lexer.setFont(font, 1)
self.lexer.setFont(font, 3)
self.lexer.setFont(font, 4)

self.api = QsciAPIs(self.lexer)
chekBoxAPI = settings.value("pythonConsole/preloadAPI", True).toBool()
if chekBoxAPI:
self.api.loadPrepared( QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap" )
else:
apiPath = settings.value("pythonConsole/userAPI").toStringList()
for i in range(0, len(apiPath)):
self.api.load(QString(unicode(apiPath[i])))
self.api.load(QString(unicode(apiPath[i])))
self.api.prepare()
self.lexer.setAPIs(self.api)

self.setLexer(self.lexer)

## TODO: show completion list for file and directory

def completion_list_selected(self, id, txt):
if id == 1:
txt = unicode(txt)
# get current cursor position
# get current cursor position
line, pos = self.getCursorPosition()
selCmdLength = self.text(line).length()
# select typed text
Expand Down Expand Up @@ -215,24 +215,24 @@ def get_end_pos(self):
"""Return (line, index) position of the last character"""
line = self.lines() - 1
return (line, self.text(line).length())

def is_cursor_at_end(self):
"""Return True if cursor is at the end of text"""
cline, cindex = self.getCursorPosition()
return (cline, cindex) == self.get_end_pos()

def move_cursor_to_end(self):
"""Move cursor to end of text"""
line, index = self.get_end_pos()
self.setCursorPosition(line, index)
self.ensureCursorVisible()
self.ensureLineVisible(line)

# def on_new_line(self):
# """On new input line"""
# self.move_cursor_to_end()
# self.new_input_line = False

def is_cursor_on_last_line(self):
"""Return True if cursor is on the last line"""
cline, _ = self.getCursorPosition()
Expand All @@ -242,7 +242,7 @@ def is_cursor_on_edition_zone(self):
""" Return True if the cursor is in the edition zone """
cline, cindex = self.getCursorPosition()
return cline == self.lines() - 1 and cindex >= 4

def new_prompt(self, prompt):
"""
Print a new prompt and save its (line, index) position
Expand All @@ -252,10 +252,10 @@ def new_prompt(self, prompt):
line, index = self.getCursorPosition()
self.ensureCursorVisible()
self.ensureLineVisible(line)

def refreshLexerProperties(self):
self.setLexers()

# def check_selection(self):
# """
# Check if selected text is r/w,
Expand All @@ -273,7 +273,7 @@ def refreshLexerProperties(self):
def displayPrompt(self, more=False):
self.append("... ") if more else self.append(">>> ")
self.move_cursor_to_end()

def updateHistory(self, command):
if isinstance(command, QStringList):
for line in command:
Expand All @@ -283,13 +283,13 @@ def updateHistory(self, command):
not command == self.history[-1]:
self.history.append(command)
self.historyIndex = len(self.history)

def writeHistoryFile(self):
wH = open(_historyFile, 'w')
for s in self.history:
wH.write(s + '\n')
wH.close()

def readHistoryFile(self):
fileExist = QFile.exists(_historyFile)
if fileExist:
Expand All @@ -300,11 +300,11 @@ def readHistoryFile(self):
self.updateHistory(l)
else:
return

def clearHistoryFile(self):
cH = open(_historyFile, 'w')
cH.close()

def showPrevious(self):
if self.historyIndex < len(self.history) and not self.history.isEmpty():
line, pos = self.getCursorPosition()
Expand All @@ -319,7 +319,7 @@ def showPrevious(self):
self.insert(self.history[self.historyIndex])
self.move_cursor_to_end()
#self.SendScintilla(QsciScintilla.SCI_DELETEBACK)

def showNext(self):
if self.historyIndex > 0 and not self.history.isEmpty():
line, pos = self.getCursorPosition()
Expand All @@ -334,7 +334,7 @@ def showNext(self):
self.move_cursor_to_end()
#self.SendScintilla(QsciScintilla.SCI_DELETEBACK)

def keyPressEvent(self, e):
def keyPressEvent(self, e):
startLine, _, endLine, _ = self.getSelection()

# handle invalid cursor position and multiline selections
Expand Down Expand Up @@ -393,8 +393,8 @@ def keyPressEvent(self, e):
## TODO: press event for auto-completion file directory
else:
QsciScintilla.keyPressEvent(self, e)
def contextMenuEvent(self, e):

def contextMenuEvent(self, e):
menu = QMenu(self)
copyAction = menu.addAction("Copy", self.copy, QKeySequence.Copy)
pasteAction = menu.addAction("Paste", self.paste, QKeySequence.Paste)
Expand All @@ -405,7 +405,7 @@ def contextMenuEvent(self, e):
if QApplication.clipboard().text() != "":
pasteAction.setEnabled(True)
action = menu.exec_(self.mapToGlobal(e.pos()))

def mousePressEvent(self, e):
"""
Re-implemented to handle the mouse press event.
Expand All @@ -420,12 +420,12 @@ def mousePressEvent(self, e):
e.accept()
else:
QsciScintilla.mousePressEvent(self, e)

def paste(self):
"""
Method to display data from the clipboard.
Method to display data from the clipboard.
XXX: It should reimplement the virtual QScintilla.paste method,
XXX: It should reimplement the virtual QScintilla.paste method,
but it seems not used by QScintilla code.
"""
stringPaste = unicode(QApplication.clipboard().text())
Expand All @@ -435,7 +435,7 @@ def paste(self):
else:
self.move_cursor_to_end()
self.insertFromDropPaste(stringPaste)

## Drag and drop
def dropEvent(self, e):
if e.mimeData().hasText():
Expand All @@ -447,7 +447,7 @@ def dropEvent(self, e):
else:
QsciScintillaCompat.dropEvent(self, e)

def insertFromDropPaste(self, textDP):
def insertFromDropPaste(self, textDP):
pasteList = textDP.split("\n")
for line in pasteList[:-1]:
line.replace(">>> ", "").replace("... ", "")
Expand All @@ -464,7 +464,7 @@ def insertFromDropPaste(self, textDP):
# text = self.text()
# textList = text.split("\n")
# return textList

def insertTextFromFile(self, listOpenFile):
for line in listOpenFile[:-1]:
self.append(line)
Expand All @@ -474,14 +474,14 @@ def insertTextFromFile(self, listOpenFile):
self.append(unicode(listOpenFile[-1]))
self.move_cursor_to_end()
self.SendScintilla(QsciScintilla.SCI_DELETEBACK)

def entered(self):
self.move_cursor_to_end()
self.runCommand( unicode(self.currentCommand()) )
self.runCommand( unicode(self.currentCommand()) )
self.setFocus()
self.move_cursor_to_end()
#self.SendScintilla(QsciScintilla.SCI_EMPTYUNDOBUFFER)

def currentCommand(self):
linenr, index = self.getCursorPosition()
#for i in range(0, linenr):
Expand All @@ -502,22 +502,22 @@ def runCommand(self, cmd):
if cmd in ('_save', '_clear', '_clearAll', '_pyqgis', '_api'):
if cmd == '_save':
self.writeHistoryFile()
print QCoreApplication.translate("PythonConsole",
print QCoreApplication.translate("PythonConsole",
"## History saved successfully ##")
elif cmd == '_clear':
self.clearHistoryFile()
print QCoreApplication.translate("PythonConsole",
print QCoreApplication.translate("PythonConsole",
"## History cleared successfully ##")
elif cmd == '_clearAll':
self.history = QStringList()
self.clearHistoryFile()
print QCoreApplication.translate("PythonConsole",
print QCoreApplication.translate("PythonConsole",
"## Session and file history cleared successfully ##")
elif cmd == '_pyqgis':
webbrowser.open( "http://www.qgis.org/pyqgis-cookbook/" )
elif cmd == '_api':
webbrowser.open( "http://www.qgis.org/api/" )

self.displayPrompt(False)
else:
self.buffer.append(cmd)
Expand Down
30 changes: 15 additions & 15 deletions python/console/console_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,21 @@ def __init__(self, parent):
self.parent = parent
self.setupUi(self)
#self.show()

self.listPath = []

self.restoreSettings()
self.initialCheck()
self.fontConfig()

self.lineEdit.setReadOnly(True)

self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.png"))
self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path"))
self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.png"))
self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path"))
self.connect( self.preloadAPI,

self.connect( self.preloadAPI,
SIGNAL("stateChanged(int)"), self.initialCheck)
self.connect(self.browseButton,
SIGNAL("clicked()"), self.loadAPIFile)
Expand All @@ -60,7 +60,7 @@ def initialCheck(self):
self.enableDisable(False)
else:
self.enableDisable(True)

def enableDisable(self, value):
self.tableWidget.setEnabled(value)
self.lineEdit.setEnabled(value)
Expand All @@ -74,10 +74,10 @@ def loadAPIFile(self):
fileAPI = QFileDialog.getOpenFileName(
self, "Open API File", lastDirPath, "API file (*.api)")
self.lineEdit.setText(fileAPI)

lastDirPath = QFileInfo(fileAPI).path()
settings.setValue("pythonConsole/lastDirAPIPath", QVariant(fileAPI))

def accept(self):
if not self.preloadAPI.isChecked():
if self.tableWidget.rowCount() == 0:
Expand All @@ -87,7 +87,7 @@ def accept(self):
self.saveSettings()
self.listPath = []
QDialog.accept( self )

def addAPI(self):
if self.lineEdit.text() == "":
return
Expand All @@ -110,17 +110,17 @@ def addAPI(self):

def removeAPI(self):
listItemSel = self.tableWidget.selectedIndexes()
#row = self.tableWidget.currentRow()
#row = self.tableWidget.currentRow()
for indx in listItemSel:
self.tableWidget.removeRow(indx.row())

def fontConfig(self):
#fontFamily = ['Courier','Monospace','Aurulent Sans','Bitstream Vera Serif']
#for i in range(0, len(fontFamily)):
#self.comboBox.addItem(fontFamily[i])
settings = QSettings()
self.fontComboBox.setCurrentIndex(settings.value("pythonConsole/fontfamilyindex").toInt()[0])

def saveSettings(self):
settings = QSettings()
settings.setValue("pythonConsole/preloadAPI", QVariant(self.preloadAPI.isChecked()))
Expand All @@ -134,7 +134,7 @@ def saveSettings(self):
self.listPath.append(text)
settings.setValue("pythonConsole/fontsize", QVariant(fontSize))
settings.setValue("pythonConsole/userAPI", QVariant(self.listPath))

def restoreSettings(self):
settings = QSettings()
self.spinBox.setValue(settings.value("pythonConsole/fontsize").toInt()[0])
Expand All @@ -152,6 +152,6 @@ def restoreSettings(self):
self.tableWidget.horizontalHeader().show()
self.tableWidget.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
#self.comboBox.setCurrentIndex(settings.value("pythonConsole/fontfamilyindex").toInt()[0])

def reject( self ):
QDialog.reject( self )
6 changes: 3 additions & 3 deletions python/core/qgscredentials.sip
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ class QgsCredentials
//! virtual destructor
virtual ~QgsCredentials();

bool get( QString realm, QString &username, QString &password, QString message = QString::null );
bool get( QString realm, QString &username /In,Out/, QString &password /In,Out/, QString message = QString::null );
void put( QString realm, QString username, QString password );

//! retrieves instance
static QgsCredentials *instance();

protected:
//! request a password
virtual bool request( QString realm, QString &username, QString &password, QString message = QString::null ) = 0;
virtual bool request( QString realm, QString &username /In,Out/, QString &password /In,Out/, QString message = QString::null ) = 0;

//! register instance
void setInstance( QgsCredentials *theInstance );
Expand All @@ -37,5 +37,5 @@ class QgsCredentialsConsole : QObject, QgsCredentials
void destroyed();

protected:
virtual bool request( QString realm, QString &username, QString &password, QString message = QString::null );
virtual bool request( QString realm, QString &username /In,Out/, QString &password /In,Out/, QString message = QString::null );
};
2 changes: 1 addition & 1 deletion python/gui/qgscredentialdialog.sip
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ class QgsCredentialDialog : QDialog, QgsCredentials
~QgsCredentialDialog();

protected:
virtual bool request( QString realm, QString &username, QString &password, QString message = QString::null );
virtual bool request( QString realm, QString &username /In,Out/, QString &password /In,Out/, QString message = QString::null );
};
18 changes: 9 additions & 9 deletions python/plugins/GdalTools/tools/GdalTools_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,9 @@ def fillVectorOutputFormat(aFilter = None, filename = None):
return shortName

class UnsupportedOGRFormat(Exception):
def __init__(self):
def __init__(self):
msg = QCoreApplication.translate( "GdalTools", "The selected file is not a supported OGR format" )
Exception.__init__(self, msg)
Exception.__init__(self, msg)

def getVectorFields(vectorFile):
hds = ogr.Open( unicode(vectorFile).encode('utf8') )
Expand Down Expand Up @@ -312,10 +312,10 @@ def getRasterExtent(parent, fileName):
if processSRS.waitForFinished():
arr = processSRS.readAllStandardOutput()
processSRS.close()

if arr.isEmpty():
return

info = QString( arr ).split( "\n" )
ulCoord = info[ info.indexOf( QRegExp( "^Upper\sLeft.*" ) ) ].simplified()
lrCoord = info[ info.indexOf( QRegExp( "^Lower\sRight.*" ) ) ].simplified()
Expand Down Expand Up @@ -426,7 +426,7 @@ def allRastersFilter(self):
QgsRasterLayer.buildSupportedRasterFileFilter(self.rastersFilter)

# workaround for QGis < 1.5 (see #2376)
# separates multiple extensions that joined by a slash
# separates multiple extensions that joined by a slash
if QGis.QGIS_VERSION[0:3] < "1.5":
formats = self.rastersFilter.split( ";;" )
self.rastersFilter = QString()
Expand Down Expand Up @@ -771,7 +771,7 @@ def string2vers(string):
vers = ['0', '0', '0']

nums = str(string).split(".")

if len(nums) > 0:
vers[0] = nums[0]
if len(nums) > 1:
Expand All @@ -797,7 +797,7 @@ def __str__(self):

def setProcessEnvironment(process):
envvar_list = {
"PATH" : getGdalBinPath(),
"PATH" : getGdalBinPath(),
"PYTHONPATH" : getGdalPymodPath()
}

Expand Down Expand Up @@ -836,13 +836,13 @@ def setMacOSXDefaultEnvironment():
# QgsApplication.prefixPath() contains the path to qgis executable (i.e. .../Qgis.app/MacOS)
# get the path to Qgis application folder
qgis_app = u"%s/.." % QgsApplication.prefixPath()
qgis_app = QDir( qgis_app ).absolutePath()
qgis_app = QDir( qgis_app ).absolutePath()

qgis_bin = u"%s/bin" % QgsApplication.prefixPath() # path to QGis bin folder
qgis_python = u"%s/Resources/python" % qgis_app # path to QGis python folder

# path to the GDAL framework within the Qgis application folder (QGis standalone only)
qgis_standalone_gdal_path = u"%s/Frameworks/GDAL.framework" % qgis_app
qgis_standalone_gdal_path = u"%s/Frameworks/GDAL.framework" % qgis_app

# path to the GDAL framework when installed as external framework
gdal_bin_path = u"/Library/Frameworks/GDAL.framework/Versions/%s/Programs" % str(GdalConfig.version())[:3]
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/tools/doBuildVRT.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def __init__(self, iface):

self.setParamsStatus(
[
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.resolutionComboBox, SIGNAL("currentIndexChanged(int)"), self.resolutionCheck),
(self.srcNoDataSpin, SIGNAL("valueChanged(int)"), self.srcNoDataCheck, "1.7.0"),
(self.inputDirCheck, SIGNAL("stateChanged(int)")),
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/doClipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, iface):
(self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck, "1.7.0"),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskModeRadio, "1.6.0"),
(self.alphaBandCheck, SIGNAL( "stateChanged( int )") ),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentModeRadio),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentModeRadio),
(self.modeStackedWidget, SIGNAL("currentIndexChanged(int)"))
]
)
Expand Down
24 changes: 12 additions & 12 deletions python/plugins/GdalTools/tools/doDEM.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,19 @@ def __init__(self, iface):

self.setParamsStatus(
[
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.computeEdgesCheck, SIGNAL("stateChanged(int)"), None, "1.8.0"),
(self.bandSpin, SIGNAL("valueChanged(int)"), self.bandCheck),
(self.algorithmCheck, SIGNAL("stateChanged(int)"), None, "1.8.0"),
(self.creationOptionsTable, [SIGNAL("cellValueChanged(int, int)"), SIGNAL("rowRemoved()")], self.creationGroupBox),
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.computeEdgesCheck, SIGNAL("stateChanged(int)"), None, "1.8.0"),
(self.bandSpin, SIGNAL("valueChanged(int)"), self.bandCheck),
(self.algorithmCheck, SIGNAL("stateChanged(int)"), None, "1.8.0"),
(self.creationOptionsTable, [SIGNAL("cellValueChanged(int, int)"), SIGNAL("rowRemoved()")], self.creationGroupBox),
(self.modeCombo, SIGNAL("currentIndexChanged(int)")),
([self.hillshadeZFactorSpin, self.hillshadeScaleSpin, self.hillshadeAltitudeSpin, self.hillshadeAzimuthSpin], SIGNAL("valueChanged(double)")),
(self.slopeScaleSpin, SIGNAL("valueChanged(double)")),
(self.slopePercentCheck, SIGNAL("stateChanged(int)")),
([self.aspectTrigonometricCheck, self.aspectZeroForFlatCheck], SIGNAL("stateChanged(int)")),
(self.configSelector, SIGNAL("filenameChanged()")),
([self.colorExactRadio, self.colorNearestRadio], SIGNAL("toggled(bool)"), self.colorMatchGroupBox),
([self.hillshadeZFactorSpin, self.hillshadeScaleSpin, self.hillshadeAltitudeSpin, self.hillshadeAzimuthSpin], SIGNAL("valueChanged(double)")),
(self.slopeScaleSpin, SIGNAL("valueChanged(double)")),
(self.slopePercentCheck, SIGNAL("stateChanged(int)")),
([self.aspectTrigonometricCheck, self.aspectZeroForFlatCheck], SIGNAL("stateChanged(int)")),
(self.configSelector, SIGNAL("filenameChanged()")),
([self.colorExactRadio, self.colorNearestRadio], SIGNAL("toggled(bool)"), self.colorMatchGroupBox),
(self.colorAlphaCheck, SIGNAL("stateChanged(int)"))
]
)
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/GdalTools/tools/doGrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ def __init__(self, iface):
([self.nearestRadius1Spin, self.nearestRadius2Spin, self.nearestAngleSpin, self.nearestNoDataSpin], SIGNAL("valueChanged(double)")),
(self.datametricsCombo, SIGNAL("currentIndexChanged(int)")),
([self.datametricsRadius1Spin, self.datametricsRadius2Spin, self.datametricsAngleSpin, self.datametricsNoDataSpin], SIGNAL("valueChanged(double)")),
(self.datametricsMinPointsSpin, SIGNAL("valueChanged(int)")),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentGroup),
(self.datametricsMinPointsSpin, SIGNAL("valueChanged(int)")),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentGroup),
( [self.widthSpin, self.heightSpin], SIGNAL( "valueChanged(int)" ), self.resizeGroupBox )
]
)
Expand All @@ -98,7 +98,7 @@ def fillFieldsCombo(self):

self.lastEncoding = self.inSelector.layer().dataProvider().encoding()
self.loadFields( self.getInputFileName() )

def fillInputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedVectorFilter()
inputFile, encoding = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file for Grid" ), Utils.FileFilter.allVectorsFilter(), lastUsedFilter, True)
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/GdalTools/tools/doMerge.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def __init__(self, iface):

self.setParamsStatus(
[
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck),
(self.inputDirCheck, SIGNAL("stateChanged(int)")),
(self.recurseCheck, SIGNAL("stateChanged(int)"), self.inputDirCheck),
Expand Down Expand Up @@ -116,7 +116,7 @@ def refreshExtent(self):
QMessageBox.warning( self, self.tr( "Empty extent" ), self.tr( 'The computed extent is empty. \nDisable the "Use intersected extent" option to have a nonempty output.' ) )

self.someValueChanged()

def fillOutputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select where to save the Merge output" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/doPolygonize.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def getOutputFileName(self):

def getInputFileName(self):
return self.inSelector.filename()

def getMaskFileName(self):
return self.maskSelector.filename()

Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/tools/doRasterize.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def fillOutputFileEdit(self):

self.outSelector.setFilename(outputFile)

# required either -ts or -tr to create the output file
# required either -ts or -tr to create the output file
if gdalVersion >= "1.8.0":
if not QFileInfo(outputFile).exists():
QMessageBox.information( self, self.tr( "Output size required" ), self.tr( "The output file doesn't exist. You must set up the output size to create it." ) )
Expand All @@ -118,7 +118,7 @@ def getArguments(self):
arguments << str( self.heightSpin.value() )
inputFn = self.getInputFileName()
if not inputFn.isEmpty():
arguments << "-l"
arguments << "-l"
arguments << QFileInfo( inputFn ).baseName()
arguments << inputFn
arguments << self.getOutputFileName()
Expand Down
8 changes: 4 additions & 4 deletions python/plugins/GdalTools/tools/doSettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def __init__( self, iface ):
QObject.connect( self.btnSetBinPath, SIGNAL( "clicked()" ), self.setBinPath )
self.bin_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.bin_tooltip_label.setToolTip( self.tr( \
u"""A list of colon-separated (Linux and MacOS) or
semicolon-separated (Windows) paths to both binaries
u"""A list of colon-separated (Linux and MacOS) or
semicolon-separated (Windows) paths to both binaries
and python executables.
MacOS users usually need to set it to something like
Expand All @@ -57,15 +57,15 @@ def __init__( self, iface ):
QObject.connect( self.btnSetPymodPath, SIGNAL( "clicked()" ), self.setPymodPath )
self.pymod_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.pymod_tooltip_label.setToolTip( self.tr( \
u"""A list of colon-separated (Linux and MacOS) or
u"""A list of colon-separated (Linux and MacOS) or
semicolon-separated (Windows) paths to python modules.""") )

# help
self.leGdalHelpPath.setText( Utils.getHelpPath() )
QObject.connect( self.btnSetHelpPath, SIGNAL( "clicked()" ), self.setHelpPath )
self.help_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.help_tooltip_label.setToolTip( self.tr( \
u"""Useful to open local GDAL documentation instead of online help
u"""Useful to open local GDAL documentation instead of online help
when pressing on the tool dialog's Help button.""") )


Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/tools/doWarp.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ def __init__(self, iface):
(self.cacheSpin, SIGNAL("valueChanged(int)"), self.cacheCheck),
( [self.widthSpin, self.heightSpin], SIGNAL( "valueChanged(int)" ), self.resizeGroupBox ),
(self.multithreadCheck, SIGNAL("stateChanged(int)")),
(self.noDataEdit, SIGNAL( "textChanged( const QString & )" ), self.noDataCheck),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskCheck, "1.6.0"),
(self.noDataEdit, SIGNAL( "textChanged( const QString & )" ), self.noDataCheck),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskCheck, "1.6.0"),
]
)

Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/tools/inOutSelector.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def setFilename(self, fn=None):
fn = fn.join( "," )
else:
fn = QString()

else:
fn = QString()

Expand Down Expand Up @@ -207,7 +207,7 @@ def setLayers(self, layers=None):
self.filenameChanged()
if self.layer() != prevLayer:
self.layerChanged()


def clearComboState(self):
self.prevState = None
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/GdalTools/tools/widgetPluginBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def finished(self, load):

outFn = QString(outFn)
if outFn.isEmpty():
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "No output file created." ) )
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "No output file created." ) )
return

fileInfo = QFileInfo(outFn)
Expand All @@ -120,8 +120,8 @@ def finished(self, load):
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) )

# This method is useful to set up options for the command. It sets for each passed widget:
# 1. its passed signals to connect to the BasePluginWidget.someValueChanged() slot,
# 2. its enabler checkbox or enabled status,
# 1. its passed signals to connect to the BasePluginWidget.someValueChanged() slot,
# 2. its enabler checkbox or enabled status,
# 3. its status as visible (hide) if the installed gdal version is greater or equal (lesser) then the passed version
#
# wdgts_sgnls_chk_ver_list: list of wdgts_sgnls_chk_ver
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/db_manager/db_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def runSqlWindow(self):
#self.connect( dlg, SIGNAL( "queryExecuted(const QString &)" ), refreshDb )
dlg.show()
dlg.exec_()


def showSystemTables(self):
self.tree.showSystemTables( self.actionShowSystemTables.isChecked() )
Expand Down Expand Up @@ -357,7 +357,7 @@ def setupUi(self):

# create status bar
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
self.setStatusBar(self.statusBar)

# create menus
self.menuBar = QMenuBar(self)
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_manager_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def unload(self):
self.iface.removeDatabaseToolBarIcon(self.action)
else:
self.iface.removeToolBarIcon(self.action)

if self.dlg != None:
self.dlg.close()

Expand Down
44 changes: 22 additions & 22 deletions python/plugins/db_manager/db_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ def __init__(self, data, parent=None):
self.populated = False
self.itemData = data
self.childItems = []
if parent:
if parent:
parent.appendChild(self)

def childRemoved(self, child):
self.itemChanged()
self.itemChanged()

def itemChanged(self):
self.emit( SIGNAL("itemChanged"), self )
Expand All @@ -62,7 +62,7 @@ def getItemData(self):
def appendChild(self, child):
self.childItems.append(child)
self.connect(child, SIGNAL("itemRemoved"), self.childRemoved)

def child(self, row):
return self.childItems[row]

Expand All @@ -71,13 +71,13 @@ def removeChild(self, row):
self.childItems[row].itemData.deleteLater()
self.disconnect(self.childItems[row], SIGNAL("itemRemoved"), self.childRemoved)
del self.childItems[row]

def childCount(self):
return len(self.childItems)

def columnCount(self):
return 1

def row(self):
if self.parent():
for row, item in enumerate(self.parent().childItems):
Expand All @@ -87,7 +87,7 @@ def row(self):

def data(self, column):
return "" if column == 0 else None

def icon(self):
return None

Expand Down Expand Up @@ -189,10 +189,10 @@ def data(self, column):
if column == 0:
return self.getItemData().name
return None

def icon(self):
return self.schemaIcon

def populate(self):
if self.populated:
return True
Expand All @@ -210,7 +210,7 @@ def __init__(self, table, parent):
self.connect(table, SIGNAL("changed"), self.itemChanged)
self.connect(table, SIGNAL("deleted"), self.itemRemoved)
self.populate()

# load (shared) icon with first instance of table item
if not hasattr(TableItem, 'tableIcon'):
TableItem.tableIcon = QIcon(":/db_manager/icons/table.png")
Expand All @@ -220,15 +220,15 @@ def __init__(self, table, parent):
TableItem.layerPolygonIcon = QIcon(":/db_manager/icons/layer_polygon.png")
TableItem.layerRasterIcon = QIcon(":/db_manager/icons/layer_raster.png")
TableItem.layerUnknownIcon = QIcon(":/db_manager/icons/layer_unknown.png")

def data(self, column):
if column == 0:
return self.getItemData().name
elif column == 1:
if self.getItemData().type == Table.VectorType:
return self.getItemData().geomType
return None

def icon(self):
if self.getItemData().type == Table.VectorType:
geom_type = self.getItemData().geomType
Expand Down Expand Up @@ -327,21 +327,21 @@ def _getPath(self, index):

def columnCount(self, parent):
return 1

def data(self, index, role):
if not index.isValid():
return QVariant()

if role == Qt.DecorationRole and index.column() == 0:
icon = index.internalPointer().icon()
if icon: return QVariant(icon)

if role != Qt.DisplayRole and role != Qt.EditRole:
return QVariant()

retval = index.internalPointer().data(index.column())
return QVariant(retval) if retval else QVariant()

def flags(self, index):
if not index.isValid():
return Qt.NoItemFlags
Expand All @@ -364,7 +364,7 @@ def flags(self, index):
flags |= Qt.ItemIsDropEnabled

return flags

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole and section < len(self.header):
return QVariant(self.header[section])
Expand All @@ -373,7 +373,7 @@ def headerData(self, section, orientation, role):
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QModelIndex()

parentItem = parent.internalPointer() if parent.isValid() else self.rootItem
childItem = parentItem.child(row)
if childItem:
Expand All @@ -383,13 +383,13 @@ def index(self, row, column, parent):
def parent(self, index):
if not index.isValid():
return QModelIndex()

childItem = index.internalPointer()
parentItem = childItem.parent()

if parentItem == self.rootItem:
return QModelIndex()

return self.createIndex(parentItem.row(), 0, parentItem)


Expand All @@ -407,10 +407,10 @@ def hasChildren(self, parent):
def setData(self, index, value, role):
if role != Qt.EditRole or index.column() != 0:
return False

item = index.internalPointer()
new_value = unicode(value.toString())

if isinstance(item, SchemaItem) or isinstance(item, TableItem):
obj = item.getItemData()

Expand Down
14 changes: 7 additions & 7 deletions python/plugins/db_manager/db_plugins/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

from qgis.core import QgsDataSourceURI

from .plugin import DbError, ConnectionError
from .plugin import BaseError, DbError, ConnectionError

class DBConnector:
def __init__(self, uri):
Expand All @@ -34,7 +34,7 @@ def __init__(self, uri):

def __del__(self):
pass #print "DBConnector.__del__", self._uri.connectionInfo()
if self.connection != None:
if self.connection != None:
self.connection.close()
self.connection = None

Expand Down Expand Up @@ -75,16 +75,16 @@ def _execute(self, cursor, sql):
try:
cursor.execute(unicode(sql))

except self.connection_error_types(), e:
except self.connection_error_types() as e:
raise ConnectionError(e)

except self.execution_error_types(), e:
except self.execution_error_types() as e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e, sql)

return cursor

def _execute_and_commit(self, sql):
""" tries to execute and commit some action, on error it rolls back the change """
self._execute(None, sql)
Expand All @@ -111,7 +111,7 @@ def _close_cursor(self, c):
try:
if c and not c.closed:
c.close()

except self.error_types(), e:
pass

Expand Down Expand Up @@ -190,7 +190,7 @@ def quoteId(self, identifier):

identifier = unicode(identifier) if identifier != None else unicode() # make sure it's python unicode string
return u'"%s"' % identifier.replace('"', '""')

@classmethod
def quoteString(self, txt):
""" make the string safe - replace ' with '' """
Expand Down
12 changes: 6 additions & 6 deletions python/plugins/db_manager/db_plugins/data_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ def rowCount(self, parent=None):

def columnCount(self, parent=None):
return len(self._header)

def data(self, index, role):
if role != Qt.DisplayRole and role != Qt.FontRole:
return QVariant()

val = self.getData(index.row(), index.column())

if role == Qt.FontRole: # draw NULL in italic
Expand All @@ -75,11 +75,11 @@ def data(self, index, role):
# too much data to display, elide the string
return QVariant( u"%s..." % val[:300] )
return QVariant( unicode(val) ) # convert to string

def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return QVariant()

if orientation == Qt.Vertical:
# header for a row
return QVariant(section+1)
Expand Down Expand Up @@ -250,7 +250,7 @@ def append(self, constr):
data = [constr.name, constr.type2String(), u", ".join(field_names)]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(constr), Qt.UserRole)
self.setData(self.index(row, 0), QVariant(constr), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(constr.type), Qt.UserRole)
self.setData(self.index(row, 2), QVariant(constr.columns), Qt.UserRole)

Expand Down Expand Up @@ -282,7 +282,7 @@ def append(self, idx):
data = [idx.name, u", ".join(field_names)]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(idx), Qt.UserRole)
self.setData(self.index(row, 0), QVariant(idx), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(idx.columns), Qt.UserRole)

def _getNewObject(self):
Expand Down
30 changes: 15 additions & 15 deletions python/plugins/db_manager/db_plugins/info_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ def generalInfo(self):
return HtmlTable( tbl )

def connectionDetails(self):
tbl = [
("Host:", self.db.connector.host),
tbl = [
("Host:", self.db.connector.host),
("User:", self.db.connector.user)
]
return HtmlTable( tbl )
Expand All @@ -55,9 +55,9 @@ def spatialInfo(self):
return

tbl = [
("Library:", info[0]),
("GEOS:", info[1]),
("Proj:", info[2])
("Library:", info[0]),
("GEOS:", info[1]),
("Proj:", info[2])
]
ret.append( HtmlTable( tbl ) )

Expand All @@ -70,8 +70,8 @@ def spatialInfo(self):
def privilegesDetails(self):
details = self.db.connector.getDatabasePrivileges()
lst = []
if details[0]: lst.append("create new schemas")
if details[1]: lst.append("create temporary tables")
if details[0]: lst.append("create new schemas")
if details[1]: lst.append("create temporary tables")
return HtmlList( lst )

def toHtml(self):
Expand All @@ -94,7 +94,7 @@ def toHtml(self):
else:
ret.append( HtmlSection( 'General info', general_info ) )

# has spatial enabled?
# has spatial enabled?
spatial_info = self.spatialInfo()
if spatial_info == None:
pass
Expand Down Expand Up @@ -176,15 +176,15 @@ def __del__(self):

def generalInfo(self):
if self.table.rowCount == None:
# row count information is not displayed yet, so just block
# row count information is not displayed yet, so just block
# table signals to avoid double refreshing (infoViewer->refreshRowCount->tableChanged->infoViewer)
self.table.blockSignals(True)
self.table.refreshRowCount()
self.table.blockSignals(False)

tbl = [
("Relation type:", "View" if self.table.isView else "Table"),
("Rows:", self.table.rowCount if self.table.rowCount != None else 'Unknown (<a href="action:rows/count">find out</a>)')
("Relation type:", "View" if self.table.isView else "Table"),
("Rows:", self.table.rowCount if self.table.rowCount != None else 'Unknown (<a href="action:rows/count">find out</a>)')
]
if self.table.comment:
tbl.append( ("Comment:", self.table.comment) )
Expand Down Expand Up @@ -228,7 +228,7 @@ def constraintsDetails(self):

# add table contents
for con in self.table.constraints():
# get the fields the constraint is defined on
# get the fields the constraint is defined on
cols = map(lambda p: p[1].name if p[1] != None else u"??? (#%d)" % p[0], con.fields().iteritems())
tbl.append( (con.name, con.type2String(), u'\n'.join(cols)) )

Expand All @@ -247,7 +247,7 @@ def indexesDetails(self):

# add table contents
for idx in self.table.indexes():
# get the fields the index is defined on
# get the fields the index is defined on
cols = map(lambda p: p[1].name if p[1] != None else u"??? (#%d)" % p[0], idx.fields().iteritems())
tbl.append( (idx.name, u'\n'.join(cols)) )

Expand Down Expand Up @@ -379,7 +379,7 @@ def spatialInfo(self):
# estimated extent
if not self.table.isView:
if self.table.estimatedExtent == None:
# estimated extent information is not displayed yet, so just block
# estimated extent information is not displayed yet, so just block
# table signals to avoid double refreshing (infoViewer->refreshEstimatedExtent->tableChanged->infoViewer)
self.table.blockSignals(True)
self.table.refreshTableEstimatedExtent()
Expand Down Expand Up @@ -426,7 +426,7 @@ def spatialInfo(self):
# only if we have info from geometry_columns
srid = self.table.srid if self.table.srid != None else -1
sr_info = self.table.database().connector.getSpatialRefInfo(srid) if srid != -1 else "Undefined"
if sr_info:
if sr_info:
tbl.append( ("Spatial ref:", u"%s (%d)" % (sr_info, srid)) )

# extent
Expand Down
22 changes: 12 additions & 10 deletions python/plugins/db_manager/db_plugins/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def info(self):

def connectToUri(self, uri):
self.db = self.databasesFactory( self, uri )
if self.db:
if self.db:
return True
return False

Expand Down Expand Up @@ -135,7 +135,7 @@ def connections(self):


def databasesFactory(self, connection, uri):
return None
return None


class DbItemObject(QObject):
Expand Down Expand Up @@ -223,7 +223,7 @@ def registerSubPluginActions(self, mainWindow):
def registerDatabaseActions(self, mainWindow):
action = QAction("&Re-connect", self)
mainWindow.registerAction( action, "&Database", self.reconnectActionSlot )

if self.schemas() != None:
action = QAction("&Create schema", self)
mainWindow.registerAction( action, "&Schema", self.createSchemaActionSlot )
Expand Down Expand Up @@ -365,7 +365,7 @@ def prepareMenuMoveTableToSchemaActionSlot(self, item, menu, mainWindow):
menu.clear()
for schema in self.schemas():
action = menu.addAction(schema.name, slot(schema))

def moveTableToSchemaActionSlot(self, item, action, parent, new_schema):
QApplication.restoreOverrideCursor()
try:
Expand Down Expand Up @@ -511,7 +511,7 @@ def delete(self):
ret = self.database().connector.deleteView( (self.schemaName(), self.name) )
else:
ret = self.database().connector.deleteTable( (self.schemaName(), self.name) )
if ret != False:
if ret != False:
self.emit( SIGNAL('deleted') )
return ret

Expand Down Expand Up @@ -566,7 +566,7 @@ def toMapLayer(self):

def getValidQGisUniqueFields(self, onlyOne=False):
""" list of fields valid to load the table as layer in QGis canvas.
QGis automatically search for a valid unique field, so it's
QGis automatically search for a valid unique field, so it's
needed only for queries and views """

ret = []
Expand Down Expand Up @@ -624,6 +624,8 @@ def deleteField(self, fld):
ret = self.database().connector.deleteTableColumn( (self.schemaName(), self.name), fld.name)
if ret != False:
self.refreshFields()
self.refreshConstraints()
self.refreshIndexes()
return ret

def addGeometryColumn(self, geomCol, geomType, srid, dim, createSpatialIndex=False):
Expand Down Expand Up @@ -973,10 +975,10 @@ def update(self, new_name, new_type_str=None, new_not_null=None, new_default_str

class TableConstraint(TableSubItemObject):
""" class that represents a constraint of a table (relation) """

TypeCheck, TypeForeignKey, TypePrimaryKey, TypeUnique = range(4)
types = { "c" : TypeCheck, "f" : TypeForeignKey, "p" : TypePrimaryKey, "u" : TypeUnique }

onAction = { "a" : "NO ACTION", "r" : "RESTRICT", "c" : "CASCADE", "n" : "SET NULL", "d" : "SET DEFAULT" }
matchTypes = { "u" : "UNSPECIFIED", "f" : "FULL", "p" : "PARTIAL" }

Expand Down Expand Up @@ -1033,7 +1035,7 @@ def delete(self):

class TableTrigger(TableSubItemObject):
""" class that represents a trigger """

# Bits within tgtype (pg_trigger.h)
TypeRow = (1 << 0) # row or statement
TypeBefore = (1 << 1) # before or after
Expand Down Expand Up @@ -1064,4 +1066,4 @@ class TableRule(TableSubItemObject):
def __init__(self, table):
TableSubItemObject.__init__(self, table)
self.name = self.definition = None

198 changes: 99 additions & 99 deletions python/plugins/db_manager/db_plugins/postgis/connector.py

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions python/plugins/db_manager/db_plugins/postgis/info_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,21 @@ def generalInfo(self):

# if the estimation is less than 100 rows, try to count them - it shouldn't take long time
if self.table.rowCount == None and self.table.estimatedRowCount < 100:
# row count information is not displayed yet, so just block
# row count information is not displayed yet, so just block
# table signals to avoid double refreshing (infoViewer->refreshRowCount->tableChanged->infoViewer)
self.table.blockSignals(True)
self.table.refreshRowCount()
self.table.blockSignals(False)

tbl = [
("Relation type:", "View" if self.table.isView else "Table"),
("Relation type:", "View" if self.table.isView else "Table"),
("Owner:", self.table.owner)
]
if self.table.comment:
tbl.append( ("Comment:", self.table.comment) )

tbl.extend([
("Pages:", self.table.pages),
("Pages:", self.table.pages),
("Rows (estimation):", self.table.estimatedRowCount )
])

Expand Down Expand Up @@ -105,9 +105,9 @@ def getSpatialInfo(self):
return

tbl = [
("Library:", info[0]),
("Library:", info[0]),
("Scripts:", info[3]),
("GEOS:", info[1]),
("GEOS:", info[1]),
("Proj:", info[2])
]
ret.append( HtmlTable( tbl ) )
Expand Down
8 changes: 4 additions & 4 deletions python/plugins/db_manager/db_plugins/postgis/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def connect(self, parent=None):
uri.setConnection(service, database, username, password, sslmode)
else:
uri.setConnection(host, port, database, username, password, sslmode)

uri.setUseEstimatedMetadata(useEstimatedMetadata)

err = QString()
Expand Down Expand Up @@ -163,7 +163,7 @@ def registerDatabaseActions(self, mainWindow):
Database.registerDatabaseActions(self, mainWindow)

# add a separator
separator = QAction(self);
separator = QAction(self);
separator.setSeparator(True)
mainWindow.registerAction( separator, "&Table" )

Expand Down Expand Up @@ -288,9 +288,9 @@ def gdalUri(self):
def mimeUri(self):
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
return QString( uri )

def toMapLayer(self):
from qgis.core import QgsRasterLayer
from qgis.core import QgsRasterLayer
rl = QgsRasterLayer(self.gdalUri(), self.name)
if rl.isValid():
rl.setContrastEnhancementAlgorithm("StretchToMinimumMaximum")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

"""
/***************************************************************************
Name : TopoViewer plugin for DB Manager
Name : TopoViewer plugin for DB Manager
Description : Create a project to display topology schema on QGis
Date : Sep 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
Expand All @@ -29,17 +29,17 @@
current_path = os.path.dirname(__file__)


# The load function is called when the "db" database or either one of its
# The load function is called when the "db" database or either one of its
# children db objects (table o schema) is selected by the user.
# @param db is the selected database
# @param mainwindow is the DBManager mainwindow
def load(db, mainwindow):
# check whether the selected database has topology enabled
# (search for topology.topology)
sql = u"""SELECT count(*)
sql = u"""SELECT count(*)
FROM pg_class AS cls JOIN pg_namespace AS nsp ON nsp.oid = cls.relnamespace
WHERE cls.relname = 'topology' AND nsp.nspname = 'topology'"""
c = db.connector._get_cursor()
c = db.connector._get_cursor()
db.connector._execute( c, sql )
res = db.connector._fetchone( c )
if res == None or int(res[0]) <= 0:
Expand All @@ -50,7 +50,7 @@ def load(db, mainwindow):
mainwindow.registerAction( action, "&Schema", run )


# The run function is called once the user clicks on the action TopoViewer
# The run function is called once the user clicks on the action TopoViewer
# (look above at the load function) from the DBManager menu/toolbar.
# @param item is the selected db item (either db, schema or table)
# @param action is the clicked action on the DBManager menu/toolbar
Expand All @@ -73,7 +73,7 @@ def run(item, action, mainwindow):

if item.schema() != None:
sql = u"SELECT count(*) FROM topology.topology WHERE name = %s" % quoteStr(item.schema().name)
c = db.connector._get_cursor()
c = db.connector._get_cursor()
db.connector._execute( c, sql )
res = db.connector._fetchone( c )
isTopoSchema = res != None and int(res[0]) > 0
Expand All @@ -82,7 +82,7 @@ def run(item, action, mainwindow):
QMessageBox.critical(mainwindow, "Invalid topology", u'Schema "%s" is not registered in topology.topology.' % item.schema().name)
return False

# load layers into the current project
# load layers into the current project
toponame = item.schema().name
template_dir = os.path.join(current_path, 'templates')
registry = QgsMapLayerRegistry.instance()
Expand All @@ -99,7 +99,7 @@ def run(item, action, mainwindow):

# face
layer = db.toSqlLayer(u'SELECT face_id, topology.ST_GetFaceGeometry(%s, face_id) as geom ' \
'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame)),
'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame)),
'geom', 'face_id', u'%s.face' % toponame)
layer.loadNamedStyle(os.path.join(template_dir, 'face.qml'))
registry.addMapLayer(layer)
Expand Down Expand Up @@ -172,7 +172,7 @@ def run(item, action, mainwindow):

# face_seed
layer = db.toSqlLayer(u'SELECT face_id, ST_PointOnSurface(topology.ST_GetFaceGeometry(%s, face_id)) as geom ' \
'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame)),
'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame)),
'geom', 'face_id', u'%s.face_seed' % toponame)
layer.loadNamedStyle(os.path.join(template_dir, 'face_seed.qml'))
registry.addMapLayer(layer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *

# The load function is called when the "db" database or either one of its
# The load function is called when the "db" database or either one of its
# children db objects (table o schema) is selected by the user.
# @param db is the selected database
# @param mainwindow is the DBManager mainwindow
Expand All @@ -32,7 +32,7 @@ def load(db, mainwindow):
mainwindow.registerAction( action, "&Table", run )


# The run function is called once the user clicks on the action TopoViewer
# The run function is called once the user clicks on the action TopoViewer
# (look above at the load function) from the DBManager menu/toolbar.
# @param item is the selected db item (either db, schema or table)
# @param action is the clicked action on the DBManager menu/toolbar
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self, item, parent=None):

self.connect(self.buttonBox, SIGNAL("accepted()"), self.onOK)
self.connect(self.buttonBox, SIGNAL("helpRequested()"), self.showHelp)

self.populateSchemas()
self.populateTables()

Expand All @@ -62,7 +62,7 @@ def __init__(self, item, parent=None):
self.connect(self.editEnd, SIGNAL("textChanged(const QString &)"), self.updateSql)

self.updateSql()


def populateSchemas(self):
self.cboSchema.clear()
Expand Down Expand Up @@ -124,7 +124,7 @@ def updateSql(self):
self.origPkeyName = self.db.connector.quoteId(constr.name)
self.colOrigPkey = map(lambda (x, y): self.db.connector.quoteId(y.name), constr.fields().iteritems())
break

if self.colOrigPkey is None:
self.txtSql.setPlainText("Table doesn't have a primary key!")
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
Expand All @@ -148,9 +148,9 @@ def updateSql(self):
self.trigger_update = self.get_escaped_name( None, self.table.name, "_update" )
self.trigger_insert = self.get_escaped_name( None, self.table.name, "_insert" )


sql = []

# modify table: add serial column, start time, end time
sql.append( self.sql_alterTable() )
# add primary key to the table
Expand All @@ -167,7 +167,7 @@ def updateSql(self):

self.txtSql.setPlainText( u'\n\n'.join(sql) )
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)

return sql

def showHelp(self):
Expand All @@ -177,7 +177,7 @@ def showHelp(self):

def sql_alterTable(self):
return u"ALTER TABLE %s ADD %s serial, ADD %s timestamp, ADD %s timestamp;" % (self.schematable, self.colPkey, self.colStart, self.colEnd)

def sql_setPkey(self):
return u"ALTER TABLE %s DROP CONSTRAINT %s, ADD PRIMARY KEY (%s);" % (self.schematable, self.origPkeyName, self.colPkey)

Expand Down Expand Up @@ -230,7 +230,7 @@ def sql_functions(self):
$$
LANGUAGE 'plpgsql';""" % { 'view' : self.view, 'schematable': self.schematable, 'cols' : cols, 'oldcols' : old_cols, 'start' : self.colStart, 'end' : self.colEnd, 'func_at_time' : self.func_at_time, 'func_update' : self.func_update, 'func_insert' : self.func_insert }
return sql

def sql_triggers(self):
return u"""
CREATE RULE %(rule_del)s AS ON DELETE TO %(schematable)s
Expand All @@ -255,15 +255,15 @@ def sql_updatesView(self):
INSERT INTO %(schematable)s (%(cols)s) VALUES (%(newcols)s);
CREATE OR REPLACE RULE "_UPDATE" AS ON UPDATE TO %(view)s DO INSTEAD
UPDATE %(schematable)s SET %(assign)s WHERE %(origpkey)s = NEW.%(origpkey)s;""" % { 'view': self.view, 'schematable' : self.schematable, 'cols' : cols, 'newcols' : new_cols, 'assign' : assign_cols, 'origpkey' : self.colOrigPkey }


def onOK(self):
# execute and commit the code
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
try:
sql = u"\n".join(self.updateSql())
self.db.connector._execute_and_commit( sql )

except BaseError, e:
DlgDbError.showError(e, self)
return
Expand Down
126 changes: 63 additions & 63 deletions python/plugins/db_manager/db_plugins/postgis/sql_dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,78 +26,78 @@
# keywords
keywords = [
# TODO get them from a reference page
"action", "add", "after", "all", "alter", "analyze", "and", "as", "asc",
"before", "begin", "between", "by", "cascade", "case", "cast", "check",
"collate", "column", "commit", "constraint", "create", "cross", "current_date",
"current_time", "current_timestamp", "default", "deferrable", "deferred",
"delete", "desc", "distinct", "drop", "each", "else", "end", "escape",
"except", "exists", "for", "foreign", "from", "full", "group", "having",
"ignore", "immediate", "in", "initially", "inner", "insert", "intersect",
"into", "is", "isnull", "join", "key", "left", "like", "limit", "match",
"natural", "no", "not", "notnull", "null", "of", "offset", "on", "or", "order",
"outer", "primary", "references", "release", "restrict", "right", "rollback",
"row", "savepoint", "select", "set", "table", "temporary", "then", "to",
"transaction", "trigger", "union", "unique", "update", "using", "values",
"action", "add", "after", "all", "alter", "analyze", "and", "as", "asc",
"before", "begin", "between", "by", "cascade", "case", "cast", "check",
"collate", "column", "commit", "constraint", "create", "cross", "current_date",
"current_time", "current_timestamp", "default", "deferrable", "deferred",
"delete", "desc", "distinct", "drop", "each", "else", "end", "escape",
"except", "exists", "for", "foreign", "from", "full", "group", "having",
"ignore", "immediate", "in", "initially", "inner", "insert", "intersect",
"into", "is", "isnull", "join", "key", "left", "like", "limit", "match",
"natural", "no", "not", "notnull", "null", "of", "offset", "on", "or", "order",
"outer", "primary", "references", "release", "restrict", "right", "rollback",
"row", "savepoint", "select", "set", "table", "temporary", "then", "to",
"transaction", "trigger", "union", "unique", "update", "using", "values",
"view", "when", "where",

"absolute", "admin", "aggregate", "alias", "allocate", "analyse", "any", "are",
"array", "asensitive", "assertion", "asymmetric", "at", "atomic",
"authorization", "avg", "bigint", "binary", "bit", "bit_length", "blob",
"boolean", "both", "breadth", "call", "called", "cardinality", "cascaded",
"catalog", "ceil", "ceiling", "char", "character", "character_length",
"char_length", "class", "clob", "close", "coalesce", "collation", "collect",
"completion", "condition", "connect", "connection", "constraints",
"constructor", "continue", "convert", "corr", "corresponding", "count",
"covar_pop", "covar_samp", "cube", "cume_dist", "current",
"current_default_transform_group", "current_path", "current_role",
"current_transform_group_for_type", "current_user", "cursor", "cycle", "data",
"date", "day", "deallocate", "dec", "decimal", "declare", "dense_rank",
"depth", "deref", "describe", "descriptor", "destroy", "destructor",
"deterministic", "diagnostics", "dictionary", "disconnect", "do", "domain",
"double", "dynamic", "element", "end-exec", "equals", "every", "exception",
"exec", "execute", "exp", "external", "extract", "false", "fetch", "filter",
"first", "float", "floor", "found", "free", "freeze", "function", "fusion",
"general", "get", "global", "go", "goto", "grant", "grouping", "hold", "host",
"hour", "identity", "ilike", "indicator", "initialize", "inout", "input",
"insensitive", "int", "integer", "intersection", "interval", "isolation",
"iterate", "language", "large", "last", "lateral", "leading", "less", "level",
"ln", "local", "localtime", "localtimestamp", "locator", "lower", "map", "max",
"member", "merge", "method", "min", "minute", "mod", "modifies", "modify",
"module", "month", "multiset", "names", "national", "nchar", "nclob", "new",
"next", "none", "normalize", "nullif", "numeric", "object", "octet_length",
"off", "old", "only", "open", "operation", "option", "ordinality", "out",
"output", "over", "overlaps", "overlay", "pad", "parameter", "parameters",
"partial", "partition", "path", "percentile_cont", "percentile_disc",
"percent_rank", "placing", "position", "postfix", "power", "precision",
"prefix", "preorder", "prepare", "preserve", "prior", "privileges",
"procedure", "public", "range", "rank", "read", "reads", "real", "recursive",
"ref", "referencing", "regr_avgx", "regr_avgy", "regr_count", "regr_intercept",
"regr_r2", "regr_slope", "regr_sxx", "regr_sxy", "regr_syy", "relative",
"result", "return", "returning", "returns", "revoke", "role", "rollup",
"routine", "rows", "row_number", "schema", "scope", "scroll", "search",
"second", "section", "sensitive", "sequence", "session", "session_user",
"sets", "similar", "size", "smallint", "some", "space", "specific",
"specifictype", "sql", "sqlcode", "sqlerror", "sqlexception", "sqlstate",
"sqlwarning", "sqrt", "start", "state", "statement", "static", "stddev_pop",
"stddev_samp", "structure", "submultiset", "substring", "sum", "symmetric",
"system", "system_user", "tablesample", "terminate", "than", "time",
"timestamp", "timezone_hour", "timezone_minute", "trailing", "translate",
"translation", "treat", "trim", "true", "uescape", "under", "unknown",
"unnest", "upper", "usage", "user", "value", "varchar", "variable", "varying",
"var_pop", "var_samp", "verbose", "whenever", "width_bucket", "window", "with",
"within", "without", "work", "write", "xml", "xmlagg", "xmlattributes",
"xmlbinary", "xmlcomment", "xmlconcat", "xmlelement", "xmlforest",
"absolute", "admin", "aggregate", "alias", "allocate", "analyse", "any", "are",
"array", "asensitive", "assertion", "asymmetric", "at", "atomic",
"authorization", "avg", "bigint", "binary", "bit", "bit_length", "blob",
"boolean", "both", "breadth", "call", "called", "cardinality", "cascaded",
"catalog", "ceil", "ceiling", "char", "character", "character_length",
"char_length", "class", "clob", "close", "coalesce", "collation", "collect",
"completion", "condition", "connect", "connection", "constraints",
"constructor", "continue", "convert", "corr", "corresponding", "count",
"covar_pop", "covar_samp", "cube", "cume_dist", "current",
"current_default_transform_group", "current_path", "current_role",
"current_transform_group_for_type", "current_user", "cursor", "cycle", "data",
"date", "day", "deallocate", "dec", "decimal", "declare", "dense_rank",
"depth", "deref", "describe", "descriptor", "destroy", "destructor",
"deterministic", "diagnostics", "dictionary", "disconnect", "do", "domain",
"double", "dynamic", "element", "end-exec", "equals", "every", "exception",
"exec", "execute", "exp", "external", "extract", "false", "fetch", "filter",
"first", "float", "floor", "found", "free", "freeze", "function", "fusion",
"general", "get", "global", "go", "goto", "grant", "grouping", "hold", "host",
"hour", "identity", "ilike", "indicator", "initialize", "inout", "input",
"insensitive", "int", "integer", "intersection", "interval", "isolation",
"iterate", "language", "large", "last", "lateral", "leading", "less", "level",
"ln", "local", "localtime", "localtimestamp", "locator", "lower", "map", "max",
"member", "merge", "method", "min", "minute", "mod", "modifies", "modify",
"module", "month", "multiset", "names", "national", "nchar", "nclob", "new",
"next", "none", "normalize", "nullif", "numeric", "object", "octet_length",
"off", "old", "only", "open", "operation", "option", "ordinality", "out",
"output", "over", "overlaps", "overlay", "pad", "parameter", "parameters",
"partial", "partition", "path", "percentile_cont", "percentile_disc",
"percent_rank", "placing", "position", "postfix", "power", "precision",
"prefix", "preorder", "prepare", "preserve", "prior", "privileges",
"procedure", "public", "range", "rank", "read", "reads", "real", "recursive",
"ref", "referencing", "regr_avgx", "regr_avgy", "regr_count", "regr_intercept",
"regr_r2", "regr_slope", "regr_sxx", "regr_sxy", "regr_syy", "relative",
"result", "return", "returning", "returns", "revoke", "role", "rollup",
"routine", "rows", "row_number", "schema", "scope", "scroll", "search",
"second", "section", "sensitive", "sequence", "session", "session_user",
"sets", "similar", "size", "smallint", "some", "space", "specific",
"specifictype", "sql", "sqlcode", "sqlerror", "sqlexception", "sqlstate",
"sqlwarning", "sqrt", "start", "state", "statement", "static", "stddev_pop",
"stddev_samp", "structure", "submultiset", "substring", "sum", "symmetric",
"system", "system_user", "tablesample", "terminate", "than", "time",
"timestamp", "timezone_hour", "timezone_minute", "trailing", "translate",
"translation", "treat", "trim", "true", "uescape", "under", "unknown",
"unnest", "upper", "usage", "user", "value", "varchar", "variable", "varying",
"var_pop", "var_samp", "verbose", "whenever", "width_bucket", "window", "with",
"within", "without", "work", "write", "xml", "xmlagg", "xmlattributes",
"xmlbinary", "xmlcomment", "xmlconcat", "xmlelement", "xmlforest",
"xmlnamespaces", "xmlparse", "xmlpi", "xmlroot", "xmlserialize", "year", "zone"
]
postgis_keywords = []

# functions
functions = [
# TODO get them from a reference page
"abs", "changes", "coalesce", "glob", "ifnull", "hex", "last_insert_rowid",
"length", "like", "lower", "ltrim", "max", "min", "nullif", "quote", "random",
"randomblob", "replace", "round", "rtrim", "soundex", "total_change", "trim",
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
"abs", "changes", "coalesce", "glob", "ifnull", "hex", "last_insert_rowid",
"length", "like", "lower", "ltrim", "max", "min", "nullif", "quote", "random",
"randomblob", "replace", "round", "rtrim", "soundex", "total_change", "trim",
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
"avg", "count", "group_concat", "sum", "total"
]
postgis_functions = [ # from http://www.postgis.org/docs/reference.html
Expand Down
70 changes: 35 additions & 35 deletions python/plugins/db_manager/db_plugins/spatialite/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def __init__(self, uri):

def _connectionInfo(self):
return unicode(self.dbname)

def _checkSpatial(self):
""" check if it's a valid spatialite db """
self.has_spatial = self._checkGeometryColumnsTable()
Expand Down Expand Up @@ -80,7 +80,7 @@ def _checkRastersTable(self):
self._execute(c, sql)
ret = c.fetchone()
return ret and ret[0]

def getInfo(self):
c = self._get_cursor()
self._execute(c, u"SELECT sqlite_version()")
Expand Down Expand Up @@ -134,11 +134,11 @@ def getTables(self, schema=None):
tablenames = []
items = []

sys_tables = [ "geom_cols_ref_sys", "geometry_columns", "geometry_columns_auth",
"views_geometry_columns", "virts_geometry_columns", "spatial_ref_sys",
"sqlite_sequence", #"tableprefix_metadata", "tableprefix_rasters",
"layer_params","layer_statistics", "layer_sub_classes", "layer_table_layout",
"pattern_bitmaps","symbol_bitmaps", "project_defs", "raster_pyramids",
sys_tables = [ "geom_cols_ref_sys", "geometry_columns", "geometry_columns_auth",
"views_geometry_columns", "virts_geometry_columns", "spatial_ref_sys",
"sqlite_sequence", #"tableprefix_metadata", "tableprefix_rasters",
"layer_params","layer_statistics", "layer_sub_classes", "layer_table_layout",
"pattern_bitmaps","symbol_bitmaps", "project_defs", "raster_pyramids",
"sqlite_stat1", "sqlite_stat2", "spatialite_history" ]

try:
Expand Down Expand Up @@ -166,14 +166,14 @@ def getTables(self, schema=None):
if self.has_geometry_columns:
# get the R*Tree tables
sql = u"SELECT f_table_name, f_geometry_column FROM geometry_columns WHERE spatial_index_enabled = 1"
self._execute(c, sql)
self._execute(c, sql)
for idx_item in c.fetchall():
sys_tables.append( 'idx_%s_%s' % idx_item )
sys_tables.append( 'idx_%s_%s_node' % idx_item )
sys_tables.append( 'idx_%s_%s_parent' % idx_item )
sys_tables.append( 'idx_%s_%s_rowid' % idx_item )


sql = u"SELECT name, type = 'view' FROM sqlite_master WHERE type IN ('table', 'view')"
self._execute(c, sql)

Expand All @@ -196,20 +196,20 @@ def getVectorTables(self, schema=None):
geometry_column:
f_table_name (the table name in geometry_columns may be in a wrong case, use this to load the layer)
f_geometry_column
type
coord_dimension
type
coord_dimension
srid
"""

if not self.has_geometry_columns:
return []

c = self._get_cursor()

# get geometry info from geometry_columns if exists
sql = u"""SELECT m.name, m.type = 'view', g.f_table_name, g.f_geometry_column, g.type, g.coord_dimension, g.srid
sql = u"""SELECT m.name, m.type = 'view', g.f_table_name, g.f_geometry_column, g.type, g.coord_dimension, g.srid
FROM sqlite_master AS m JOIN geometry_columns AS g ON upper(m.name) = upper(g.f_table_name)
WHERE m.type in ('table', 'view')
WHERE m.type in ('table', 'view')
ORDER BY m.name, g.f_geometry_column"""

self._execute(c, sql)
Expand All @@ -233,14 +233,14 @@ def getRasterTables(self, schema=None):
r.geometry_column
srid
"""

if not self.has_geometry_columns:
return []
if not self.has_raster:
return []

c = self._get_cursor()

# get geometry info from geometry_columns if exists
sql = u"""SELECT r.table_name||'_rasters', m.type = 'view', r.table_name, r.geometry_column, g.srid
FROM sqlite_master AS m JOIN geometry_columns AS g ON upper(m.name) = upper(g.f_table_name)
Expand All @@ -255,7 +255,7 @@ def getRasterTables(self, schema=None):
item = list(tbl)
item.insert(0, Table.RasterType)
items.append( item )

return items

def getTableRowCount(self, table):
Expand Down Expand Up @@ -317,11 +317,11 @@ def getTableExtent(self, table, geom):
tablename = QString(tablename).replace('_rasters', '_metadata')
geom = u'geometry'

sql = u"""SELECT Min(MbrMinX(%(geom)s)), Min(MbrMinY(%(geom)s)), Max(MbrMaxX(%(geom)s)), Max(MbrMaxY(%(geom)s))
sql = u"""SELECT Min(MbrMinX(%(geom)s)), Min(MbrMinY(%(geom)s)), Max(MbrMaxX(%(geom)s)), Max(MbrMaxY(%(geom)s))
FROM %(table)s """ % { 'geom' : self.quoteId(geom), 'table' : self.quoteId(tablename) }
self._execute(c, sql)
return c.fetchone()

def getViewDefinition(self, view):
""" returns definition of the view """
schema, tablename = self.getSchemaTableName(view)
Expand Down Expand Up @@ -351,8 +351,8 @@ def isRasterTable(self, table):
if not QString(tablename).endsWith( "_rasters" ):
return False

sql = u"""SELECT count(*)
FROM layer_params AS r JOIN geometry_columns AS g
sql = u"""SELECT count(*)
FROM layer_params AS r JOIN geometry_columns AS g
ON upper(r.table_name||'_metadata') = upper(g.f_table_name)
WHERE upper(r.table_name) = upper(REPLACE(%s, '_rasters', ''))""" % self.quoteString(tablename)
c = self._execute(None, sql)
Expand Down Expand Up @@ -400,7 +400,7 @@ def emptyTable(self, table):

sql = u"DELETE FROM %s" % self.quoteId(table)
self._execute_and_commit(sql)

def renameTable(self, table, new_table):
""" rename a table """
schema, tablename = self.getSchemaTableName(table)
Expand All @@ -414,7 +414,7 @@ def renameTable(self, table, new_table):

sql = u"ALTER TABLE %s RENAME TO %s" % (self.quoteId(table), self.quoteId(new_table))
self._execute(c, sql)

# update geometry_columns
if self.has_geometry_columns:
sql = u"UPDATE geometry_columns SET f_table_name = %s WHERE upper(f_table_name) = upper(%s)" % (self.quoteString(new_table), self.quoteString(tablename))
Expand All @@ -424,15 +424,15 @@ def renameTable(self, table, new_table):

def moveTable(self, table, new_table, new_schema=None):
return self.renameTable(table, new_table)

def createView(self, view, query):
sql = u"CREATE VIEW %s AS %s" % (self.quoteId(view), query)
self._execute_and_commit(sql)

def deleteView(self, view):
sql = u"DROP VIEW %s" % self.quoteId(view)
self._execute_and_commit(sql)

def renameView(self, view, new_name):
""" rename view """
return self.renameTable(view, new_name)
Expand All @@ -447,7 +447,7 @@ def addTableColumn(self, table, field_def):
""" add a column to table """
sql = u"ALTER TABLE %s ADD %s" % (self.quoteId(table), field_def)
self._execute_and_commit(sql)

def deleteTableColumn(self, table, column):
""" delete column from a table """
if not self.isGeometryColumn(table, column):
Expand All @@ -457,7 +457,7 @@ def deleteTableColumn(self, table, column):
schema, tablename = self.getSchemaTableName(table)
sql = u"SELECT DiscardGeometryColumn(%s, %s)" % (self.quoteString(tablename), self.quoteString(column))
self._execute_and_commit(sql)

def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None):
return False # column editing not supported

Expand All @@ -468,11 +468,11 @@ def renameTableColumn(self, table, column, new_name):
def setColumnType(self, table, column, data_type):
""" change column type """
return False # column editing not supported

def setColumnDefault(self, table, column, default):
""" change column's default value. If default=None drop default value """
return False # column editing not supported

def setColumnNull(self, table, column, is_null):
""" change whether column can contain null values """
return False # column editing not supported
Expand Down Expand Up @@ -513,7 +513,7 @@ def createTableIndex(self, table, name, column, unique=False):
unique_str = u"UNIQUE" if unique else ""
sql = u"CREATE %s INDEX %s ON %s (%s)" % (unique_str, self.quoteId(name), self.quoteId(table), self.quoteId(column))
self._execute_and_commit(sql)

def deleteTableIndex(self, table, name):
schema, tablename = self.getSchemaTableName(table)
sql = u"DROP INDEX %s" % self.quoteId( (schema, name) )
Expand All @@ -526,7 +526,7 @@ def createSpatialIndex(self, table, geom_column='geometry'):
schema, tablename = self.getSchemaTableName(table)
sql = u"SELECT CreateSpatialIndex(%s, %s)" % (self.quoteString(tablename), self.quoteString(geom_column))
self._execute_and_commit(sql)

def deleteSpatialIndex(self, table, geom_column='geometry'):
if self.isRasterTable( table ):
return False
Expand Down Expand Up @@ -554,15 +554,15 @@ def hasSpatialIndex(self, table, geom_column='geometry'):


def execution_error_types(self):
return sqlite.Error, sqlite.ProgrammingError
return sqlite.Error, sqlite.ProgrammingError, sqlite.Warning

def connection_error_types(self):
return sqlite.InterfaceError, sqlite.OperationalError

# moved into the parent class: DbConnector._execute()
#def _execute(self, cursor, sql):
# pass

# moved into the parent class: DbConnector._execute_and_commit()
#def _execute_and_commit(self, sql):
# pass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __init__(self, table, parent=None):

fields_txt = u", ".join(self.fields)
table_txt = self.db.quoteId( (self.table.schemaName(), self.table.name) )

# run query and get results
sql = u"SELECT %s FROM %s" % (fields_txt, table_txt)
c = self.db._get_cursor()
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/db_manager/db_plugins/spatialite/info_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def __init__(self, db):
self.db = db

def connectionDetails(self):
tbl = [
("Filename:", self.db.connector.dbname)
tbl = [
("Filename:", self.db.connector.dbname)
]
return HtmlTable( tbl )

Expand Down
8 changes: 4 additions & 4 deletions python/plugins/db_manager/db_plugins/spatialite/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,10 @@ def uri(self):
uri.setDataSource('', self.geomTableName, self.geomColumn)
return uri

def hasSpatialIndex(self, geom_column=None):
def hasSpatialIndex(self, geom_column=None):
geom_column = geom_column if geom_column != None else self.geomColumn
return self.database().connector.hasSpatialIndex( (self.schemaName(), self.name), geom_column )

def createSpatialIndex(self, geom_column=None):
self.aboutToChange()
ret = VectorTable.createSpatialIndex(self, geom_column)
Expand Down Expand Up @@ -222,9 +222,9 @@ def gdalUri(self):
def mimeUri(self):
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
return QString( uri )

def toMapLayer(self):
from qgis.core import QgsRasterLayer
from qgis.core import QgsRasterLayer
rl = QgsRasterLayer(self.gdalUri(), self.name)
if rl.isValid():
rl.setContrastEnhancementAlgorithm("StretchToMinimumMaximum")
Expand Down
38 changes: 19 additions & 19 deletions python/plugins/db_manager/db_plugins/spatialite/sql_dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,34 @@
# keywords
keywords = [
# TODO get them from a reference page
"action", "add", "after", "all", "alter", "analyze", "and", "as", "asc",
"before", "begin", "between", "by", "cascade", "case", "cast", "check",
"collate", "column", "commit", "constraint", "create", "cross", "current_date",
"current_time", "current_timestamp", "default", "deferrable", "deferred",
"delete", "desc", "distinct", "drop", "each", "else", "end", "escape",
"except", "exists", "for", "foreign", "from", "full", "group", "having",
"ignore", "immediate", "in", "initially", "inner", "insert", "intersect",
"into", "is", "isnull", "join", "key", "left", "like", "limit", "match",
"natural", "no", "not", "notnull", "null", "of", "offset", "on", "or", "order",
"outer", "primary", "references", "release", "restrict", "right", "rollback",
"row", "savepoint", "select", "set", "table", "temporary", "then", "to",
"transaction", "trigger", "union", "unique", "update", "using", "values",
"action", "add", "after", "all", "alter", "analyze", "and", "as", "asc",
"before", "begin", "between", "by", "cascade", "case", "cast", "check",
"collate", "column", "commit", "constraint", "create", "cross", "current_date",
"current_time", "current_timestamp", "default", "deferrable", "deferred",
"delete", "desc", "distinct", "drop", "each", "else", "end", "escape",
"except", "exists", "for", "foreign", "from", "full", "group", "having",
"ignore", "immediate", "in", "initially", "inner", "insert", "intersect",
"into", "is", "isnull", "join", "key", "left", "like", "limit", "match",
"natural", "no", "not", "notnull", "null", "of", "offset", "on", "or", "order",
"outer", "primary", "references", "release", "restrict", "right", "rollback",
"row", "savepoint", "select", "set", "table", "temporary", "then", "to",
"transaction", "trigger", "union", "unique", "update", "using", "values",
"view", "when", "where",

"abort", "attach", "autoincrement", "conflict", "database", "detach",
"exclusive", "explain", "fail", "glob", "if", "index", "indexed", "instead",
"plan", "pragma", "query", "raise", "regexp", "reindex", "rename", "replace",
"abort", "attach", "autoincrement", "conflict", "database", "detach",
"exclusive", "explain", "fail", "glob", "if", "index", "indexed", "instead",
"plan", "pragma", "query", "raise", "regexp", "reindex", "rename", "replace",
"temp", "vacuum", "virtual"
]
spatialite_keywords = []

# functions
functions = [
# TODO get them from a reference page
"abs", "changes", "coalesce", "glob", "ifnull", "hex", "last_insert_rowid",
"length", "like", "lower", "ltrim", "max", "min", "nullif", "quote", "random",
"randomblob", "replace", "round", "rtrim", "soundex", "total_change", "trim",
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
"abs", "changes", "coalesce", "glob", "ifnull", "hex", "last_insert_rowid",
"length", "like", "lower", "ltrim", "max", "min", "nullif", "quote", "random",
"randomblob", "replace", "round", "rtrim", "soundex", "total_change", "trim",
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
"avg", "count", "group_concat", "sum", "total"
]
spatialite_functions = [ # from www.gaia-gis.it/spatialite-2.3.0/spatialite-sql-2.3.0.html
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def currentTable(self):
if isinstance(item, Table):
return item
return None


def itemChanged(self, index):
self.setCurrentIndex(index)
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/db_manager/dlg_add_geometry_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -29,9 +29,9 @@
from .dlg_db_error import DlgDbError
from .db_plugins.plugin import TableField

from .ui.ui_DlgAddGeometryColumn import Ui_DlgAddGeometryColumn
from .ui.ui_DlgAddGeometryColumn import Ui_DbManagerDlgAddGeometryColumn as Ui_Dialog

class DlgAddGeometryColumn(QDialog, Ui_DlgAddGeometryColumn):
class DlgAddGeometryColumn(QDialog, Ui_Dialog):

GEOM_TYPES = ["POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION"]

Expand Down
13 changes: 6 additions & 7 deletions python/plugins/db_manager/dlg_create_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -29,24 +29,23 @@
from .dlg_db_error import DlgDbError
from .db_plugins.plugin import TableConstraint

from .ui.ui_DlgCreateConstraint import Ui_DlgCreateConstraint
from .ui.ui_DlgCreateConstraint import Ui_DbManagerDlgCreateConstraint as Ui_Dialog

class DlgCreateConstraint(QDialog, Ui_DlgCreateConstraint):

class DlgCreateConstraint(QDialog, Ui_Dialog):
def __init__(self, parent=None, table=None, db=None):
QDialog.__init__(self, parent)
self.table = table
self.db = self.table.database() if self.table and self.table.database() else db
self.setupUi(self)

self.connect(self.buttonBox, SIGNAL("accepted()"), self.createConstraint)
self.populateColumns()

def populateColumns(self):
self.cboColumn.clear()
for fld in self.table.fields():
self.cboColumn.addItem(fld.name)


def createConstraint(self):
constr = self.getConstraint()
Expand Down
18 changes: 8 additions & 10 deletions python/plugins/db_manager/dlg_create_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -29,19 +29,17 @@
from .dlg_db_error import DlgDbError
from .db_plugins.plugin import TableIndex

from .ui.ui_DlgCreateIndex import Ui_DlgCreateIndex
from .ui.ui_DlgCreateIndex import Ui_DbManagerDlgCreateIndex as Ui_Dialog


class DlgCreateIndex(QDialog, Ui_DlgCreateIndex):

class DlgCreateIndex(QDialog, Ui_Dialog):
def __init__(self, parent=None, table=None, db=None):
QDialog.__init__(self, parent)
self.table = table
self.db = self.table.database() if self.table and self.table.database() else db
self.setupUi(self)

self.connect(self.buttonBox, SIGNAL("accepted()"), self.createIndex)

self.connect(self.cboColumn, SIGNAL("currentIndexChanged(int)"), self.columnChanged)
self.populateColumns()

Expand All @@ -50,17 +48,17 @@ def populateColumns(self):
self.cboColumn.clear()
for fld in self.table.fields():
self.cboColumn.addItem(fld.name)

def columnChanged(self):
self.editName.setText(u"idx_%s_%s" % (self.table.name, self.cboColumn.currentText()))


def createIndex(self):
idx = self.getIndex()
if idx.name == "":
QMessageBox.critical(self, "error", "Please enter some name for the index")
return

# now create the index
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
Expand Down
83 changes: 41 additions & 42 deletions python/plugins/db_manager/dlg_create_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -29,16 +29,16 @@
from .db_plugins.plugin import DbError, ConnectionError
from .dlg_db_error import DlgDbError

from .ui.ui_DlgCreateTable import Ui_DlgCreateTable
from .ui.ui_DlgCreateTable import Ui_DbManagerDlgCreateTable as Ui_Dialog


class TableFieldsDelegate(QItemDelegate):
""" delegate with some special item editors """

def __init__(self, field_types, parent=None):
QItemDelegate.__init__(self, parent)
self.fieldTypes = field_types

def createEditor(self, parent, option, index):
# special combobox for field type
if index.column() == 1:
Expand All @@ -52,7 +52,7 @@ def createEditor(self, parent, option, index):
elif index.column() == 2:
return QCheckBox(parent)
return QItemDelegate.createEditor(self, parent, option, index)

def setEditorData(self, editor, index):
""" load data from model to editor """
m = index.model()
Expand All @@ -65,7 +65,7 @@ def setEditorData(self, editor, index):
else:
# use default
QItemDelegate.setEditorData(self, editor, index)

def setModelData(self, editor, model, index):
""" save data from editor back to model """
if index.column() == 1:
Expand All @@ -79,8 +79,7 @@ def setModelData(self, editor, model, index):
self.emit(SIGNAL("columnNameChanged()"))


class DlgCreateTable(QDialog, Ui_DlgCreateTable):

class DlgCreateTable(QDialog, Ui_Dialog):
GEOM_TYPES = ["POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION"]

def __init__(self, item, parent=None):
Expand All @@ -96,14 +95,14 @@ def __init__(self, item, parent=None):
m = TableFieldsModel(self, True) # it's editable
self.fields.setModel(m)
self.fields.setColumnHidden(3, True) # hide Default column

d = TableFieldsDelegate(self.fieldTypes, self)
self.fields.setItemDelegate(d)

self.fields.setColumnWidth(0,140)
self.fields.setColumnWidth(1,140)
self.fields.setColumnWidth(2,50)

b = QPushButton("&Create")
self.buttonBox.addButton(b, QDialogButtonBox.ActionRole)

Expand All @@ -112,17 +111,17 @@ def __init__(self, item, parent=None):
self.connect(self.btnFieldUp, SIGNAL("clicked()"), self.fieldUp)
self.connect(self.btnFieldDown, SIGNAL("clicked()"), self.fieldDown)
self.connect(b, SIGNAL("clicked()"), self.createTable)

self.connect(self.chkGeomColumn, SIGNAL("clicked()"), self.updateUi)

self.connect(self.fields.selectionModel(), SIGNAL("selectionChanged(const QItemSelection &, const QItemSelection &)"), self.updateUiFields)
self.connect(d, SIGNAL("columnNameChanged()"), self.updatePkeyCombo)

self.populateSchemas()
self.populateSchemas()
self.updateUi()
self.updateUiFields()


def populateSchemas(self):
self.cboSchema.clear()
if not self.hasSchemas:
Expand All @@ -139,15 +138,15 @@ def populateSchemas(self):
def hideSchemas(self):
self.cboSchema.setEnabled(False)


def updateUi(self):
useGeom = self.chkGeomColumn.isChecked()
self.cboGeomType.setEnabled(useGeom)
self.editGeomColumn.setEnabled(useGeom)
self.spinGeomDim.setEnabled(useGeom)
self.editGeomSrid.setEnabled(useGeom)
self.chkSpatialIndex.setEnabled(useGeom)

def updateUiFields(self):
fld = self.selectedField()
if fld is not None:
Expand All @@ -159,32 +158,32 @@ def updateUiFields(self):
self.btnFieldUp.setEnabled(up_enabled)
self.btnFieldDown.setEnabled(down_enabled)
self.btnDeleteField.setEnabled(del_enabled)

def updatePkeyCombo(self, selRow=None):
""" called when list of columns changes. if 'sel' is None, it keeps current index """

if selRow is None:
selRow = self.cboPrimaryKey.currentIndex()

self.cboPrimaryKey.clear()

m = self.fields.model()
for row in xrange(m.rowCount()):
name = m.data(m.index(row,0)).toString()
self.cboPrimaryKey.addItem(name)

self.cboPrimaryKey.setCurrentIndex(selRow)

def addField(self):
""" add new field to the end of field table """
m = self.fields.model()
newRow = m.rowCount()
m.insertRows(newRow,1)

indexName = m.index(newRow,0,QModelIndex())
indexType = m.index(newRow,1,QModelIndex())
indexNull = m.index(newRow,2,QModelIndex())

m.setData(indexName, QVariant("new_field"))
colType = self.fieldTypes[0]
if newRow == 0:
Expand All @@ -193,32 +192,32 @@ def addField(self):
colType = "serial"
m.setData(indexType, QVariant(colType))
m.setData(indexNull, QVariant(False))

# selects the new row
sel = self.fields.selectionModel()
sel.select(indexName, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect)

# starts editing
self.fields.edit(indexName)

self.updatePkeyCombo(0 if newRow == 0 else None)

def selectedField(self):
sel = self.fields.selectedIndexes()
if len(sel) < 1:
return None
return sel[0].row()

def deleteField(self):
""" delete selected field """
row = self.selectedField()
if row is None:
QMessageBox.information(self, "sorry", "no field selected")
else:
self.fields.model().removeRows(row,1)

self.updatePkeyCombo()

def fieldUp(self):
""" move selected field up """
row = self.selectedField()
Expand All @@ -228,17 +227,17 @@ def fieldUp(self):
if row == 0:
QMessageBox.information(self, "sorry", "field is at top 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 fieldDown(self):
""" move selected field down """
row = self.selectedField()
Expand All @@ -248,17 +247,17 @@ def fieldDown(self):
if row == self.fields.model().rowCount()-1:
QMessageBox.information(self, "sorry", "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 createTable(self):
""" create table with chosen fields, optionally add a geometry column """
if not self.hasSchemas:
Expand All @@ -268,17 +267,17 @@ def createTable(self):
if len(schema) == 0:
QMessageBox.information(self, "sorry", "select schema!")
return

table = unicode(self.editName.text())
if len(table) == 0:
QMessageBox.information(self, "sorry", "enter table name!")
return

m = self.fields.model()
if m.rowCount() == 0:
QMessageBox.information(self, "sorry", "add some fields!")
return

useGeomColumn = self.chkGeomColumn.isChecked()
if useGeomColumn:
geomColumn = unicode(self.editGeomColumn.text())
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/db_manager/dlg_db_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -25,10 +25,10 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from .ui.ui_DlgDbError import Ui_DlgDbError
from .ui.ui_DlgDbError import Ui_DbManagerDlgDbError as Ui_Dialog
from .db_plugins.plugin import DbError

class DlgDbError(QDialog, Ui_DlgDbError):
class DlgDbError(QDialog, Ui_Dialog):
def __init__(self, e, parent=None):
QDialog.__init__(self, parent)
self.setupUi(self)
Expand Down
10 changes: 5 additions & 5 deletions python/plugins/db_manager/dlg_export_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
import qgis.core
from qgis.utils import iface

from .ui.ui_DlgExportVector import Ui_DlgExportVector
from .ui.ui_DlgExportVector import Ui_DbManagerDlgExportVector as Ui_Dialog

class DlgExportVector(QDialog, Ui_DlgExportVector):
class DlgExportVector(QDialog, Ui_Dialog):

def __init__(self, inLayer, inDb, parent=None):
QDialog.__init__(self, parent)
Expand Down Expand Up @@ -58,7 +58,7 @@ def checkSupports(self):
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)
#self.chkSpatialIndex.setEnabled(allowSpatial and hasGeomType)


def chooseOutputFile(self):
Expand Down Expand Up @@ -158,8 +158,8 @@ def accept(self):
return

# create spatial index
if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked():
self.db.connector.createSpatialIndex( (schema, table), geom )
#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)
Expand Down
9 changes: 4 additions & 5 deletions python/plugins/db_manager/dlg_field_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,16 @@

from .db_plugins.plugin import TableField

from .ui.ui_DlgFieldProperties import Ui_DlgFieldProperties
from .ui.ui_DlgFieldProperties import Ui_DbManagerDlgFieldProperties as Ui_Dialog

class DlgFieldProperties(QDialog, Ui_DlgFieldProperties):

class DlgFieldProperties(QDialog, Ui_Dialog):
def __init__(self, parent=None, fld=None, table=None, db=None):
QDialog.__init__(self, parent)
self.fld = fld
self.table = self.fld.table() if self.fld and self.fld.table() else table
self.db = self.table.database() if self.table and self.table.database() else db
self.setupUi(self)

for item in self.db.connector.fieldTypes():
self.cboType.addItem(item)
self.setField(self.fld)
Expand Down Expand Up @@ -78,6 +77,6 @@ def onOK(self):
if fld.dataType == "":
QMessageBox.critical(self, "sorry", "field type must not be empty")
return

self.accept()

24 changes: 12 additions & 12 deletions python/plugins/db_manager/dlg_import_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -28,11 +28,11 @@
import qgis.core
from qgis.utils import iface

from .ui.ui_DlgImportVector import Ui_DlgImportVector
from .ui.ui_DlgImportVector import Ui_DbManagerDlgImportVector as Ui_Dialog

class DlgImportVector(QDialog, Ui_DlgImportVector):
class DlgImportVector(QDialog, Ui_Dialog):

HAS_INPUT_MODE, ASK_FOR_INPUT_MODE = range(2)
HAS_INPUT_MODE, ASK_FOR_INPUT_MODE = range(2)

def __init__(self, inLayer, outDb, outUri, parent=None):
QDialog.__init__(self, parent)
Expand Down Expand Up @@ -106,7 +106,7 @@ def populateLayers(self):
self.cboInputLayer.addItem( layer.name(), index )

def deleteInputLayer(self):
""" destroy the input layer instance, but only if it was
""" destroy the input layer instance, but only if it was
created from this dialog """
if self.mode == self.ASK_FOR_INPUT_MODE and self.inLayer:
self.inLayer.deleteLater()
Expand Down Expand Up @@ -173,7 +173,7 @@ def updateInputLayer(self):
def populateSchemas(self):
if not self.db:
return

self.cboSchema.clear()
schemas = self.db.schemas()
if schemas == None:
Expand All @@ -193,7 +193,7 @@ def hideSchemas(self):
def populateTables(self):
if not self.db:
return

currentText = self.cboTable.currentText()

schemas = self.db.schemas()
Expand All @@ -209,16 +209,16 @@ def populateTables(self):
self.cboTable.addItem(table.name)

self.cboTable.setEditText(currentText)

def populateEncodings(self):
encodings = ['ISO-8859-1', 'ISO-8859-2', 'UTF-8', 'CP1250']
for enc in encodings:
self.cboEncoding.addItem(enc)
self.cboEncoding.setCurrentIndex(2)

def accept(self):
if self.mode == self.ASK_FOR_INPUT_MODE:
# create the input layer (if not already done) and
# create the input layer (if not already done) and
# update available options w/o changing the tablename!
self.cboTable.blockSignals(True)
table = self.cboTable.currentText()
Expand Down Expand Up @@ -257,7 +257,7 @@ def accept(self):
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
# get pk and geom field names from the source layer or use the
# ones defined by the user
pk = self.outUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text()

Expand Down Expand Up @@ -322,7 +322,7 @@ def accept(self):


def closeEvent(self, event):
# destroy the input layer instance but only if it was created
# destroy the input layer instance but only if it was created
# from this dialog!
self.deleteInputLayer()
QDialog.closeEvent(self, event)
Expand Down
30 changes: 16 additions & 14 deletions python/plugins/db_manager/dlg_sql_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of this file is based on
The content of this file is based on
- PG_Manager by Martin Dobias (GPLv2 license)
***************************************************************************/
Expand All @@ -28,12 +28,12 @@
from .db_plugins.plugin import BaseError
from .dlg_db_error import DlgDbError

from .ui.ui_DlgSqlWindow import Ui_DlgSqlWindow
from .ui.ui_DlgSqlWindow import Ui_DbManagerDlgSqlWindow as Ui_Dialog

from .highlighter import SqlHighlighter
from .completer import SqlCompleter

class DlgSqlWindow(QDialog, Ui_DlgSqlWindow):
class DlgSqlWindow(QDialog, Ui_Dialog):

def __init__(self, iface, db, parent=None):
QDialog.__init__(self, parent)
Expand All @@ -56,7 +56,7 @@ def __init__(self, iface, db, parent=None):
self.viewResult.addAction( copyAction )
copyAction.setShortcuts(QKeySequence.Copy)
QObject.connect(copyAction, SIGNAL("triggered()"), self.copySelectedResults)

self.connect(self.btnExecute, SIGNAL("clicked()"), self.executeSql)
self.connect(self.btnClear, SIGNAL("clicked()"), self.clearSql)
self.connect(self.buttonBox.button(QDialogButtonBox.Close), SIGNAL("clicked()"), self.close)
Expand All @@ -76,17 +76,17 @@ def closeEvent(self, e):
""" save window state """
settings = QSettings()
settings.setValue("/DB_Manager/sqlWindow/geometry", QVariant(self.saveGeometry()))

QDialog.closeEvent(self, e)

def loadAsLayerToggled(self, checked):
self.loadAsLayerGroup.setChecked( checked )
self.loadAsLayerWidget.setVisible( checked )

def getSql(self):
# If the selection obtained from an editor spans a line break,
# the text will contain a Unicode U+2029 paragraph separator
# character instead of a newline \n character
# If the selection obtained from an editor spans a line break,
# the text will contain a Unicode U+2029 paragraph separator
# character instead of a newline \n character
# (see https://qt-project.org/doc/qt-4.8/qtextcursor.html#selectedText)
sql = self.editSql.textCursor().selectedText().replace(unichr(0x2029), "\n")
if sql.isEmpty():
Expand All @@ -104,7 +104,7 @@ def executeSql(self):

QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

# delete the old model
# delete the old model
old_model = self.viewResult.model()
self.viewResult.setModel(None)
if old_model: old_model.deleteLater()
Expand All @@ -113,7 +113,7 @@ def executeSql(self):
self.geomCombo.clear()

try:
# set the new model
# set the new model
model = self.db.sqlResultModel( sql, self )
self.viewResult.setModel( model )
self.lblResult.setText("%d rows, %.1f seconds" % (model.affectedRows(), model.secs()))
Expand Down Expand Up @@ -181,7 +181,7 @@ def fillColumnCombos(self):
aliasIndex = 0
while True:
alias = "_%s__%d" % ("subQuery", aliasIndex)
escaped = '\\b("?)' + QRegExp.escape(alias) + '\\1\\b'
escaped = '\\b("?)' + QRegExp.escape(alias) + '\\1\\b'
if not query.contains( QRegExp(escaped, Qt.CaseInsensitive) ):
break
aliasIndex += 1
Expand All @@ -191,18 +191,20 @@ def fillColumnCombos(self):
connector = self.db.connector
sql = u"SELECT * FROM (%s\n) AS %s LIMIT 0" % ( unicode(query), connector.quoteId(alias) )

c = None
try:
c = connector._execute(None, sql)
cols = connector._get_cursor_columns(c)

except BaseError, e:
except BaseError as e:
QApplication.restoreOverrideCursor()
DlgDbError.showError(e, self)
return

finally:
c.close()
del c
if c:
c.close()
del c

cols.sort()
self.uniqueCombo.addItems( cols )
Expand Down
Loading