Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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 471734a
Show file tree
Hide file tree
Showing 14 changed files with 114 additions and 86 deletions.
9 changes: 9 additions & 0 deletions python/plugins/db_manager/db_plugins/connector.py
Expand Up @@ -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 {}
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_plugins/gpkg/connector.py
Expand Up @@ -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

Expand Down
7 changes: 3 additions & 4 deletions python/plugins/db_manager/db_plugins/gpkg/plugin.py
Expand Up @@ -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):

Expand Down Expand Up @@ -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):

Expand Down
33 changes: 16 additions & 17 deletions python/plugins/db_manager/db_plugins/oracle/plugin.py
Expand Up @@ -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):

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):

Expand Down
16 changes: 1 addition & 15 deletions python/plugins/db_manager/db_plugins/plugin.py
Expand Up @@ -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)
Expand Down
25 changes: 24 additions & 1 deletion python/plugins/db_manager/db_plugins/postgis/connector.py
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions python/plugins/db_manager/db_plugins/postgis/plugin.py
Expand Up @@ -181,6 +181,9 @@ def runRefreshMaterializedViewSlot(self, item, action, parent):
def hasLowercaseFieldNamesOption(self):
return True

def supportsComment(self):
return True


class PGSchema(Schema):

Expand Down Expand Up @@ -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):

Expand Down
Expand Up @@ -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):
Expand Down
7 changes: 3 additions & 4 deletions python/plugins/db_manager/db_plugins/spatialite/plugin.py
Expand Up @@ -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):

Expand Down Expand Up @@ -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):

Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_plugins/vlayers/connector.py
Expand Up @@ -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):
Expand Down
7 changes: 3 additions & 4 deletions python/plugins/db_manager/db_plugins/vlayers/plugin.py
Expand Up @@ -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):

Expand Down Expand Up @@ -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 ''
30 changes: 11 additions & 19 deletions python/plugins/db_manager/dlg_field_properties.py
Expand Up @@ -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


Expand All @@ -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)

Expand All @@ -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
Expand Down
11 changes: 9 additions & 2 deletions python/plugins/db_manager/dlg_import_vector.py
Expand Up @@ -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"

Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 471734a

Please sign in to comment.