Skip to content
Permalink
Browse files

Merge pull request #9111 from SIRS-CLS/sirs_db_manager

Fix bug comment on postgres and others management
  • Loading branch information
elpaso committed Feb 8, 2019
2 parents 7e106ef + d331143 commit 471734a9eaf6029ce75cf563d1014d9ecab11409
@@ -231,5 +231,14 @@ def getSqlDictionary(self):
except ImportError:
return []

def getComment(self, tablename, field):
"""Returns the comment for a field"""
return ''

def commentTable(self, schema, tablename, comment=None):
"""Comment the table"""
pass

def getQueryBuilderDictionary(self):

return {}
@@ -644,7 +644,7 @@ def deleteTableColumn(self, table, column):
return lyr.DeleteField(idx) == 0
return False

def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None, new_comment=None):
def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None, comment=None):
if self.isGeometryColumn(table, column):
return False

@@ -177,6 +177,9 @@ def toSqlLayer(self, sql, geomCol, uniqueCol, layerName="QueryLayer", layerType=
vl.setSubsetString(sql)
return vl

def supportsComment(self):
return False


class GPKGTable(Table):

@@ -301,10 +304,6 @@ def __init__(self, row, table):
self.num, self.name, self.dataType, self.notNull, self.default, self.primaryKey = row
self.hasDefault = self.default

def getComment(self):
"""Returns the comment for a field"""
return ''


class GPKGTableIndex(TableIndex):

@@ -263,6 +263,9 @@ def registerDatabaseActions(self, mainWindow):
mainWindow.registerAction(action, QApplication.translate(
"DBManagerPlugin", "&Table"), self.emptyTableActionSlot)

def supportsComment(self):
return False


class ORSchema(Schema):

@@ -405,18 +408,18 @@ def getValidQgisUniqueFields(self, onlyOne=False):
for idx in indexes:
if idx.isUnique and len(idx.columns) == 1:
fld = idx.fields()[idx.columns[0]]
if (fld.dataType == u"NUMBER" and
not fld.modifier and
fld.notNull and
fld not in ret):
if (fld.dataType == u"NUMBER"
and not fld.modifier
and fld.notNull
and fld not in ret):
ret.append(fld)

# and finally append the other suitable fields
for fld in self.fields():
if (fld.dataType == u"NUMBER" and
not fld.modifier and
fld.notNull and
fld not in ret):
if (fld.dataType == u"NUMBER"
and not fld.modifier
and fld.notNull
and fld not in ret):
ret.append(fld)

if onlyOne:
@@ -516,15 +519,15 @@ def __init__(self, row, table):

# find out whether fields are part of primary key
for con in self.table().constraints():
if (con.type == ORTableConstraint.TypePrimaryKey and
self.name == con.column):
if (con.type == ORTableConstraint.TypePrimaryKey
and self.name == con.column):
self.primaryKey = True
break

def type2String(self):
if (u"TIMESTAMP" in self.dataType or
self.dataType in [u"DATE", u"SDO_GEOMETRY",
u"BINARY_FLOAT", u"BINARY_DOUBLE"]):
if (u"TIMESTAMP" in self.dataType
or self.dataType in [u"DATE", u"SDO_GEOMETRY",
u"BINARY_FLOAT", u"BINARY_DOUBLE"]):
return u"{}".format(self.dataType)
if self.charMaxLen in [None, -1]:
return u"{}".format(self.dataType)
@@ -559,10 +562,6 @@ def update(self, new_name, new_type_str=None, new_not_null=None,
self.table().refreshIndexes()
return ret

def getComment(self):
"""Returns the comment for a field"""
return ''


class ORTableConstraint(TableConstraint):

@@ -1097,21 +1097,7 @@ def definition(self):

def getComment(self):
"""Returns the comment for a field"""
tab = self.table()
# SQL Query checking if a comment exists for the field
sql_cpt = "Select count(*) from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tab.name, self.name)
# SQL Query that return the comment of the field
sql = "Select pd.description from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tab.name, self.name)
c = tab.database().connector._execute(None, sql_cpt) # Execute Check query
res = tab.database().connector._fetchone(c)[0] # Store result
if res == 1:
# When a comment exists
c = tab.database().connector._execute(None, sql) # Execute query
res = tab.database().connector._fetchone(c)[0] # Store result
tab.database().connector._close_cursor(c) # Close cursor
return res # Return comment
else:
return ''
return ''

def delete(self):
return self.table().deleteField(self)
@@ -742,6 +742,29 @@ def renameTable(self, table, new_table):

self._commit()

def commentTable(self, schema, tablename, comment=None):
if comment is None:
self._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS NULL;'.format(schema, tablename))
else:
self._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS E\'{2}\';'.format(schema, tablename, comment))

def getComment(self, tablename, field):
"""Returns the comment for a field"""
# SQL Query checking if a comment exists for the field
sql_cpt = "Select count(*) from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tablename, field)
# SQL Query that return the comment of the field
sql = "Select pd.description from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tablename, field)
c = self._execute(None, sql_cpt) # Execute Check query
res = self._fetchone(c)[0] # Store result
if res == 1:
# When a comment exists
c = self._execute(None, sql) # Execute query
res = self._fetchone(c)[0] # Store result
self._close_cursor(c) # Close cursor
return res # Return comment
else:
return ''

def moveTableToSchema(self, table, new_schema):
schema, tablename = self.getSchemaTableName(table)
if new_schema == schema:
@@ -857,7 +880,7 @@ def deleteTableColumn(self, table, column):
sql = u"ALTER TABLE %s DROP %s" % (self.quoteId(table), self.quoteId(column))
self._execute_and_commit(sql)

def updateTableColumn(self, table, column, new_name=None, data_type=None, not_null=None, default=None, comment=None):
def updateTableColumn(self, table, column, new_name=None, data_type=None, not_null=None, default=None, comment=None, test=None):
if new_name is None and data_type is None and not_null is None and default is None and comment is None:
return

@@ -181,6 +181,9 @@ def runRefreshMaterializedViewSlot(self, item, action, parent):
def hasLowercaseFieldNamesOption(self):
return True

def supportsComment(self):
return True


class PGSchema(Schema):

@@ -397,6 +400,24 @@ def __init__(self, row, table):
self.primaryKey = True
break

def getComment(self):
"""Returns the comment for a field"""
tab = self.table()
# SQL Query checking if a comment exists for the field
sql_cpt = "Select count(*) from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tab.name, self.name)
# SQL Query that return the comment of the field
sql = "Select pd.description from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (tab.name, self.name)
c = tab.database().connector._execute(None, sql_cpt) # Execute Check query
res = tab.database().connector._fetchone(c)[0] # Store result
if res == 1:
# When a comment exists
c = tab.database().connector._execute(None, sql) # Execute query
res = tab.database().connector._fetchone(c)[0] # Store result
tab.database().connector._close_cursor(c) # Close cursor
return res # Return comment
else:
return ''


class PGTableConstraint(TableConstraint):

@@ -595,7 +595,7 @@ def deleteTableColumn(self, table, column):
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, new_comment=None):
def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None, comment=None):
return False # column editing not supported

