Skip to content

Commit

Permalink
DBManager: updated to new SIP API
Browse files Browse the repository at this point in the history
  • Loading branch information
brushtyler committed Jun 4, 2013
1 parent edfa0fc commit 80b5a07
Show file tree
Hide file tree
Showing 17 changed files with 147 additions and 135 deletions.
18 changes: 9 additions & 9 deletions python/plugins/db_manager/completer.py
Expand Up @@ -37,10 +37,10 @@ def __init__(self, editor, db=None):
from .sql_dictionary import getSqlDictionary
dictionary = getSqlDictionary()

wordlist = QStringList()
wordlist = []
for name, value in dictionary.iteritems():
wordlist << value
wordlist = QStringList() << list(set( wordlist )) # remove duplicates
wordlist += value # concat lists
wordlist = list( set(wordlist) ) # remove duplicates

# setup the completer
QCompleter.__init__(self, sorted(wordlist), editor)
Expand Down Expand Up @@ -70,10 +70,10 @@ def setCompleter(self, completer):

def insertCompletion(self, completion):
tc = self.textCursor()
extra = completion.length() - self.completer.completionPrefix().length()
extra = len(completion) - len(self.completer.completionPrefix())
tc.movePosition(QTextCursor.Left)
tc.movePosition(QTextCursor.EndOfWord)
tc.insertText(completion.right(extra))
tc.insertText(completion[-extra:])
self.setTextCursor(tc)

def textUnderCursor(self):
Expand All @@ -99,18 +99,18 @@ def keyPressEvent(self, event):

# ctrl or shift key on it's own??
ctrlOrShift = event.modifiers() in (Qt.ControlModifier, Qt.ShiftModifier)
if ctrlOrShift and event.text().isEmpty():
if ctrlOrShift and event.text() == "":
# ctrl or shift key on it's own
return

eow = QString("~!@#$%^&*()+{}|:\"<>?,./;'[]\\-=") # end of word
eow = "~!@#$%^&*()+{}|:\"<>?,./;'[]\\-=" # end of word

hasModifier = event.modifiers() != Qt.NoModifier and not ctrlOrShift

completionPrefix = self.textUnderCursor()

if not isShortcut and (hasModifier or event.text().isEmpty() or
completionPrefix.length() < 3 or eow.contains(event.text().right(1))):
if not isShortcut and (hasModifier or event.text() == "" or
len(completionPrefix) < 3 or event.text()[-1] in eow):
self.completer.popup().hide()
return

Expand Down
12 changes: 6 additions & 6 deletions python/plugins/db_manager/db_manager.py
Expand Up @@ -45,8 +45,8 @@ def __init__(self, iface, parent=None):

# restore the window state
settings = QSettings()
self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry").toByteArray() )
self.restoreState( settings.value("/DB_Manager/mainWindow/windowState").toByteArray() )
self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry") )
self.restoreState( settings.value("/DB_Manager/mainWindow/windowState") )

self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged)
self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged)
Expand All @@ -58,8 +58,8 @@ def closeEvent(self, e):

# save the window state
settings = QSettings()
settings.setValue( "/DB_Manager/mainWindow/windowState", QVariant(self.saveState()) )
settings.setValue( "/DB_Manager/mainWindow/geometry", QVariant(self.saveGeometry()) )
settings.setValue( "/DB_Manager/mainWindow/windowState", self.saveState() )
settings.setValue( "/DB_Manager/mainWindow/geometry", self.saveGeometry() )

QMainWindow.closeEvent(self, e)

Expand Down Expand Up @@ -236,7 +236,7 @@ def registerAction(self, action, menuName, callback=None):
# get the placeholder's position to insert before it
pos = 0
for pos in range(len(menuActions)):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endsWith("_placeholder"):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
menuActions[pos].setVisible(True)
break

Expand Down Expand Up @@ -314,7 +314,7 @@ def unregisterAction(self, action, menuName):
# hide the placeholder if there're no other registered actions
if len(self._registeredDbActions[menuName]) <= 0:
for i in range(len(menuActions)):
if menuActions[i].isSeparator() and menuActions[i].objectName().endsWith("_placeholder"):
if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
menuActions[i].setVisible(False)
break

Expand Down
45 changes: 24 additions & 21 deletions python/plugins/db_manager/db_model.py
Expand Up @@ -92,9 +92,11 @@ def icon(self):
return None

def path(self):
pathList = QStringList()
if self.parent(): pathList << self.parent().path()
return pathList << self.data(0)
pathList = []
if self.parent():
pathList.append( self.parent().path() )
pathList.append( self.data(0) )
return pathList


