Skip to content
Browse files
[DBManager] Allow to load a layer without primary key
  • Loading branch information
Hugo Mercier committed May 4, 2015
1 parent 00618fc commit d684c8c749ad937b52a305e6b2a1ae6de4b055b8
@@ -208,9 +208,24 @@ def sqlResultModel(self, sql, parent):

return SqlResultModel(self, sql, parent)

def uniqueIdFunction(self):
"""Return a SQL function used to generate a unique id for rows of a query"""
# may be overloaded by derived classes
return "row_number() over ()"

def toSqlLayer(self, sql, geomCol, uniqueCol, layerName="QueryLayer", layerType=None, avoidSelectById=False):
from qgis.core import QgsMapLayer, QgsVectorLayer, QgsRasterLayer

if uniqueCol is None:
if hasattr(self, 'uniqueIdFunction'):
uniqueFct = self.uniqueIdFunction()
if uniqueFct is not None:
q = 1
while "_subq_%d_" % q in sql:
q += 1
sql = "SELECT %s AS _uid_,* FROM (%s) AS _subq_%d_" % (uniqueFct, sql, q)
uniqueCol = "_uid_"

uri = self.uri()
uri.setDataSource("", u"(%s\n)" % sql, geomCol, "", uniqueCol)
if avoidSelectById:
@@ -144,6 +144,8 @@ def runAction(self, action):

return Database.runAction(self, action)

def uniqueIdFunction(self):
return None

class SLTable(Table):
def __init__(self, row, db, schema=None):
@@ -178,18 +178,17 @@ def executeSql(self):

def loadSqlLayer(self):
uniqueFieldName = self.uniqueCombo.currentText()
hasUniqueField = self.uniqueColumnCheck.checkState() == Qt.Checked
if hasUniqueField:
uniqueFieldName = self.uniqueCombo.currentText()
uniqueFieldName = None
hasGeomCol = self.hasGeometryCol.checkState() == Qt.Checked
if hasGeomCol:
geomFieldName = self.geomCombo.currentText()
geomFieldName = None

if (hasGeomCol and geomFieldName == "") or uniqueFieldName == "":
QMessageBox.warning(self,"DB Manager"),
"You must fill the required fields: \ngeometry column - column with unique integer values"))

query = self.editSql.text()
if query == "":
@@ -6,7 +6,7 @@
@@ -181,7 +181,7 @@
<item row="0" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<widget class="QLabel" name="label_4">
<widget class="QCheckBox" name="uniqueColumnCheck">
<property name="text">
<string>Column with unique
integer values</string>
@@ -190,6 +190,9 @@ integer values</string>
<widget class="QComboBox" name="uniqueCombo">
<property name="enabled">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
@@ -403,5 +406,21 @@ columns</string>
<hint type="sourcelabel">
<hint type="destinationlabel">

0 comments on commit d684c8c

Please sign in to comment.