Skip to content

Commit

Permalink
Add comment on field | DbManager
Browse files Browse the repository at this point in the history
  • Loading branch information
corentin.falcone committed Jan 10, 2019
1 parent 805646d commit 6b98d8d
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 74 deletions.
6 changes: 3 additions & 3 deletions python/plugins/db_manager/db_plugins/data_model.py
Expand Up @@ -259,7 +259,7 @@ def getObjectIter(self):
class TableFieldsModel(SimpleTableModel):

def __init__(self, parent, editable=False):
SimpleTableModel.__init__(self, ['Name', 'Type', 'Null', 'Default'], editable, parent)
SimpleTableModel.__init__(self, ['Name', 'Type', 'Null', 'Default', 'Comment'], editable, parent)

def headerData(self, section, orientation, role):
if orientation == Qt.Vertical and role == Qt.DisplayRole:
Expand All @@ -273,7 +273,7 @@ def flags(self, index):
return flags

def append(self, fld):
data = [fld.name, fld.type2String(), not fld.notNull, fld.default2String()]
data = [fld.name, fld.type2String(), not fld.notNull, fld.default2String(), fld.getComment()]
self.appendRow(self.rowFromData(data))
row = self.rowCount() - 1
self.setData(self.index(row, 0), fld, Qt.UserRole)
Expand All @@ -290,7 +290,6 @@ def getObject(self, row):
val = self.data(self.index(row, 0), Qt.UserRole)
fld = val if val is not None else self._getNewObject()
fld.name = self.data(self.index(row, 0)) or ""

typestr = self.data(self.index(row, 1)) or ""
regex = QRegExp("([^\\(]+)\\(([^\\)]+)\\)")
startpos = regex.indexIn(typestr)
Expand All @@ -303,6 +302,7 @@ def getObject(self, row):

fld.notNull = self.data(self.index(row, 2), Qt.CheckStateRole) == Qt.Unchecked
fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole)
fld.comment = self.data(self.index(row, 4), Qt.UserRole)
return fld

def getFields(self):
Expand Down
28 changes: 25 additions & 3 deletions python/plugins/db_manager/db_plugins/plugin.py
Expand Up @@ -1101,7 +1101,27 @@ def delete(self):
def rename(self, new_name):
return self.update(new_name)

def update(self, new_name, new_type_str=None, new_not_null=None, new_default_str=None):
def getComment(self):
# Function returning the comment of a field if exists
tab = self.table()
#SQL Query checking if a comment exists for the field
sql_cpt = u"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 = u"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 void string



def update(self, new_name, new_type_str=None, new_not_null=None, new_default_str=None, new_comment=None):
self.table().aboutToChange.emit()
if self.name == new_name:
new_name = None
Expand All @@ -1111,10 +1131,12 @@ def update(self, new_name, new_type_str=None, new_not_null=None, new_default_str
new_not_null = None
if self.default2String() == new_default_str:
new_default_str = None

if self.comment == new_comment:
# Update also a new_comment
new_comment = None
ret = self.table().database().connector.updateTableColumn((self.table().schemaName(), self.table().name),
self.name, new_name, new_type_str, new_not_null,
new_default_str)
new_default_str, new_comment)
if ret is not False:
self.table().refreshFields()
return ret
Expand Down
11 changes: 9 additions & 2 deletions python/plugins/db_manager/db_plugins/postgis/connector.py
Expand Up @@ -857,8 +857,8 @@ 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):
if new_name is None and data_type is None and not_null is None and default is None:
def updateTableColumn(self, table, column, new_name=None, data_type=None, not_null=None, default=None, comment=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

c = self._get_cursor()
Expand Down Expand Up @@ -895,6 +895,13 @@ def updateTableColumn(self, table, column, new_name=None, data_type=None, not_nu
self.quoteString(new_name), schema_where, self.quoteString(tablename), self.quoteString(column))
self._execute(c, sql)

# comment the column
if comment is not None:
# Add the comment on the field
schema, tablename = self.getSchemaTableName(table)
sql = u"COMMENT ON COLUMN %s.%s.%s is '%s'" % (schema, tablename, column, comment)
self._execute(c, sql)

self._commit()

def renameTableColumn(self, table, column, new_name):
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/db_manager/db_plugins/postgis/info_model.py
Expand Up @@ -162,7 +162,7 @@ def fieldsDetails(self):
header = (
"#", QApplication.translate("DBManagerPlugin", "Name"), QApplication.translate("DBManagerPlugin", "Type"),
QApplication.translate("DBManagerPlugin", "Length"), QApplication.translate("DBManagerPlugin", "Null"),
QApplication.translate("DBManagerPlugin", "Default"))
QApplication.translate("DBManagerPlugin", "Default"), QApplication.translate("DBManagerPlugin", "Comment"))
tbl.append(HtmlTableHeader(header))

# add table contents
Expand All @@ -174,7 +174,7 @@ def fieldsDetails(self):
attrs = {"class": "underline"} if fld.primaryKey else None
name = HtmlTableCol(fld.name, attrs)

tbl.append((fld.num, name, fld.type2String(), char_max_len, is_null_txt, fld.default2String()))
tbl.append((fld.num, name, fld.type2String(), char_max_len, is_null_txt, fld.default2String(), fld.getComment()))

return HtmlTable(tbl, {"class": "header"})