def renameTableColumn(self, table, column, new_name):
@@ -175,6 +175,9 @@ def explicitSpatialIndex(self):
def spatialIndexClause(self, src_table, src_column, dest_table, dest_column):
return u""" "%s".ROWID IN (\nSELECT ROWID FROM SpatialIndex WHERE f_table_name='%s' AND search_frame="%s"."%s") """ % (src_table, src_table, dest_table, dest_column)

def supportsComment(self):
return False


class SLTable(Table):

@@ -294,10 +297,6 @@ def __init__(self, row, table):
self.num, self.name, self.dataType, self.notNull, self.default, self.primaryKey = row
self.hasDefault = self.default

def getComment(self):
"""Returns the comment for a field"""
return ''


class SLTableIndex(TableIndex):

@@ -349,7 +349,7 @@ def addTableColumn(self, table, field_def):
def deleteTableColumn(self, table, column):
print("**unimplemented** deleteTableColumn")

def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None, new_comment=None):
def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None, comment=None):
print("**unimplemented** updateTableColumn")

def renameTableColumn(self, table, column, new_name):
@@ -132,6 +132,9 @@ def explicitSpatialIndex(self):
def spatialIndexClause(self, src_table, src_column, dest_table, dest_column):
return '"%s"._search_frame_ = "%s"."%s"' % (src_table, dest_table, dest_column)