class PluginItem(TreeItem):
Expand Down Expand Up @@ -122,7 +124,7 @@ def icon(self):
return self.getItemData().icon()

def path(self):
return QStringList() << self.getItemData().typeName()
return [ self.getItemData().typeName() ]

class ConnectionItem(TreeItem):
def __init__(self, connection, parent=None):
Expand Down Expand Up @@ -249,13 +251,14 @@ def icon(self):
return self.tableIcon

def path(self):
pathList = QStringList()
if self.parent(): pathList << self.parent().path()
pathList = []
if self.parent():
pathList.append( self.parent().path() )

if self.getItemData().type == Table.VectorType:
pathList << "%s::%s" % ( self.data(0), self.getItemData().geomColumn )
pathList.append( "%s::%s" % ( self.data(0), self.getItemData().geomColumn ) )
else:
pathList << self.data(0)
pathList.append( self.data(0) )

return pathList

Expand Down Expand Up @@ -330,17 +333,17 @@ def columnCount(self, parent):

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

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

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

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

def flags(self, index):
if not index.isValid():
Expand All @@ -367,8 +370,8 @@ def flags(self, index):

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole and section < len(self.header):
return QVariant(self.header[section])
return QVariant()
return self.header[section]
return None

def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
Expand Down Expand Up @@ -409,7 +412,7 @@ def setData(self, index, value, role):
return False

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

if isinstance(item, SchemaItem) or isinstance(item, TableItem):
obj = item.getItemData()
Expand Down Expand Up @@ -470,7 +473,7 @@ def _onDataChanged(self, indexFrom, indexTo=None):
QGIS_URI_MIME = "application/x-vnd.qgis.qgis.uri"

def mimeTypes(self):
return QStringList() << "text/uri-list" << self.QGIS_URI_MIME
return ["text/uri-list", self.QGIS_URI_MIME]

def mimeData(self, indexes):
mimeData = QMimeData()
Expand Down Expand Up @@ -502,7 +505,7 @@ def dropMimeData(self, data, action, row, column, parent):
if data.hasUrls():
for u in data.urls():
filename = u.toLocalFile()
if filename.isEmpty():
if filename == "":
continue

if qgis.core.QgsRasterLayer.isValidRasterFileName( filename ):
Expand All @@ -524,7 +527,7 @@ def dropMimeData(self, data, action, row, column, parent):
while not stream.atEnd():
mimeUri = stream.readQString()

parts = QStringList() << unicode(mimeUri).split(":", 3)
parts = mimeUri.split(":", 3)
if len(parts) != 4:
# invalid qgis mime uri
QMessageBox.warning(None, "Invalid MIME uri", "The dropped object is not a valid QGis layer")
Expand Down Expand Up @@ -570,8 +573,8 @@ def importLayer(self, layerType, providerKey, layerName, uriString, parent):

if inLayer.type() == inLayer.VectorLayer:
# create the output uri
schema = outSchema.name if outDb.schemas() != None and outSchema != None else QString()
pkCol = geomCol = QString()
schema = outSchema.name if outDb.schemas() != None and outSchema != None else ""
pkCol = geomCol = ""

# default pk and geom field name value
if providerKey in ['postgres', 'spatialite']:
Expand All @@ -580,7 +583,7 @@ def importLayer(self, layerType, providerKey, layerName, uriString, parent):
geomCol = inUri.geometryColumn()

outUri = outDb.uri()
outUri.setDataSource( schema, layerName, geomCol, QString(), pkCol )
outUri.setDataSource( schema, layerName, geomCol, "", pkCol )

self.emit( SIGNAL("importVector"), inLayer, outDb, outUri, toIndex )
return True
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_plugins/connector.py
Expand Up @@ -93,7 +93,7 @@ def _execute_and_commit(self, sql):
def _get_cursor(self, name=None):
try:
if name != None:
name = QString( unicode(name).encode('ascii', 'replace') ).replace( QRegExp("\W"), "_" ).toAscii()
name = unicode(name).encode('ascii', 'replace').replace( '?', "_" )
self._last_cursor_named_id = 0 if not hasattr(self, '_last_cursor_named_id') else self._last_cursor_named_id + 1
return self.connection.cursor( "%s_%d" % (name, self._last_cursor_named_id) )

Expand Down
70 changes: 35 additions & 35 deletions python/plugins/db_manager/db_plugins/data_model.py
Expand Up @@ -32,11 +32,11 @@ def __init__(self, header=None, data=None, parent=None):
self.resdata = data if data else []