Expand Down
16 changes: 15 additions & 1 deletion python/plugins/db_manager/dlg_field_properties.py
Expand Up @@ -22,7 +22,7 @@
__date__ = 'April 2012'
__copyright__ = '(C) 2012, Giuseppe Sucameli'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
__revision__ = '2f64a3c4e74022c5555ee19862f034ffacc2b5fe'

from qgis.PyQt.QtWidgets import QDialog, QMessageBox

Expand Down Expand Up @@ -56,6 +56,18 @@ def setField(self, fld):
self.chkNull.setChecked(not fld.notNull)
if fld.hasDefault:
self.editDefault.setText(fld.default)
# Check with SQL query if a comment exists for the field
sql_cpt = u"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 = u"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

def getField(self, newCopy=False):
fld = TableField(self.table) if not self.fld or newCopy else self.fld
Expand All @@ -64,6 +76,8 @@ def getField(self, newCopy=False):
fld.notNull = not self.chkNull.isChecked()
fld.default = self.editDefault.text()
fld.hasDefault = fld.default != ""
#Get the comment from the LineEdit
fld.comment = self.editCom.text()
try:
modifier = int(self.editLength.text())
except ValueError:
Expand Down
37 changes: 1 addition & 36 deletions python/plugins/db_manager/dlg_table_properties.py
Expand Up @@ -59,10 +59,6 @@ def __init__(self, table, parent=None):
m = TableIndexesModel(self)
self.viewIndexes.setModel(m)

#Display comment in line edit
m = self.table.comment
self.viewComment.setText(m)

self.btnAddColumn.clicked.connect(self.addColumn)
self.btnAddGeometryColumn.clicked.connect(self.addGeometryColumn)
self.btnEditColumn.clicked.connect(self.editColumn)
Expand All @@ -75,11 +71,6 @@ def __init__(self, table, parent=None):
self.btnAddSpatialIndex.clicked.connect(self.createSpatialIndex)
self.btnDeleteIndex.clicked.connect(self.deleteIndex)

#Connect button add Comment to function
self.btnAddComment.clicked.connect(self.createComment)
#Connect button delete Comment to function
self.btnDeleteComment.clicked.connect(self.deleteComment)

self.refresh()

def refresh(self):
Expand Down Expand Up @@ -162,7 +153,7 @@ def editColumn(self):
with OverrideCursor(Qt.WaitCursor):
self.aboutToChangeTable.emit()
try:
fld.update(new_fld.name, new_fld.type2String(), new_fld.notNull, new_fld.default2String())
fld.update(new_fld.name, new_fld.type2String(), new_fld.notNull, new_fld.default2String(), new_fld.comment)
self.refresh()
except BaseError as e:
DlgDbError.showError(e, self)
Expand Down Expand Up @@ -331,29 +322,3 @@ def deleteIndex(self):
self.refresh()
except BaseError as e:
DlgDbError.showError(e, self)

def createComment(self):
#Function that add a comment to the selected table
try:
#Using the db connector, executing de SQL query Comment on table
self.db.connector._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS E\'{2}\';'.format(self.table.schema().name, self.table.name, self.viewComment.text()))
except DbError as e:
DlgDbError.showError(e, self)
return
self.refresh()
#Display successful message
QMessageBox.information(self, self.tr("Add comment"), self.tr("Table successfully commented"))

def deleteComment(self):
#Function that drop the comment to the selected table
try:
#Using the db connector, executing de SQL query Comment on table using the NULL definition
self.db.connector._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS NULL;'.format(self.table.schema().name, self.table.name))
except DbError as e:
DlgDbError.showError(e, self)
return
self.refresh()
#Refresh line edit, put a void comment
self.viewComment.setText('')
#Display successful message
QMessageBox.information(self, self.tr("Delete comment"), self.tr("Comment deleted"))
71 changes: 44 additions & 27 deletions python/plugins/db_manager/ui/DlgFieldProperties.ui 100644 → 100755
Expand Up @@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>354</width>
<height>247</height>
<width>569</width>
<height>308</height>
</rect>
</property>
<property name="windowTitle">
Expand All @@ -23,20 +23,13 @@
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="editName">
<item row="2" column="1">
<widget class="QLineEdit" name="editLength">
<property name="text">
<string notr="true"/>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Type</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="cboType">
<property name="editable">
Expand All @@ -47,10 +40,10 @@
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_3">
<item row="4" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Can be NULL</string>
<string>Default value expression</string>
</property>
</widget>
</item>
Expand All @@ -64,10 +57,38 @@
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_4">
<item row="0" column="1">
<widget class="QLineEdit" name="editName">
<property name="text">
<string>Default value expression</string>
<string notr="true"/>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Length</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Type</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Can be NULL</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>Comment</string>
</property>
</widget>
</item>
Expand All @@ -81,15 +102,11 @@
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Length</string>
<item row="5" column="1">
<widget class="QLineEdit" name="editCom">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Properly quoted PostgreSQL expression (e.g. &lt;code&gt;4&lt;/code&gt;, &lt;code&gt;'text'&lt;/code&gt; or &lt;code&gt;nextval('foo_id_seq')&lt;/code&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="editLength">
<property name="text">
<string notr="true"/>
</property>
Expand Down Expand Up @@ -126,8 +143,8 @@
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
<x>325</x>
<y>456</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
Expand Down

0 comments on commit 6b98d8d

Please sign in to comment.