def supportsComment(self):
return False


class LTable(Table):

@@ -192,7 +195,3 @@ def __init__(self, row, table):
TableField.__init__(self, table)
self.num, self.name, self.dataType, self.notNull, self.default, self.primaryKey = row
self.hasDefault = self.default

def getComment(self):
"""Returns the comment for a field"""
return ''
@@ -27,7 +27,6 @@
from qgis.PyQt.QtWidgets import QDialog, QMessageBox

from .db_plugins.plugin import TableField

from .ui.ui_DlgFieldProperties import Ui_DbManagerDlgFieldProperties as Ui_Dialog


@@ -42,7 +41,13 @@ def __init__(self, parent=None, fld=None, table=None, db=None):

for item in self.db.connector.fieldTypes():
self.cboType.addItem(item)
self.setField(self.fld)

supportCom = self.db.supportsComment()
if not supportCom:
self.label_6.setVisible(False)
self.editCom.setVisible(False)

self.setField(fld)

self.buttonBox.accepted.connect(self.onOK)

@@ -56,23 +61,10 @@ def setField(self, fld):
self.chkNull.setChecked(not fld.notNull)
if fld.hasDefault:
self.editDefault.setText(fld.default)
# This is an ugly patch, but the comments PR https://github.com/qgis/QGIS/pull/8831 added
# support for postgres only and broke all the others :(
try:
# Check with SQL query if a comment exists for the field
sql_cpt = "Select count(*) from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (self.table.name, self.editName.text())
# Get the comment for the field with SQL Query
sql = "Select pd.description from pg_description pd, pg_class pc, pg_attribute pa where relname = '%s' and attname = '%s' and pa.attrelid = pc.oid and pd.objoid = pc.oid and pd.objsubid = pa.attnum" % (self.table.name, self.editName.text())
c = self.db.connector._execute(None, sql_cpt) # Execute check query
res = self.db.connector._fetchone(c)[0] # Fetch data
# Check if result is 1 then it's ok, else we don't want to get a value
if res == 1:
c = self.db.connector._execute(None, sql) # Execute query returning the comment value
res = self.db.connector._fetchone(c)[0] # Fetch the comment value
self.db.connector._close_cursor(c) # Close cursor
self.editCom.setText(res) # Set comment value
except:
self.editCom.setEnabled(False)
tab = self.table.name
field = fld.name
res = self.db.connector.getComment(tab, field)
self.editCom.setText(res) # Set comment value

def getField(self, newCopy=False):
fld = TableField(self.table) if not self.fld or newCopy else self.fld
@@ -51,6 +51,11 @@ def __init__(self, inLayer, outDb, outUri, parent=None):
self.outUri = outUri
self.setupUi(self)

supportCom = self.db.supportsComment()
if not supportCom:
self.chkCom.setVisible(False)
self.editCom.setVisible(False)

self.default_pk = "id"
self.default_geom = "geom"

@@ -368,9 +373,11 @@ def accept(self):
self.db.connector.createSpatialIndex((schema, table), geom)

# add comment on table
if self.chkCom.isEnabled() and self.chkCom.isChecked():
supportCom = self.db.supportsComment()
if self.chkCom.isEnabled() and self.chkCom.isChecked() and supportCom:
# using connector executing COMMENT ON TABLE query (with editCome.text() value)
self.db.connector._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS E\'{2}E\''.format(schema, table, self.editCom.text()))
com = self.editCome.text()
self.db.connector.commentTable(schema, table, com)

self.db.connection().reconnect()
self.db.refresh()

0 comments on commit 471734a

Please sign in to comment.
You can’t perform that action at this time.