def headerToString(self, sep=u"\t"):
header = QStringList() << self._header
return header.join( sep )
header = self._header
return sep.join(header)

def rowToString(self, row, sep=u"\t"):
text = QString()
text = u""
for col in range(self.columnCount()):
text += u"%s" % self.getData(row, col) + sep
return text[:-1]
Expand All @@ -55,37 +55,37 @@ def columnCount(self, parent=None):

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

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

if role == Qt.FontRole: # draw NULL in italic
if val != None:
return QVariant()
return None
f = QFont()
f.setItalic(True)
return QVariant(f)
return f

if val == None:
return QVariant("NULL")
return "NULL"
elif isinstance(val, buffer):
# hide binary data
return QVariant()
elif isinstance(val, (str, unicode, QString)) and len(val) > 300:
return None
elif isinstance(val, (str, unicode)) and len(val) > 300:
# too much data to display, elide the string
return QVariant( u"%s..." % val[:300] )
return QVariant( unicode(val) ) # convert to string
return u"%s..." % val[:300]
return unicode(val) # convert to string

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

if orientation == Qt.Vertical:
# header for a row
return QVariant(section+1)
return section+1
else:
# header for a column
return QVariant(self._header[section])
return self._header[section]


class TableDataModel(BaseTableModel):
Expand Down Expand Up @@ -180,8 +180,8 @@ def rowFromData(self, data):

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[section])
return QVariant()
return self.header[section]
return None

def _getNewObject(self):
pass
Expand All @@ -201,37 +201,37 @@ def __init__(self, parent, editable=False):

def headerData(self, section, orientation, role):
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return QVariant(section+1)
return section+1
return SimpleTableModel.headerData(self, section, orientation, role)

def append(self, fld):
data = [fld.name, fld.type2String(), not fld.notNull, fld.default2String()]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(fld), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(fld.primaryKey), Qt.UserRole)
self.setData(self.index(row, 0), fld, Qt.UserRole)
self.setData(self.index(row, 1), fld.primaryKey, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableField
return TableField(None)

def getObject(self, row):
val = self.data(self.index(row, 0), Qt.UserRole)
fld = val.toPyObject() if val.isValid() else self._getNewObject()
fld.name = self.data(self.index(row, 0)).toString()
fld = val if val != None else self._getNewObject()
fld.name = self.data(self.index(row, 0)) or ""

typestr = self.data(self.index(row, 1)).toString()
typestr = self.data(self.index(row, 1)) or ""
regex = QRegExp( "([^\(]+)\(([^\)]+)\)" )
startpos = regex.indexIn( QString(typestr) )
startpos = regex.indexIn( typestr )
if startpos >= 0:
fld.dataType = regex.cap(1).trimmed()
fld.modifier = regex.cap(2).trimmed()
fld.dataType = regex.cap(1).strip()
fld.modifier = regex.cap(2).strip()
else:
fld.modifier = None
fld.dataType = typestr

fld.notNull = not self.data(self.index(row, 2)).toBool()
fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole).toBool()
fld.notNull = self.data(self.index(row, 2)) != "true"
fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole)
return fld

def getFields(self):
Expand All @@ -250,9 +250,9 @@ 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, 1), QVariant(constr.type), Qt.UserRole)
self.setData(self.index(row, 2), QVariant(constr.columns), Qt.UserRole)
self.setData(self.index(row, 0), constr, Qt.UserRole)
self.setData(self.index(row, 1), constr.type, Qt.UserRole)
self.setData(self.index(row, 2), constr.columns, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableConstraint
Expand All @@ -261,9 +261,9 @@ def _getNewObject(self):
def getObject(self, row):
val = self.data(self.index(row, 0), Qt.UserRole)
constr = val.toPyObject() if val.isValid() else self._getNewObject()
constr.name = self.data(self.index(row, 0)).toString()
constr.type = self.data(self.index(row, 1), Qt.UserRole).toInt()[0]
constr.columns = self.data(self.index(row, 2), Qt.UserRole).toList()
constr.name = self.data(self.index(row, 0)) or ""
constr.type = self.data(self.index(row, 1), Qt.UserRole)
constr.columns = self.data(self.index(row, 2), Qt.UserRole)
return constr

def getConstraints(self):
Expand All @@ -282,8 +282,8 @@ 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, 1), QVariant(idx.columns), Qt.UserRole)
self.setData(self.index(row, 0), idx, Qt.UserRole)
self.setData(self.index(row, 1), idx.columns, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableIndex
Expand Down

0 comments on commit 80b5a07

Please sign in to comment.