public inbox for [email protected]  
help / color / mirror / Atom feed
[pgAdmin4][Patch] - SonarQube Fixes
11+ messages / 3 participants
[nested] [flat]

* [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-08-03 08:06  Khushboo Vashi <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Khushboo Vashi @ 2020-08-03 08:06 UTC (permalink / raw)
  To: pgadmin-hackers

Hi,

Please find the attached patch to fix the sonarqube code smells having the
rule "String literals should not be duplicated".

Thanks,
Khushboo


Attachments:

  [application/octet-stream] sonarqube_fixes.patch (40.0K, 3-sonarqube_fixes.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/__init__.py b/web/pgadmin/browser/__init__.py
index b1f2b5d92..ebeb0eab4 100644
--- a/web/pgadmin/browser/__init__.py
+++ b/web/pgadmin/browser/__init__.py
@@ -57,6 +57,18 @@ except ImportError as e:
         from flask_security.views import _render_json as default_render_json
 
 MODULE_NAME = 'browser'
+BROWSER_STATIC = 'browser.static'
+JQUERY_ACIPLUGIN = 'jquery.aciplugin'
+BROWSER_INDEX = 'browser.index'
+PGADMIN_NODE = 'pgadmin.node.%s'
+PGADMIN_BROWSER = 'pgAdmin.Browser'
+APP_JS = 'application/javascript'
+SMTP_SOCKET_ERROR = u'SMTP Socket error: {}\n' \
+                    u'Your password has not been changed.'
+SMTP_ERROR = u'SMTP error: {}\n' \
+             u'Your password has not been changed.'
+PASS_ERROR = u'Error: {}\n' \
+             u'Your password has not been changed.'
 
 
 class BrowserModule(PgAdminModule):
@@ -77,7 +89,7 @@ class BrowserModule(PgAdminModule):
             ('static', 'vendor/codemirror/addon/dialog/dialog.css'),
             ('static', context_menu_file),
             ('static', wcdocker_file),
-            ('browser.static', 'vendor/aciTree/css/aciTree.css')
+            (BROWSER_STATIC, 'vendor/aciTree/css/aciTree.css')
         ]:
             stylesheets.append(url_for(endpoint, filename=filename))
         return stylesheets
@@ -119,9 +131,9 @@ class BrowserModule(PgAdminModule):
             'preloaded': True
         })
         scripts.append({
-            'name': 'jquery.aciplugin',
+            'name': JQUERY_ACIPLUGIN,
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciPlugin.min'
             ),
             'deps': ['jquery'],
@@ -131,21 +143,21 @@ class BrowserModule(PgAdminModule):
         scripts.append({
             'name': 'jquery.acitree',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciTree' if
                 current_app.debug else 'vendor/aciTree/jquery.aciTree.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciTree',
             'preloaded': True
         })
         scripts.append({
             'name': 'jquery.acisortable',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciSortable.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciSortable',
             'when': None,
             'preloaded': True
@@ -153,10 +165,10 @@ class BrowserModule(PgAdminModule):
         scripts.append({
             'name': 'jquery.acifragment',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciFragment.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciFragment',
             'when': None,
             'preloaded': True
@@ -175,7 +187,7 @@ class BrowserModule(PgAdminModule):
 
         scripts.append({
             'name': 'pgadmin.browser.datamodel',
-            'path': url_for('browser.static', filename='js/datamodel'),
+            'path': url_for(BROWSER_STATIC, filename='js/datamodel'),
             'preloaded': True
         })
 
@@ -186,7 +198,7 @@ class BrowserModule(PgAdminModule):
         ]:
             scripts.append({
                 'name': name,
-                'path': url_for('browser.index') + script,
+                'path': url_for(BROWSER_INDEX) + script,
                 'preloaded': True
             })
 
@@ -197,7 +209,7 @@ class BrowserModule(PgAdminModule):
         ]:
             scripts.append({
                 'name': name,
-                'path': url_for('browser.index') + script,
+                'path': url_for(BROWSER_INDEX) + script,
                 'preloaded': True,
                 'deps': ['pgadmin.browser.datamodel']
             })
@@ -208,12 +220,12 @@ class BrowserModule(PgAdminModule):
             ['pgadmin.browser.frame', 'js/frame']
         ]:
             scripts.append({
-                'name': name, 'path': url_for('browser.static', filename=end),
+                'name': name, 'path': url_for(BROWSER_STATIC, filename=end),
                 'preloaded': True})
 
         scripts.append({
             'name': 'pgadmin.browser.node.ui',
-            'path': url_for('browser.static', filename='js/node.ui'),
+            'path': url_for(BROWSER_STATIC, filename='js/node.ui'),
             'when': 'server_group'
         })
 
@@ -226,26 +238,26 @@ class BrowserModule(PgAdminModule):
             'file_items': [
                 MenuItem(
                     name='mnu_locklayout',
-                    module='pgAdmin.Browser',
+                    module=PGADMIN_BROWSER,
                     label=gettext('Lock Layout'),
                     priority=999,
                     menu_items=[MenuItem(
                         name='mnu_lock_none',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_none',
                         priority=0,
                         label=gettext('None'),
                         checked=True
                     ), MenuItem(
                         name='mnu_lock_docking',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_docking',
                         priority=1,
                         label=gettext('Prevent Docking'),
                         checked=False
                     ), MenuItem(
                         name='mnu_lock_full',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_full',
                         priority=2,
                         label=gettext('Full Lock'),
@@ -263,7 +275,7 @@ class BrowserModule(PgAdminModule):
         Returns:
             list: a list of url endpoints exposed to the client.
         """
-        return ['browser.index', 'browser.nodes',
+        return [BROWSER_INDEX, 'browser.nodes',
                 'browser.check_master_password',
                 'browser.set_master_password',
                 'browser.reset_master_password',
@@ -358,15 +370,14 @@ class BrowserPluginModule(PgAdminModule):
 
         if self.module_use_template_javascript:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
-                'path': url_for('browser.index') +
-                        '%s/module' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
+                'path': url_for(BROWSER_INDEX) + '%s/module' % self.node_type,
                 'when': self.script_load,
                 'is_template': True
             }])
         else:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
                 'path': url_for(
                     '%s.static' % self.name,
                     filename=('js/%s' % self.node_type)
@@ -412,7 +423,7 @@ class BrowserPluginModule(PgAdminModule):
             "_type": node_type,
             "_id": node_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % node_type
+            "module": PGADMIN_NODE % node_type
         }
         for key in kwargs:
             obj.setdefault(key, kwargs[key])
@@ -527,7 +538,7 @@ class BrowserPluginModule(PgAdminModule):
 
 def _get_logout_url():
     return '{0}?next={1}'.format(
-        url_for('security.logout'), url_for('browser.index'))
+        url_for('security.logout'), url_for(BROWSER_INDEX))
 
 
 @blueprint.route("/")
@@ -737,7 +748,7 @@ def utils():
             support_ssh_tunnel=config.SUPPORT_SSH_TUNNEL,
             logout_url=_get_logout_url()
         ),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/js/endpoints.js")
@@ -745,7 +756,7 @@ def utils():
 def exposed_urls():
     return make_response(
         render_template('browser/js/endpoints.js'),
-        200, {'Content-Type': 'application/javascript'}
+        200, {'Content-Type': APP_JS}
     )
 
 
@@ -755,7 +766,7 @@ def exposed_urls():
 def error_js():
     return make_response(
         render_template('browser/js/error.js', _=gettext),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/js/messages.js")
@@ -763,7 +774,7 @@ def error_js():
 def messages_js():
     return make_response(
         render_template('browser/js/messages.js', _=gettext),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/browser.css")
@@ -969,9 +980,7 @@ if hasattr(config, 'SECURITY_CHANGEABLE') and config.SECURITY_CHANGEABLE:
             except SOCKETErrorException as e:
                 # Handle socket errors which are not covered by SMTPExceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP Socket error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_SOCKET_ERROR).format(e),
                       'danger')
                 has_error = True
             except (SMTPConnectError, SMTPResponseException,
@@ -980,19 +989,14 @@ if hasattr(config, 'SECURITY_CHANGEABLE') and config.SECURITY_CHANGEABLE:
                     SMTPRecipientsRefused) as e:
                 # Handle smtp specific exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_ERROR).format(e),
                       'danger')
                 has_error = True
             except Exception as e:
                 # Handle other exceptions.
                 logging.exception(str(e), exc_info=True)
                 flash(
-                    gettext(
-                        u'Error: {}\n'
-                        u'Your password has not been changed.'
-                    ).format(e),
+                    gettext(PASS_ERROR).format(e),
                     'danger'
                 )
                 has_error = True
@@ -1078,9 +1082,7 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
                     # Handle socket errors which are not
                     # covered by SMTPExceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'SMTP Socket error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(SMTP_SOCKET_ERROR).format(e),
                           'danger')
                     has_error = True
                 except (SMTPConnectError, SMTPResponseException,
@@ -1090,17 +1092,13 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
 
                     # Handle smtp specific exceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'SMTP error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(SMTP_ERROR).format(e),
                           'danger')
                     has_error = True
                 except Exception as e:
                     # Handle other exceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'Error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(PASS_ERROR).format(e),
                           'danger')
                     has_error = True
 
@@ -1149,9 +1147,7 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
             except SOCKETErrorException as e:
                 # Handle socket errors which are not covered by SMTPExceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP Socket error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_SOCKET_ERROR).format(e),
                       'danger')
                 has_error = True
             except (SMTPConnectError, SMTPResponseException,
@@ -1161,17 +1157,13 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
 
                 # Handle smtp specific exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_ERROR).format(e),
                       'danger')
                 has_error = True
             except Exception as e:
                 # Handle other exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'Error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(PASS_ERROR).format(e),
                       'danger')
                 has_error = True
 
diff --git a/web/pgadmin/browser/collection.py b/web/pgadmin/browser/collection.py
index 6c1633451..1cecb3f4c 100644
--- a/web/pgadmin/browser/collection.py
+++ b/web/pgadmin/browser/collection.py
@@ -17,6 +17,8 @@ from pgadmin.browser.utils import PGChildModule
 from pgadmin.utils import PgAdminModule
 from pgadmin.utils.preferences import Preferences
 
+PGADMIN_NODE = 'pgadmin.node.%s'
+
 
 @six.add_metaclass(ABCMeta)
 class CollectionNodeModule(PgAdminModule, PGChildModule):
@@ -58,15 +60,15 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
 
         if self.module_use_template_javascript:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
-                'path': url_for('browser.index') +
-                        '%s/module' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
+                'path': url_for('browser.index'
+                                ) + '%s/module' % self.node_type,
                 'when': self.script_load,
                 'is_template': True
             }])
         else:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
                 'path': url_for(
                     '%s.static' % self.name,
                     filename=('js/%s' % self.node_type)
@@ -93,7 +95,7 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
             "_type": self.node_type,
             "_id": node_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % self.node_type
+            "module": PGADMIN_NODE % self.node_type
         }
         for key in kwargs:
             obj.setdefault(key, kwargs[key])
@@ -108,7 +110,7 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
             "_type": 'coll-%s' % (self.node_type),
             "_id": parent_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % self.node_type,
+            "module": PGADMIN_NODE % self.node_type,
             "nodes": [self.node_type]
         }
 
diff --git a/web/pgadmin/browser/register_browser_preferences.py b/web/pgadmin/browser/register_browser_preferences.py
index 2857fc7cd..5d6451aa0 100644
--- a/web/pgadmin/browser/register_browser_preferences.py
+++ b/web/pgadmin/browser/register_browser_preferences.py
@@ -13,6 +13,7 @@ LOCK_LAYOUT_LEVEL = {
     'FULL': 'full',
     'NONE': 'none'
 }
+KEYBOARD_SHORTCUTS = 'Keyboard shortcuts'
 
 
 def register_browser_preferences(self):
@@ -125,7 +126,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 66, 'char': 'b'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -140,7 +141,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 91, 'char': '['}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -155,7 +156,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 93, 'char': ']'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -170,7 +171,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 70, 'char': 'f'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -185,7 +186,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 79, 'char': 'o'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -200,7 +201,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 76, 'char': 'l'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -215,7 +216,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 72, 'char': 'h'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -230,7 +231,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 81, 'char': 'q'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -245,7 +246,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 86, 'char': 'v'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -260,7 +261,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 83, 'char': 's'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -275,7 +276,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 78, 'char': 'n'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -290,7 +291,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 69, 'char': 'e'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -305,7 +306,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 68, 'char': 'd'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -320,7 +321,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 77, 'char': 'm'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -335,7 +336,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 85, 'char': 'u'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -350,7 +351,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 67, 'char': 'c'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -365,7 +366,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 71, 'char': 'g'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -380,7 +381,7 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 93, 'char': ']'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -395,7 +396,7 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 91, 'char': '['}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -410,7 +411,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 116, 'char': 'F5'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -425,6 +426,6 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 65, 'char': 'a'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
diff --git a/web/pgadmin/browser/server_groups/__init__.py b/web/pgadmin/browser/server_groups/__init__.py
index b9733f845..3b741c2b8 100644
--- a/web/pgadmin/browser/server_groups/__init__.py
+++ b/web/pgadmin/browser/server_groups/__init__.py
@@ -25,8 +25,12 @@ from sqlalchemy import exc
 from pgadmin.model import db, ServerGroup
 
 
+SG_NOT_FOUND_ERROR = 'The specified server group could not be found.'
+
+
 class ServerGroupModule(BrowserPluginModule):
     _NODE_TYPE = "server_group"
+    node_icon = "icon-%s" % _NODE_TYPE
 
     def get_nodes(self, *arg, **kwargs):
         """Return a JSON document listing the server groups for the user"""
@@ -37,7 +41,7 @@ class ServerGroupModule(BrowserPluginModule):
             yield self.generate_browser_node(
                 "%d" % (group.id), None,
                 group.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type,
                 can_delete=True if idx > 0 else False
@@ -92,6 +96,8 @@ blueprint = ServerGroupModule(__name__)
 
 class ServerGroupView(NodeView):
     node_type = ServerGroupModule._NODE_TYPE
+    node_icon = ServerGroupModule.node_icon
+    node_label = "Server Group"
     parent_ids = []
     ids = [{'type': 'int', 'id': 'gid'}]
 
@@ -136,9 +142,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             try:
@@ -169,9 +173,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=417,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             try:
@@ -194,7 +196,7 @@ class ServerGroupView(NodeView):
                 gid,
                 None,
                 servergroup.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type,
                 can_delete=True  # This is user created hence can deleted
@@ -214,9 +216,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             return ajax_response(
@@ -246,7 +246,7 @@ class ServerGroupView(NodeView):
                         "%d" % sg.id,
                         None,
                         sg.name,
-                        "icon-%s" % self.node_type,
+                        self.node_icon,
                         True,
                         self.node_type,
                         # This is user created hence can deleted
@@ -306,7 +306,7 @@ class ServerGroupView(NodeView):
                         "%d" % group.id,
                         None,
                         group.name,
-                        "icon-%s" % self.node_type,
+                        self.node_icon,
                         True,
                         self.node_type
                     )
@@ -322,7 +322,7 @@ class ServerGroupView(NodeView):
             nodes = self.blueprint.generate_browser_node(
                 "%d" % (group.id), None,
                 group.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type
             )
diff --git a/web/pgadmin/browser/server_groups/servers/__init__.py b/web/pgadmin/browser/server_groups/servers/__init__.py
index 870da543b..b53422680 100644
--- a/web/pgadmin/browser/server_groups/servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/__init__.py
@@ -31,6 +31,8 @@ from pgadmin.utils.exception import CryptKeyMissing
 from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
 from psycopg2 import Error as psycopg2_Error, OperationalError
 
+UNAUTH_REQ = "Unauthorized request."
+
 
 def has_any(data, keys):
     """
@@ -240,6 +242,7 @@ blueprint = ServerModule(__name__)
 
 class ServerNode(PGChildNodeView):
     node_type = ServerModule._NODE_TYPE
+    node_label = "Server"
 
     parent_ids = [{'type': 'int', 'id': 'gid'}]
     ids = [{'type': 'int', 'id': 'sid'}]
@@ -471,7 +474,7 @@ class ServerNode(PGChildNodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error
             )
 
         # Not all parameters can be modified, while the server is connected
@@ -658,7 +661,7 @@ class ServerNode(PGChildNodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error
             )
 
         sg = ServerGroup.query.filter_by(
@@ -1006,15 +1009,15 @@ class ServerNode(PGChildNodeView):
         # Fetch Server Details
         server = Server.query.filter_by(id=sid).first()
         if server is None:
-            return bad_request(gettext("Server not found."))
+            return bad_request(self.not_found_error)
 
         if current_user and hasattr(current_user, 'id'):
             # Fetch User Details.
             user = User.query.filter_by(id=current_user.id).first()
             if user is None:
-                return unauthorized(gettext("Unauthorized request."))
+                return unauthorized(gettext(UNAUTH_REQ))
         else:
-            return unauthorized(gettext("Unauthorized request."))
+            return unauthorized(gettext(UNAUTH_REQ))
 
         data = request.form if request.form else json.loads(
             request.data, encoding='utf-8'
@@ -1181,7 +1184,7 @@ class ServerNode(PGChildNodeView):
 
         server = Server.query.filter_by(id=sid).first()
         if server is None:
-            return bad_request(gettext("Server not found."))
+            return bad_request(self.not_found_error)
 
         # Release Connection
         manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
@@ -1289,12 +1292,12 @@ class ServerNode(PGChildNodeView):
             # Fetch Server Details
             server = Server.query.filter_by(id=sid).first()
             if server is None:
-                return bad_request(gettext("Server not found."))
+                return bad_request(self.not_found_error)
 
             # Fetch User Details.
             user = User.query.filter_by(id=current_user.id).first()
             if user is None:
-                return unauthorized(gettext("Unauthorized request."))
+                return unauthorized(gettext(UNAUTH_REQ))
 
             manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
             conn = manager.connection()
@@ -1409,7 +1412,7 @@ class ServerNode(PGChildNodeView):
         if server is None:
             return make_json_response(
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error
             )
 
         try:
@@ -1493,7 +1496,7 @@ class ServerNode(PGChildNodeView):
         if server is None:
             return make_json_response(
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error
             )
 
         try:
@@ -1568,7 +1571,7 @@ class ServerNode(PGChildNodeView):
             if server is None:
                 return make_json_response(
                     success=0,
-                    info=gettext("Could not find the required server.")
+                    info=self.not_found_error
                 )
 
             setattr(server, 'password', None)
@@ -1607,7 +1610,7 @@ class ServerNode(PGChildNodeView):
             if server is None:
                 return make_json_response(
                     success=0,
-                    info=gettext("Could not find the required server.")
+                    info=self.not_found_error
                 )
 
             setattr(server, 'tunnel_password', None)
diff --git a/web/pgadmin/browser/server_groups/servers/databases/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/__init__.py
index 6c6472583..b7e1bed95 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/__init__.py
@@ -373,7 +373,7 @@ class DatabaseView(PGChildNodeView):
                 status=200
             )
 
-        return gone(errormsg=_("Could not find the database on the server."))
+        return gone(errormsg=self.not_found_error)
 
     @check_precondition(action="properties")
     def properties(self, gid, sid, did):
@@ -388,9 +388,7 @@ class DatabaseView(PGChildNodeView):
             return internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return gone(
-                _("Could not find the database on the server.")
-            )
+            return gone(self.not_found_error)
 
         SQL = render_template(
             "/".join([self.template_path, self._ACL_SQL]),
@@ -793,9 +791,7 @@ class DatabaseView(PGChildNodeView):
             return internal_server_error(errormsg=rset)
 
         if len(rset['rows']) == 0:
-            return gone(
-                _("Could not find the database on the server.")
-            )
+            return gone(self.not_found_error)
 
         res = rset['rows'][0]
 
@@ -924,9 +920,7 @@ class DatabaseView(PGChildNodeView):
                 return False, internal_server_error(errormsg=rset)
 
             if len(rset['rows']) == 0:
-                return gone(
-                    _("Could not find the database on the server.")
-                )
+                return gone(self.not_found_error)
 
             data['old_name'] = (rset['rows'][0])['name']
             if 'name' not in data:
@@ -1095,9 +1089,7 @@ class DatabaseView(PGChildNodeView):
             return internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return gone(
-                _("Could not find the database on the server.")
-            )
+            return gone(self.not_found_error)
 
         SQL = render_template(
             "/".join([self.template_path, self._ACL_SQL]),
diff --git a/web/pgadmin/browser/server_groups/servers/databases/casts/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/casts/__init__.py
index 30640662a..492cdcda5 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/casts/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/casts/__init__.py
@@ -147,6 +147,7 @@ class CastView(PGChildNodeView):
     """
 
     node_type = blueprint.node_type
+    node_label = "Cast"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
diff --git a/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
index 035901726..847c9b07b 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
@@ -147,6 +147,7 @@ class EventTriggerView(PGChildNodeView):
     """
 
     node_type = blueprint.node_type
+    node_icon = "icon-%s" % blueprint.node_type
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -254,7 +255,7 @@ class EventTriggerView(PGChildNodeView):
                     row['oid'],
                     did,
                     row['name'],
-                    icon="icon-%s" % self.node_type
+                    icon=self.node_icon
                 ))
 
         return make_json_response(
@@ -288,7 +289,7 @@ class EventTriggerView(PGChildNodeView):
                     row['oid'],
                     did,
                     row['name'],
-                    icon="icon-%s" % self.node_type
+                    icon=self.node_icon
                 ),
                 status=200
             )
@@ -415,7 +416,7 @@ class EventTriggerView(PGChildNodeView):
                     etid,
                     did,
                     data['name'],
-                    icon="icon-%s" % self.node_type
+                    icon=self.node_icon
                 )
             )
         except Exception as e:
@@ -462,7 +463,7 @@ class EventTriggerView(PGChildNodeView):
                         etid,
                         did,
                         data['name'],
-                        icon="icon-%s" % self.node_type
+                        icon=self.node_icon
                     )
                 )
             else:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
index 9607c670d..a86e1fcf7 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
@@ -161,6 +161,7 @@ class ForeignServerView(PGChildNodeView):
     """
 
     node_type = blueprint.node_type
+    node_label = "Foreign Server"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -338,9 +339,7 @@ class ForeignServerView(PGChildNodeView):
             return internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the foreign server information.")
-            )
+            return gone(self.not_found_error)
 
         res['rows'][0]['is_sys_obj'] = (
             res['rows'][0]['fsrvid'] <= self.datlastsysoid)
@@ -619,9 +618,7 @@ class ForeignServerView(PGChildNodeView):
             if not status:
                 return internal_server_error(errormsg=res)
             if len(res['rows']) == 0:
-                return gone(
-                    gettext("Could not find the foreign server information.")
-                )
+                return gone(self.not_found_error)
 
             if res['rows'][0]['fsrvoptions'] is not None:
                 res['rows'][0]['fsrvoptions'] = tokenize_options(
@@ -724,9 +721,7 @@ class ForeignServerView(PGChildNodeView):
         if not status:
             return internal_server_error(errormsg=res)
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the foreign server information.")
-            )
+            return gone(self.not_found_error)
 
         is_valid_options = False
         if res['rows'][0]['fsrvoptions'] is not None:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
index fcec41f2f..eb5e52162 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
@@ -177,6 +177,7 @@ class UserMappingView(PGChildNodeView):
     """
 
     node_type = blueprint.node_type
+    node_label = "User Mapping"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -356,9 +357,7 @@ class UserMappingView(PGChildNodeView):
             return internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the user mapping information.")
-            )
+            return gone(self.not_found_error)
 
         res['rows'][0]['is_sys_obj'] = (
             res['rows'][0]['um_oid'] <= self.datlastsysoid)
@@ -633,9 +632,7 @@ class UserMappingView(PGChildNodeView):
             if not status:
                 return internal_server_error(errormsg=res)
             if len(res['rows']) == 0:
-                return gone(
-                    gettext("Could not find the user mapping information.")
-                )
+                return gone(self.not_found_error)
 
             if res['rows'][0]['umoptions'] is not None:
                 res['rows'][0]['umoptions'] = tokenize_options(
@@ -728,9 +725,7 @@ class UserMappingView(PGChildNodeView):
         if not status:
             return internal_server_error(errormsg=res)
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the user mapping information.")
-            )
+            return gone(self.not_found_error)
 
         is_valid_options = False
         if res['rows'][0]['umoptions'] is not None:
diff --git a/web/pgadmin/browser/utils.py b/web/pgadmin/browser/utils.py
index d14c8cf5c..544d52635 100644
--- a/web/pgadmin/browser/utils.py
+++ b/web/pgadmin/browser/utils.py
@@ -221,6 +221,8 @@ class NodeView(with_metaclass(MethodViewType, View)):
 
     # Inherited class needs to modify these parameters
     node_type = None
+    # Inherited class needs to modify these parameters
+    node_label = None
     # This must be an array object with attributes (type and id)
     parent_ids = []
     # This must be an array object with attributes (type and id)
@@ -686,3 +688,8 @@ class PGChildNodeView(NodeView):
             )
 
         return dependency
+
+    @property
+    def not_found_error(self):
+        return gettext("Could not find the specified {}.".format(
+            self.node_label.lower()))


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-08-04 06:40  Akshay Joshi <[email protected]>
  parent: Khushboo Vashi <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Akshay Joshi @ 2020-08-04 06:40 UTC (permalink / raw)
  To: Khushboo Vashi <[email protected]>; +Cc: pgadmin-hackers

Hi Khushboo

As per offline discussion, multiple developers declaring the constant for
the same string and error messages. To avoid that only one developer should
work on this task.
Suggestions:

   - We should have a common class for Constants (which are not module
   specific).
   - For module specific constants we should not declare them as Global
   variables if possible declare them as the Class variable.
   - For common error messages(if any) we can define functions in
   PGChildNodeView.

Please incorporate the changes send by Yogesh.

On Mon, Aug 3, 2020 at 1:36 PM Khushboo Vashi <
[email protected]> wrote:

> Hi,
>
> Please find the attached patch to fix the sonarqube code smells having the
> rule "String literals should not be duplicated".
>
> Thanks,
> Khushboo
>


-- 
*Thanks & Regards*
*Akshay Joshi*
*pgAdmin Hacker | Sr. Software Architect*
*EDB Postgres <http://edbpostgres.com>*

*Mobile: +91 976-788-8246*


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-08-19 08:31  Khushboo Vashi <[email protected]>
  parent: Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Khushboo Vashi @ 2020-08-19 08:31 UTC (permalink / raw)
  To: Akshay Joshi <[email protected]>; +Cc: pgadmin-hackers

Hi,

Please find the attached updated patch.


On Tue, Aug 4, 2020 at 12:10 PM Akshay Joshi <[email protected]>
wrote:

> Hi Khushboo
>
> As per offline discussion, multiple developers declaring the constant for
> the same string and error messages. To avoid that only one developer should
> work on this task.
> Suggestions:
>
>    - We should have a common class for Constants (which are not module
>    specific).
>
> Made a constant.py file which contains the common Constants.

>
>    - For module specific constants we should not declare them as Global
>    variables if possible declare them as the Class variable.
>
>
>    - For common error messages(if any) we can define functions in
>    PGChildNodeView.
>
> Already implemented.

> Please incorporate the changes send by Yogesh.
>
I will send another patch for Yogesh's changes as needed more changes.

Thanks,
Khushboo

>
> On Mon, Aug 3, 2020 at 1:36 PM Khushboo Vashi <
> [email protected]> wrote:
>
>> Hi,
>>
>> Please find the attached patch to fix the sonarqube code smells having
>> the rule "String literals should not be duplicated".
>>
>> Thanks,
>> Khushboo
>>
>
>
> --
> *Thanks & Regards*
> *Akshay Joshi*
> *pgAdmin Hacker | Sr. Software Architect*
> *EDB Postgres <http://edbpostgres.com>*
>
> *Mobile: +91 976-788-8246*
>


Attachments:

  [application/octet-stream] sonarqube_fixes_v1.patch (40.7K, 3-sonarqube_fixes_v1.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/__init__.py b/web/pgadmin/browser/__init__.py
index b1f2b5d92..9ee756374 100644
--- a/web/pgadmin/browser/__init__.py
+++ b/web/pgadmin/browser/__init__.py
@@ -47,6 +47,7 @@ from pgadmin.utils.master_password import validate_master_password, \
     set_masterpass_check_text, cleanup_master_password, get_crypt_key, \
     set_crypt_key, process_masterpass_disabled
 from pgadmin.model import User
+from pgadmin.utils.constants import APP_JS, PGADMIN_NODE
 
 try:
     from flask_security.views import default_render_json
@@ -57,6 +58,17 @@ except ImportError as e:
         from flask_security.views import _render_json as default_render_json
 
 MODULE_NAME = 'browser'
+BROWSER_STATIC = 'browser.static'
+JQUERY_ACIPLUGIN = 'jquery.aciplugin'
+BROWSER_INDEX = 'browser.index'
+PGADMIN_BROWSER = 'pgAdmin.Browser'
+PASS_ERROR_MSG = u'Your password has not been changed.'
+SMTP_SOCKET_ERROR = u'SMTP Socket error: {error}\n {pass_error}'.format(
+    error={}, pass_error=PASS_ERROR_MSG)
+SMTP_ERROR = u'SMTP error: {error}\n {pass_error}'.format(
+    error={}, pass_error=PASS_ERROR_MSG)
+PASS_ERROR = u'Error: {error}\n {pass_error}'.format(
+    error={}, pass_error=PASS_ERROR_MSG)
 
 
 class BrowserModule(PgAdminModule):
@@ -77,7 +89,7 @@ class BrowserModule(PgAdminModule):
             ('static', 'vendor/codemirror/addon/dialog/dialog.css'),
             ('static', context_menu_file),
             ('static', wcdocker_file),
-            ('browser.static', 'vendor/aciTree/css/aciTree.css')
+            (BROWSER_STATIC, 'vendor/aciTree/css/aciTree.css')
         ]:
             stylesheets.append(url_for(endpoint, filename=filename))
         return stylesheets
@@ -119,9 +131,9 @@ class BrowserModule(PgAdminModule):
             'preloaded': True
         })
         scripts.append({
-            'name': 'jquery.aciplugin',
+            'name': JQUERY_ACIPLUGIN,
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciPlugin.min'
             ),
             'deps': ['jquery'],
@@ -131,21 +143,21 @@ class BrowserModule(PgAdminModule):
         scripts.append({
             'name': 'jquery.acitree',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciTree' if
                 current_app.debug else 'vendor/aciTree/jquery.aciTree.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciTree',
             'preloaded': True
         })
         scripts.append({
             'name': 'jquery.acisortable',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciSortable.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciSortable',
             'when': None,
             'preloaded': True
@@ -153,10 +165,10 @@ class BrowserModule(PgAdminModule):
         scripts.append({
             'name': 'jquery.acifragment',
             'path': url_for(
-                'browser.static',
+                BROWSER_STATIC,
                 filename='vendor/aciTree/jquery.aciFragment.min'
             ),
-            'deps': ['jquery', 'jquery.aciplugin'],
+            'deps': ['jquery', JQUERY_ACIPLUGIN],
             'exports': 'aciPluginClass.plugins.aciFragment',
             'when': None,
             'preloaded': True
@@ -175,18 +187,18 @@ class BrowserModule(PgAdminModule):
 
         scripts.append({
             'name': 'pgadmin.browser.datamodel',
-            'path': url_for('browser.static', filename='js/datamodel'),
+            'path': url_for(BROWSER_STATIC, filename='js/datamodel'),
             'preloaded': True
         })
 
         for name, script in [
-            ['pgadmin.browser', 'js/browser'],
+            [PGADMIN_BROWSER, 'js/browser'],
             ['pgadmin.browser.endpoints', 'js/endpoints'],
             ['pgadmin.browser.error', 'js/error']
         ]:
             scripts.append({
                 'name': name,
-                'path': url_for('browser.index') + script,
+                'path': url_for(BROWSER_INDEX) + script,
                 'preloaded': True
             })
 
@@ -197,7 +209,7 @@ class BrowserModule(PgAdminModule):
         ]:
             scripts.append({
                 'name': name,
-                'path': url_for('browser.index') + script,
+                'path': url_for(BROWSER_INDEX) + script,
                 'preloaded': True,
                 'deps': ['pgadmin.browser.datamodel']
             })
@@ -208,12 +220,12 @@ class BrowserModule(PgAdminModule):
             ['pgadmin.browser.frame', 'js/frame']
         ]:
             scripts.append({
-                'name': name, 'path': url_for('browser.static', filename=end),
+                'name': name, 'path': url_for(BROWSER_STATIC, filename=end),
                 'preloaded': True})
 
         scripts.append({
             'name': 'pgadmin.browser.node.ui',
-            'path': url_for('browser.static', filename='js/node.ui'),
+            'path': url_for(BROWSER_STATIC, filename='js/node.ui'),
             'when': 'server_group'
         })
 
@@ -226,26 +238,26 @@ class BrowserModule(PgAdminModule):
             'file_items': [
                 MenuItem(
                     name='mnu_locklayout',
-                    module='pgAdmin.Browser',
+                    module=PGADMIN_BROWSER,
                     label=gettext('Lock Layout'),
                     priority=999,
                     menu_items=[MenuItem(
                         name='mnu_lock_none',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_none',
                         priority=0,
                         label=gettext('None'),
                         checked=True
                     ), MenuItem(
                         name='mnu_lock_docking',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_docking',
                         priority=1,
                         label=gettext('Prevent Docking'),
                         checked=False
                     ), MenuItem(
                         name='mnu_lock_full',
-                        module='pgAdmin.Browser',
+                        module=PGADMIN_BROWSER,
                         callback='mnu_lock_full',
                         priority=2,
                         label=gettext('Full Lock'),
@@ -263,7 +275,7 @@ class BrowserModule(PgAdminModule):
         Returns:
             list: a list of url endpoints exposed to the client.
         """
-        return ['browser.index', 'browser.nodes',
+        return [BROWSER_INDEX, 'browser.nodes',
                 'browser.check_master_password',
                 'browser.set_master_password',
                 'browser.reset_master_password',
@@ -358,15 +370,15 @@ class BrowserPluginModule(PgAdminModule):
 
         if self.module_use_template_javascript:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
-                'path': url_for('browser.index') +
-                        '%s/module' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
+                'path': url_for(BROWSER_INDEX
+                                ) + '%s/module' % self.node_type,
                 'when': self.script_load,
                 'is_template': True
             }])
         else:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
                 'path': url_for(
                     '%s.static' % self.name,
                     filename=('js/%s' % self.node_type)
@@ -412,7 +424,7 @@ class BrowserPluginModule(PgAdminModule):
             "_type": node_type,
             "_id": node_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % node_type
+            "module": PGADMIN_NODE % node_type
         }
         for key in kwargs:
             obj.setdefault(key, kwargs[key])
@@ -527,7 +539,7 @@ class BrowserPluginModule(PgAdminModule):
 
 def _get_logout_url():
     return '{0}?next={1}'.format(
-        url_for('security.logout'), url_for('browser.index'))
+        url_for('security.logout'), url_for(BROWSER_INDEX))
 
 
 @blueprint.route("/")
@@ -737,7 +749,7 @@ def utils():
             support_ssh_tunnel=config.SUPPORT_SSH_TUNNEL,
             logout_url=_get_logout_url()
         ),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/js/endpoints.js")
@@ -745,7 +757,7 @@ def utils():
 def exposed_urls():
     return make_response(
         render_template('browser/js/endpoints.js'),
-        200, {'Content-Type': 'application/javascript'}
+        200, {'Content-Type': APP_JS}
     )
 
 
@@ -755,7 +767,7 @@ def exposed_urls():
 def error_js():
     return make_response(
         render_template('browser/js/error.js', _=gettext),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/js/messages.js")
@@ -763,7 +775,7 @@ def error_js():
 def messages_js():
     return make_response(
         render_template('browser/js/messages.js', _=gettext),
-        200, {'Content-Type': 'application/javascript'})
+        200, {'Content-Type': APP_JS})
 
 
 @blueprint.route("/browser.css")
@@ -969,9 +981,7 @@ if hasattr(config, 'SECURITY_CHANGEABLE') and config.SECURITY_CHANGEABLE:
             except SOCKETErrorException as e:
                 # Handle socket errors which are not covered by SMTPExceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP Socket error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_SOCKET_ERROR).format(e),
                       'danger')
                 has_error = True
             except (SMTPConnectError, SMTPResponseException,
@@ -980,19 +990,14 @@ if hasattr(config, 'SECURITY_CHANGEABLE') and config.SECURITY_CHANGEABLE:
                     SMTPRecipientsRefused) as e:
                 # Handle smtp specific exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_ERROR).format(e),
                       'danger')
                 has_error = True
             except Exception as e:
                 # Handle other exceptions.
                 logging.exception(str(e), exc_info=True)
                 flash(
-                    gettext(
-                        u'Error: {}\n'
-                        u'Your password has not been changed.'
-                    ).format(e),
+                    gettext(PASS_ERROR).format(e),
                     'danger'
                 )
                 has_error = True
@@ -1078,9 +1083,7 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
                     # Handle socket errors which are not
                     # covered by SMTPExceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'SMTP Socket error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(SMTP_SOCKET_ERROR).format(e),
                           'danger')
                     has_error = True
                 except (SMTPConnectError, SMTPResponseException,
@@ -1090,17 +1093,13 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
 
                     # Handle smtp specific exceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'SMTP error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(SMTP_ERROR).format(e),
                           'danger')
                     has_error = True
                 except Exception as e:
                     # Handle other exceptions.
                     logging.exception(str(e), exc_info=True)
-                    flash(gettext(u'Error: {}\n'
-                                  u'Your password has not been changed.'
-                                  ).format(e),
+                    flash(gettext(PASS_ERROR).format(e),
                           'danger')
                     has_error = True
 
@@ -1149,9 +1148,7 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
             except SOCKETErrorException as e:
                 # Handle socket errors which are not covered by SMTPExceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP Socket error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_SOCKET_ERROR).format(e),
                       'danger')
                 has_error = True
             except (SMTPConnectError, SMTPResponseException,
@@ -1161,17 +1158,13 @@ if hasattr(config, 'SECURITY_RECOVERABLE') and config.SECURITY_RECOVERABLE:
 
                 # Handle smtp specific exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'SMTP error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(SMTP_ERROR).format(e),
                       'danger')
                 has_error = True
             except Exception as e:
                 # Handle other exceptions.
                 logging.exception(str(e), exc_info=True)
-                flash(gettext(u'Error: {}\n'
-                              u'Your password has not been changed.'
-                              ).format(e),
+                flash(gettext(PASS_ERROR).format(e),
                       'danger')
                 has_error = True
 
diff --git a/web/pgadmin/browser/collection.py b/web/pgadmin/browser/collection.py
index 6c1633451..61ee9d26e 100644
--- a/web/pgadmin/browser/collection.py
+++ b/web/pgadmin/browser/collection.py
@@ -16,6 +16,7 @@ from pgadmin.browser import BrowserPluginModule
 from pgadmin.browser.utils import PGChildModule
 from pgadmin.utils import PgAdminModule
 from pgadmin.utils.preferences import Preferences
+from pgadmin.utils.constants import PGADMIN_NODE
 
 
 @six.add_metaclass(ABCMeta)
@@ -58,15 +59,15 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
 
         if self.module_use_template_javascript:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
-                'path': url_for('browser.index') +
-                        '%s/module' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
+                'path': url_for('browser.index'
+                                ) + '%s/module' % self.node_type,
                 'when': self.script_load,
                 'is_template': True
             }])
         else:
             scripts.extend([{
-                'name': 'pgadmin.node.%s' % self.node_type,
+                'name': PGADMIN_NODE % self.node_type,
                 'path': url_for(
                     '%s.static' % self.name,
                     filename=('js/%s' % self.node_type)
@@ -93,7 +94,7 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
             "_type": self.node_type,
             "_id": node_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % self.node_type
+            "module": PGADMIN_NODE % self.node_type
         }
         for key in kwargs:
             obj.setdefault(key, kwargs[key])
@@ -108,7 +109,7 @@ class CollectionNodeModule(PgAdminModule, PGChildModule):
             "_type": 'coll-%s' % (self.node_type),
             "_id": parent_id,
             "_pid": parent_id,
-            "module": 'pgadmin.node.%s' % self.node_type,
+            "module": PGADMIN_NODE % self.node_type,
             "nodes": [self.node_type]
         }
 
diff --git a/web/pgadmin/browser/register_browser_preferences.py b/web/pgadmin/browser/register_browser_preferences.py
index 2857fc7cd..73cda77e2 100644
--- a/web/pgadmin/browser/register_browser_preferences.py
+++ b/web/pgadmin/browser/register_browser_preferences.py
@@ -7,6 +7,7 @@
 #
 ##########################################################################
 from flask_babelex import gettext
+from pgadmin.utils.constants import KEYBOARD_SHORTCUTS
 
 LOCK_LAYOUT_LEVEL = {
     'PREVENT_DOCKING': 'docking',
@@ -125,7 +126,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 66, 'char': 'b'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -140,7 +141,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 91, 'char': '['}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -155,7 +156,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 93, 'char': ']'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -170,7 +171,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 70, 'char': 'f'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -185,7 +186,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 79, 'char': 'o'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -200,7 +201,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 76, 'char': 'l'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -215,7 +216,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 72, 'char': 'h'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -230,7 +231,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 81, 'char': 'q'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -245,7 +246,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 86, 'char': 'v'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -260,7 +261,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 83, 'char': 's'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -275,7 +276,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 78, 'char': 'n'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -290,7 +291,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 69, 'char': 'e'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -305,7 +306,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 68, 'char': 'd'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -320,7 +321,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 77, 'char': 'm'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -335,7 +336,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 85, 'char': 'u'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -350,7 +351,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 67, 'char': 'c'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -365,7 +366,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 71, 'char': 'g'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -380,7 +381,7 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 93, 'char': ']'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -395,7 +396,7 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 91, 'char': '['}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -410,7 +411,7 @@ def register_browser_preferences(self):
             'control': False,
             'key': {'key_code': 116, 'char': 'F5'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
 
@@ -425,6 +426,6 @@ def register_browser_preferences(self):
             'control': True,
             'key': {'key_code': 65, 'char': 'a'}
         },
-        category_label=gettext('Keyboard shortcuts'),
+        category_label=gettext(KEYBOARD_SHORTCUTS),
         fields=fields
     )
diff --git a/web/pgadmin/browser/server_groups/__init__.py b/web/pgadmin/browser/server_groups/__init__.py
index b9733f845..3c4ec6831 100644
--- a/web/pgadmin/browser/server_groups/__init__.py
+++ b/web/pgadmin/browser/server_groups/__init__.py
@@ -24,9 +24,12 @@ from pgadmin.utils.menu import MenuItem
 from sqlalchemy import exc
 from pgadmin.model import db, ServerGroup
 
+SG_NOT_FOUND_ERROR = 'The specified server group could not be found.'
+
 
 class ServerGroupModule(BrowserPluginModule):
     _NODE_TYPE = "server_group"
+    node_icon = "icon-%s" % _NODE_TYPE
 
     def get_nodes(self, *arg, **kwargs):
         """Return a JSON document listing the server groups for the user"""
@@ -37,7 +40,7 @@ class ServerGroupModule(BrowserPluginModule):
             yield self.generate_browser_node(
                 "%d" % (group.id), None,
                 group.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type,
                 can_delete=True if idx > 0 else False
@@ -92,6 +95,9 @@ blueprint = ServerGroupModule(__name__)
 
 class ServerGroupView(NodeView):
     node_type = ServerGroupModule._NODE_TYPE
+    node_icon = ServerGroupModule.node_icon
+    node_label = "Server Group"
+
     parent_ids = []
     ids = [{'type': 'int', 'id': 'gid'}]
 
@@ -136,9 +142,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             try:
@@ -169,9 +173,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=417,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             try:
@@ -194,7 +196,7 @@ class ServerGroupView(NodeView):
                 gid,
                 None,
                 servergroup.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type,
                 can_delete=True  # This is user created hence can deleted
@@ -214,9 +216,7 @@ class ServerGroupView(NodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext(
-                    'The specified server group could not be found.'
-                )
+                errormsg=gettext(SG_NOT_FOUND_ERROR)
             )
         else:
             return ajax_response(
@@ -246,7 +246,7 @@ class ServerGroupView(NodeView):
                         "%d" % sg.id,
                         None,
                         sg.name,
-                        "icon-%s" % self.node_type,
+                        self.node_icon,
                         True,
                         self.node_type,
                         # This is user created hence can deleted
@@ -306,7 +306,7 @@ class ServerGroupView(NodeView):
                         "%d" % group.id,
                         None,
                         group.name,
-                        "icon-%s" % self.node_type,
+                        self.node_icon,
                         True,
                         self.node_type
                     )
@@ -322,7 +322,7 @@ class ServerGroupView(NodeView):
             nodes = self.blueprint.generate_browser_node(
                 "%d" % (group.id), None,
                 group.name,
-                "icon-%s" % self.node_type,
+                self.node_icon,
                 True,
                 self.node_type
             )
diff --git a/web/pgadmin/browser/server_groups/servers/__init__.py b/web/pgadmin/browser/server_groups/servers/__init__.py
index 7a0730b24..1a295f515 100644
--- a/web/pgadmin/browser/server_groups/servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/__init__.py
@@ -30,6 +30,7 @@ from pgadmin.utils.exception import CryptKeyMissing
 from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
 from psycopg2 import Error as psycopg2_Error, OperationalError
 from pgadmin.browser.server_groups.servers.utils import is_valid_ipaddress
+from pgadmin.utils.constants import UNAUTH_REQ
 
 
 def has_any(data, keys):
@@ -240,6 +241,7 @@ blueprint = ServerModule(__name__)
 
 class ServerNode(PGChildNodeView):
     node_type = ServerModule._NODE_TYPE
+    node_label = "Server"
 
     parent_ids = [{'type': 'int', 'id': 'gid'}]
     ids = [{'type': 'int', 'id': 'sid'}]
@@ -658,7 +660,7 @@ class ServerNode(PGChildNodeView):
             return make_json_response(
                 status=410,
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error_msg
             )
 
         sg = ServerGroup.query.filter_by(
@@ -1004,15 +1006,15 @@ class ServerNode(PGChildNodeView):
         # Fetch Server Details
         server = Server.query.filter_by(id=sid).first()
         if server is None:
-            return bad_request(gettext("Server not found."))
+            return bad_request(self.not_found_error_msg)
 
         if current_user and hasattr(current_user, 'id'):
             # Fetch User Details.
             user = User.query.filter_by(id=current_user.id).first()
             if user is None:
-                return unauthorized(gettext("Unauthorized request."))
+                return unauthorized(gettext(UNAUTH_REQ))
         else:
-            return unauthorized(gettext("Unauthorized request."))
+            return unauthorized(gettext(UNAUTH_REQ))
 
         data = {}
         if request.form:
@@ -1179,7 +1181,7 @@ class ServerNode(PGChildNodeView):
 
         server = Server.query.filter_by(id=sid).first()
         if server is None:
-            return bad_request(gettext("Server not found."))
+            return bad_request(self.not_found_error_msg)
 
         # Release Connection
         manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
@@ -1287,12 +1289,12 @@ class ServerNode(PGChildNodeView):
             # Fetch Server Details
             server = Server.query.filter_by(id=sid).first()
             if server is None:
-                return bad_request(gettext("Server not found."))
+                return bad_request(self.not_found_error_msg)
 
             # Fetch User Details.
             user = User.query.filter_by(id=current_user.id).first()
             if user is None:
-                return unauthorized(gettext("Unauthorized request."))
+                return unauthorized(gettext(UNAUTH_REQ))
 
             manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
             conn = manager.connection()
@@ -1407,7 +1409,7 @@ class ServerNode(PGChildNodeView):
         if server is None:
             return make_json_response(
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error_msg
             )
 
         try:
@@ -1491,7 +1493,7 @@ class ServerNode(PGChildNodeView):
         if server is None:
             return make_json_response(
                 success=0,
-                errormsg=gettext("Could not find the required server.")
+                errormsg=self.not_found_error_msg
             )
 
         try:
@@ -1566,7 +1568,7 @@ class ServerNode(PGChildNodeView):
             if server is None:
                 return make_json_response(
                     success=0,
-                    info=gettext("Could not find the required server.")
+                    info=self.not_found_error_msg
                 )
 
             setattr(server, 'password', None)
@@ -1605,7 +1607,7 @@ class ServerNode(PGChildNodeView):
             if server is None:
                 return make_json_response(
                     success=0,
-                    info=gettext("Could not find the required server.")
+                    info=self.not_found_error_msg
                 )
 
             setattr(server, 'tunnel_password', None)
diff --git a/web/pgadmin/browser/server_groups/servers/databases/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/__init__.py
index 5e2ed1c8a..bbe98f177 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/__init__.py
@@ -97,6 +97,7 @@ blueprint = DatabaseModule(__name__)
 
 class DatabaseView(PGChildNodeView):
     node_type = blueprint.node_type
+    node_label = "Database"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -380,7 +381,7 @@ class DatabaseView(PGChildNodeView):
                 status=200
             )
 
-        return gone(errormsg=_("Could not find the database on the server."))
+        return gone(errormsg=self.not_found_error_msg)
 
     @check_precondition(action="properties")
     def properties(self, gid, sid, did):
@@ -396,7 +397,7 @@ class DatabaseView(PGChildNodeView):
 
         if len(res['rows']) == 0:
             return gone(
-                _("Could not find the database on the server.")
+                self.not_found_error_msg
             )
 
         SQL = render_template(
@@ -801,7 +802,7 @@ class DatabaseView(PGChildNodeView):
 
         if len(rset['rows']) == 0:
             return gone(
-                _("Could not find the database on the server.")
+                self.not_found_error_msg
             )
 
         res = rset['rows'][0]
@@ -930,7 +931,7 @@ class DatabaseView(PGChildNodeView):
 
             if len(rset['rows']) == 0:
                 return gone(
-                    _("Could not find the database on the server.")
+                    self.not_found_error_msg
                 )
 
             data['old_name'] = (rset['rows'][0])['name']
@@ -1101,7 +1102,7 @@ class DatabaseView(PGChildNodeView):
 
         if len(res['rows']) == 0:
             return gone(
-                _("Could not find the database on the server.")
+                self.not_found_error_msg
             )
 
         SQL = render_template(
diff --git a/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
index 2b41d6c30..7b396011b 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/event_triggers/__init__.py
@@ -149,6 +149,7 @@ class EventTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
     """
 
     node_type = blueprint.node_type
+    node_icon = "icon-%s" % blueprint.node_type
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -258,7 +259,7 @@ class EventTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
                     row['oid'],
                     did,
                     row['name'],
-                    icon="icon-%s" % self.node_type
+                    self.node_icon
                 ))
 
         return make_json_response(
@@ -292,7 +293,7 @@ class EventTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
                     row['oid'],
                     did,
                     row['name'],
-                    icon="icon-%s" % self.node_type
+                    self.node_icon
                 ),
                 status=200
             )
@@ -431,7 +432,7 @@ class EventTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
                     etid,
                     did,
                     data['name'],
-                    icon="icon-%s" % self.node_type
+                    self.node_icon
                 )
             )
         except Exception as e:
@@ -478,7 +479,7 @@ class EventTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
                         etid,
                         did,
                         data['name'],
-                        icon="icon-%s" % self.node_type
+                        self.node_icon
                     )
                 )
             else:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
index d08bd66a3..e07c90692 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/__init__.py
@@ -163,6 +163,7 @@ class ForeignServerView(PGChildNodeView, SchemaDiffObjectCompare):
     """
 
     node_type = blueprint.node_type
+    node_label = "Foreign Server"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -356,9 +357,7 @@ class ForeignServerView(PGChildNodeView, SchemaDiffObjectCompare):
             return False, internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return False, gone(
-                gettext("Could not find the foreign server information.")
-            )
+            return False, gone(self.not_found_error_msg)
 
         res['rows'][0]['is_sys_obj'] = (
             res['rows'][0]['oid'] <= self.datlastsysoid)
@@ -651,9 +650,7 @@ class ForeignServerView(PGChildNodeView, SchemaDiffObjectCompare):
             if not status:
                 return internal_server_error(errormsg=res)
             if len(res['rows']) == 0:
-                return gone(
-                    gettext("Could not find the foreign server information.")
-                )
+                return gone(self.not_found_error_msg)
 
             if res['rows'][0]['fsrvoptions'] is not None:
                 res['rows'][0]['fsrvoptions'] = tokenize_options(
@@ -758,9 +755,7 @@ class ForeignServerView(PGChildNodeView, SchemaDiffObjectCompare):
         if not status:
             return internal_server_error(errormsg=res)
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the foreign server information.")
-            )
+            return gone(self.not_found_error_msg)
 
         if fid is None and 'fdwid' in res['rows'][0]:
             fid = res['rows'][0]['fdwid']
diff --git a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
index 075c94ee3..a22387dbb 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mappings/__init__.py
@@ -179,6 +179,7 @@ class UserMappingView(PGChildNodeView, SchemaDiffObjectCompare):
     """
 
     node_type = blueprint.node_type
+    node_label = "User Mapping"
 
     parent_ids = [
         {'type': 'int', 'id': 'gid'},
@@ -374,9 +375,7 @@ class UserMappingView(PGChildNodeView, SchemaDiffObjectCompare):
             return False, internal_server_error(errormsg=res)
 
         if len(res['rows']) == 0:
-            return False, gone(
-                gettext("Could not find the user mapping information.")
-            )
+            return False, gone(self.not_found_error_msg)
 
         res['rows'][0]['is_sys_obj'] = (
             res['rows'][0]['oid'] <= self.datlastsysoid)
@@ -672,9 +671,7 @@ class UserMappingView(PGChildNodeView, SchemaDiffObjectCompare):
             if not status:
                 return internal_server_error(errormsg=res)
             if len(res['rows']) == 0:
-                return gone(
-                    gettext("Could not find the user mapping information.")
-                )
+                return gone(self.not_found_error_msg)
 
             if res['rows'][0]['umoptions'] is not None:
                 res['rows'][0]['umoptions'] = tokenize_options(
@@ -769,9 +766,7 @@ class UserMappingView(PGChildNodeView, SchemaDiffObjectCompare):
         if not status:
             return internal_server_error(errormsg=res)
         if len(res['rows']) == 0:
-            return gone(
-                gettext("Could not find the user mapping information.")
-            )
+            return gone(self.not_found_error_msg)
 
         if fsid is None and 'fsid' in res['rows'][0]:
             fsid = res['rows'][0]['fsid']
diff --git a/web/pgadmin/browser/utils.py b/web/pgadmin/browser/utils.py
index e6e1c4664..fca2bdeae 100644
--- a/web/pgadmin/browser/utils.py
+++ b/web/pgadmin/browser/utils.py
@@ -221,6 +221,8 @@ class NodeView(with_metaclass(MethodViewType, View)):
 
     # Inherited class needs to modify these parameters
     node_type = None
+    # Inherited class needs to modify these parameters
+    node_label = None
     # This must be an array object with attributes (type and id)
     parent_ids = []
     # This must be an array object with attributes (type and id)
@@ -707,3 +709,8 @@ class PGChildNodeView(NodeView):
                 )
 
         return dependency
+
+    @property
+    def not_found_error_msg(self):
+        return gettext("Could not find the specified {}.".format(
+            self.node_label).lower())
diff --git a/web/pgadmin/utils/constants.py b/web/pgadmin/utils/constants.py
new file mode 100644
index 000000000..1663b7bcb
--- /dev/null
+++ b/web/pgadmin/utils/constants.py
@@ -0,0 +1,15 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2020, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Application wide constants."""
+
+APP_JS = 'application/javascript'
+PGADMIN_NODE = 'pgadmin.node.%s'
+KEYBOARD_SHORTCUTS = 'Keyboard shortcuts'
+UNAUTH_REQ = "Unauthorized request."


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-08-19 08:56  Akshay Joshi <[email protected]>
  parent: Khushboo Vashi <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Akshay Joshi @ 2020-08-19 08:56 UTC (permalink / raw)
  To: Khushboo Vashi <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Wed, Aug 19, 2020 at 2:01 PM Khushboo Vashi <
[email protected]> wrote:

> Hi,
>
> Please find the attached updated patch.
>
>
> On Tue, Aug 4, 2020 at 12:10 PM Akshay Joshi <
> [email protected]> wrote:
>
>> Hi Khushboo
>>
>> As per offline discussion, multiple developers declaring the constant for
>> the same string and error messages. To avoid that only one developer should
>> work on this task.
>> Suggestions:
>>
>>    - We should have a common class for Constants (which are not module
>>    specific).
>>
>> Made a constant.py file which contains the common Constants.
>
>>
>>    - For module specific constants we should not declare them as Global
>>    variables if possible declare them as the Class variable.
>>
>>
>>    - For common error messages(if any) we can define functions in
>>    PGChildNodeView.
>>
>> Already implemented.
>
>> Please incorporate the changes send by Yogesh.
>>
> I will send another patch for Yogesh's changes as needed more changes.
>
> Thanks,
> Khushboo
>
>>
>> On Mon, Aug 3, 2020 at 1:36 PM Khushboo Vashi <
>> [email protected]> wrote:
>>
>>> Hi,
>>>
>>> Please find the attached patch to fix the sonarqube code smells having
>>> the rule "String literals should not be duplicated".
>>>
>>> Thanks,
>>> Khushboo
>>>
>>
>>
>> --
>> *Thanks & Regards*
>> *Akshay Joshi*
>> *pgAdmin Hacker | Sr. Software Architect*
>> *EDB Postgres <http://edbpostgres.com>*
>>
>> *Mobile: +91 976-788-8246*
>>
>

-- 
*Thanks & Regards*
*Akshay Joshi*
*pgAdmin Hacker | Sr. Software Architect*
*EDB Postgres <http://edbpostgres.com>*

*Mobile: +91 976-788-8246*


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-09-03 11:09  Khushboo Vashi <[email protected]>
  parent: Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Khushboo Vashi @ 2020-09-03 11:09 UTC (permalink / raw)
  To: Akshay Joshi <[email protected]>; +Cc: pgadmin-hackers

Hi,

Please find more fixes for the sonarqube code smells having the rule "String
literals should not be duplicated".

Thanks,
Khushboo

On Wed, Aug 19, 2020 at 2:27 PM Akshay Joshi <[email protected]>
wrote:

> Thanks, patch applied.
>
> On Wed, Aug 19, 2020 at 2:01 PM Khushboo Vashi <
> [email protected]> wrote:
>
>> Hi,
>>
>> Please find the attached updated patch.
>>
>>
>> On Tue, Aug 4, 2020 at 12:10 PM Akshay Joshi <
>> [email protected]> wrote:
>>
>>> Hi Khushboo
>>>
>>> As per offline discussion, multiple developers declaring the constant
>>> for the same string and error messages. To avoid that only one developer
>>> should work on this task.
>>> Suggestions:
>>>
>>>    - We should have a common class for Constants (which are not module
>>>    specific).
>>>
>>> Made a constant.py file which contains the common Constants.
>>
>>>
>>>    - For module specific constants we should not declare them as Global
>>>    variables if possible declare them as the Class variable.
>>>
>>>
>>>    - For common error messages(if any) we can define functions in
>>>    PGChildNodeView.
>>>
>>> Already implemented.
>>
>>> Please incorporate the changes send by Yogesh.
>>>
>> I will send another patch for Yogesh's changes as needed more changes.
>>
>> Thanks,
>> Khushboo
>>
>>>
>>> On Mon, Aug 3, 2020 at 1:36 PM Khushboo Vashi <
>>> [email protected]> wrote:
>>>
>>>> Hi,
>>>>
>>>> Please find the attached patch to fix the sonarqube code smells having
>>>> the rule "String literals should not be duplicated".
>>>>
>>>> Thanks,
>>>> Khushboo
>>>>
>>>
>>>
>>> --
>>> *Thanks & Regards*
>>> *Akshay Joshi*
>>> *pgAdmin Hacker | Sr. Software Architect*
>>> *EDB Postgres <http://edbpostgres.com>*
>>>
>>> *Mobile: +91 976-788-8246*
>>>
>>
>
> --
> *Thanks & Regards*
> *Akshay Joshi*
> *pgAdmin Hacker | Sr. Software Architect*
> *EDB Postgres <http://edbpostgres.com>*
>
> *Mobile: +91 976-788-8246*
>


Attachments:

  [application/octet-stream] Sonar_Qube_Fixes.patch (22.3K, 3-Sonar_Qube_Fixes.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/utils.py b/web/pgadmin/browser/server_groups/servers/databases/schemas/utils.py
index 362209a11..10fce304f 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/utils.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/utils.py
@@ -19,6 +19,10 @@ from pgadmin.browser.collection import CollectionNodeModule
 from pgadmin.utils.ajax import internal_server_error
 from pgadmin.utils.driver import get_driver
 from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.constants import DATATYPE_TIME_WITH_TIMEZONE,\
+    DATATYPE_TIME_WITHOUT_TIMEZONE,\
+    DATATYPE_TIMESTAMP_WITH_TIMEZONE,\
+    DATATYPE_TIMESTAMP_WITHOUT_TIMEZONE
 
 
 class SchemaChildModule(CollectionNodeModule):
@@ -205,20 +209,22 @@ class DataTypeReader:
                                    1014, 'bpchar[]', 'character[]',
                                    1015, 'varchar[]', 'character varying[]'):
                 typeval = 'L'
-            elif elemoid_or_name in (1083, 'time', 'time without time zone',
+            elif elemoid_or_name in (1083, 'time',
+                                     DATATYPE_TIME_WITHOUT_TIMEZONE,
                                      1114, 'timestamp',
-                                     'timestamp without time zone',
+                                     DATATYPE_TIMESTAMP_WITHOUT_TIMEZONE,
                                      1115, 'timestamp[]',
                                      'timestamp without time zone[]',
                                      1183, 'time[]',
                                      'time without time zone[]',
                                      1184, 'timestamptz',
-                                     'timestamp with time zone',
+                                     DATATYPE_TIMESTAMP_WITH_TIMEZONE,
                                      1185, 'timestamptz[]',
                                      'timestamp with time zone[]',
                                      1186, 'interval',
                                      1187, 'interval[]', 'interval[]',
-                                     1266, 'timetz', 'time with time zone',
+                                     1266, 'timetz',
+                                     DATATYPE_TIME_WITH_TIMEZONE,
                                      1270, 'timetz', 'time with time zone[]'):
                 typeval = 'D'
             elif elemoid_or_name in (1231, 'numeric[]',
@@ -254,12 +260,12 @@ class DataTypeReader:
         elif (
             name == 'time' or
             name == 'timetz' or
-            name == 'time without time zone' or
-            name == 'time with time zone' or
+            name == DATATYPE_TIME_WITHOUT_TIMEZONE or
+            name == DATATYPE_TIME_WITH_TIMEZONE or
             name == 'timestamp' or
             name == 'timestamptz' or
-            name == 'timestamp without time zone' or
-            name == 'timestamp with time zone' or
+            name == DATATYPE_TIMESTAMP_WITHOUT_TIMEZONE or
+            name == DATATYPE_TIMESTAMP_WITH_TIMEZONE or
             name == 'bit' or
             name == 'bit varying' or
             name == 'varbit'
@@ -300,13 +306,13 @@ class DataTypeReader:
         """
         if name == 'char' and schema == 'pg_catalog':
             return '"char"' + array
-        elif name == 'time with time zone':
+        elif name == DATATYPE_TIME_WITH_TIMEZONE:
             return 'time' + length + ' with time zone' + array
-        elif name == 'time without time zone':
+        elif name == DATATYPE_TIME_WITHOUT_TIMEZONE:
             return 'time' + length + ' without time zone' + array
-        elif name == 'timestamp with time zone':
+        elif name == DATATYPE_TIMESTAMP_WITH_TIMEZONE:
             return 'timestamp' + length + ' with time zone' + array
-        elif name == 'timestamp without time zone':
+        elif name == DATATYPE_TIMESTAMP_WITHOUT_TIMEZONE:
             return 'timestamp' + length + ' without time zone' + array
         else:
             return name + length + array
diff --git a/web/pgadmin/misc/file_manager/__init__.py b/web/pgadmin/misc/file_manager/__init__.py
index 955f98073..a96d7b9ec 100644
--- a/web/pgadmin/misc/file_manager/__init__.py
+++ b/web/pgadmin/misc/file_manager/__init__.py
@@ -557,10 +557,9 @@ class Filemanager(object):
             Filemanager.check_access_permission(in_dir, path)
         except Exception as e:
             Filemanager.resume_windows_warning()
-            err_msg = gettext("Error: {0}").format(e)
             files = {
                 'Code': 0,
-                'Error': err_msg
+                'Error': str(e)
             }
             return files
 
@@ -660,9 +659,9 @@ class Filemanager(object):
             Filemanager.resume_windows_warning()
             if (hasattr(e, 'strerror') and
                     e.strerror == gettext('Permission denied')):
-                err_msg = gettext("Error: {0}").format(e.strerror)
+                err_msg = str(e.strerror)
             else:
-                err_msg = gettext("Error: {0}").format(e)
+                err_msg = str(e)
             files = {
                 'Code': 0,
                 'Error': err_msg
@@ -752,7 +751,7 @@ class Filemanager(object):
                 'Filename': split_path(path)[-1],
                 'FileType': '',
                 'Path': path,
-                'Error': gettext("Error: {0}").format(e),
+                'Error': str(e),
                 'Code': 0,
                 'Info': '',
                 'Properties': {
@@ -836,7 +835,7 @@ class Filemanager(object):
             Filemanager.check_access_permission(the_dir, new)
         except Exception as e:
             res = {
-                'Error': gettext("Error: {0}").format(e),
+                'Error': str(e),
                 'Code': 0
             }
             return res
@@ -897,7 +896,7 @@ class Filemanager(object):
             Filemanager.check_access_permission(the_dir, path)
         except Exception as e:
             res = {
-                'Error': gettext("Error: {0}").format(e),
+                'Error': str(e),
                 'Code': 0
             }
             return res
@@ -911,7 +910,7 @@ class Filemanager(object):
                 os.remove(orig_path)
         except Exception as e:
             code = 0
-            err_msg = gettext("Error: {0}").format(e.strerror)
+            err_msg = str(e.strerror)
 
         result = {
             'Path': path,
@@ -951,14 +950,13 @@ class Filemanager(object):
                     f.write(data)
         except Exception as e:
             code = 0
-            err_msg = gettext("Error: {0}").format(
-                e.strerror if hasattr(e, 'strerror') else gettext('Unknown'))
+            err_msg = str(e.strerror) if hasattr(e, 'strerror') else str(e)
 
         try:
             Filemanager.check_access_permission(the_dir, path)
         except Exception as e:
             res = {
-                'Error': gettext("Error: {0}").format(e),
+                'Error': str(e),
                 'Code': 0
             }
             return res
@@ -992,9 +990,9 @@ class Filemanager(object):
         except Exception as e:
             code = 0
             if hasattr(e, 'strerror'):
-                err_msg = gettext("Error: {0}").format(e.strerror)
+                err_msg = str(e.strerror)
             else:
-                err_msg = gettext("Error: {0}").format(e)
+                err_msg = str(e)
 
         result = {
             'Path': path,
@@ -1084,13 +1082,13 @@ class Filemanager(object):
             # we don't want to expose real path of file
             # so only show error message.
             if ex.strerror == 'Permission denied':
-                err_msg = gettext("Error: {0}").format(ex.strerror)
+                err_msg = str(ex.strerror)
             else:
-                err_msg = gettext("Error: {0}").format(str(ex))
+                err_msg = str(ex)
 
         except Exception as ex:
             status = False
-            err_msg = gettext("Error: {0}").format(str(ex))
+            err_msg = str(ex)
 
         # Remove root storage path from error message
         # when running in Server mode
@@ -1118,7 +1116,7 @@ class Filemanager(object):
                 path, name))
         except Exception as e:
             res = {
-                'Error': gettext("Error: {0}").format(e),
+                'Error': str(e),
                 'Code': 0
             }
             return res
@@ -1136,14 +1134,14 @@ class Filemanager(object):
                 os.mkdir(new_path)
             except Exception as e:
                 code = 0
-                err_msg = gettext("Error: {0}").format(e.strerror)
+                err_msg = str(e.strerror)
         else:
             new_path, new_name = self.get_new_name(the_dir, path, name)
             try:
                 os.mkdir(new_path)
             except Exception as e:
                 code = 0
-                err_msg = gettext("Error: {0}").format(e.strerror)
+                err_msg = str(e.strerror)
 
         result = {
             'Parent': path,
@@ -1172,7 +1170,7 @@ class Filemanager(object):
                 the_dir, "{}{}".format(path, path)
             )
         except Exception as e:
-            resp = Response(gettext("Error: {0}").format(e))
+            resp = Response(str(e))
             resp.headers['Content-Disposition'] = \
                 'attachment; filename=' + name
             return resp
@@ -1189,7 +1187,7 @@ class Filemanager(object):
         try:
             Filemanager.check_access_permission(the_dir, path)
         except Exception as e:
-            err_msg = gettext("Error: {0}").format(e)
+            err_msg = str(e)
             res['Code'] = 0
             res['Error'] = err_msg
         return res
diff --git a/web/pgadmin/tools/schema_diff/__init__.py b/web/pgadmin/tools/schema_diff/__init__.py
index babb05888..ea533eb6d 100644
--- a/web/pgadmin/tools/schema_diff/__init__.py
+++ b/web/pgadmin/tools/schema_diff/__init__.py
@@ -26,7 +26,8 @@ from pgadmin.tools.schema_diff.model import SchemaDiffModel
 from config import PG_DEFAULT_DRIVER
 from pgadmin.utils.driver import get_driver
 from pgadmin.utils.preferences import Preferences
-from pgadmin.utils.constants import PREF_LABEL_DISPLAY, MIMETYPE_APP_JS
+from pgadmin.utils.constants import PREF_LABEL_DISPLAY, MIMETYPE_APP_JS,\
+    ERROR_MSG_TRANS_ID_NOT_FOUND
 from sqlalchemy import or_
 
 MODULE_NAME = 'schema_diff'
@@ -439,7 +440,7 @@ def compare(trans_id, source_sid, source_did, target_sid, target_did):
     status, error_msg, diff_model_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg, status=404)
 
     # Server version compatibility check
@@ -566,7 +567,7 @@ def poll(trans_id):
     status, error_msg, diff_model_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg, status=404)
 
     msg, diff_percentage = diff_model_obj.get_comparison_info()
@@ -599,7 +600,7 @@ def ddl_compare(trans_id, source_sid, source_did, source_scid,
     status, error_msg, diff_model_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg, status=404)
 
     view = SchemaDiffRegistry.get_node_view(node_type)
diff --git a/web/pgadmin/tools/sqleditor/__init__.py b/web/pgadmin/tools/sqleditor/__init__.py
index 014192763..524d0294b 100644
--- a/web/pgadmin/tools/sqleditor/__init__.py
+++ b/web/pgadmin/tools/sqleditor/__init__.py
@@ -44,7 +44,8 @@ from pgadmin.tools.sqleditor.utils.query_tool_fs_utils import \
     read_file_generator
 from pgadmin.tools.sqleditor.utils.filter_dialog import FilterDialog
 from pgadmin.tools.sqleditor.utils.query_history import QueryHistory
-from pgadmin.utils.constants import MIMETYPE_APP_JS, SERVER_CONNECTION_CLOSED
+from pgadmin.utils.constants import MIMETYPE_APP_JS, SERVER_CONNECTION_CLOSED,\
+    ERROR_MSG_TRANS_ID_NOT_FOUND
 
 MODULE_NAME = 'sqleditor'
 
@@ -139,17 +140,13 @@ def check_transaction_status(trans_id):
     """
 
     if 'gridData' not in session:
-        return False, gettext(
-            'Transaction ID not found in the session.'
-        ), None, None, None
+        return False, ERROR_MSG_TRANS_ID_NOT_FOUND, None, None, None
 
     grid_data = session['gridData']
 
     # Return from the function if transaction id not found
     if str(trans_id) not in grid_data:
-        return False, gettext(
-            'Transaction ID not found in the session.'
-        ), None, None, None
+        return False, ERROR_MSG_TRANS_ID_NOT_FOUND, None, None, None
 
     # Fetch the object for the specified transaction id.
     # Use pickle.loads function to get the command object
@@ -199,7 +196,7 @@ def start_view_data(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -345,7 +342,7 @@ def poll(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -531,7 +528,7 @@ def fetch(trans_id, fetch_all=None):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -677,7 +674,7 @@ def save(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -750,7 +747,7 @@ def append_filter_inclusive(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -805,7 +802,7 @@ def append_filter_exclusive(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -857,7 +854,7 @@ def remove_filter(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -901,7 +898,7 @@ def set_limit(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -984,7 +981,7 @@ def cancel_transaction(trans_id):
     if is_error:
         return make_json_response(
             success=0,
-            errormsg=gettext('Transaction ID not found in the session.'),
+            errormsg=ERROR_MSG_TRANS_ID_NOT_FOUND,
             info='DATAGRID_TRANSACTION_REQUIRED', status=404)
 
     # Fetch the object for the specified transaction id.
@@ -1043,7 +1040,7 @@ def get_object_name(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -1079,7 +1076,7 @@ def set_auto_commit(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -1124,7 +1121,7 @@ def set_auto_rollback(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
@@ -1176,7 +1173,7 @@ def auto_complete(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
-    if error_msg == gettext('Transaction ID not found in the session.'):
+    if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
         return make_json_response(success=0, errormsg=error_msg,
                                   info='DATAGRID_TRANSACTION_REQUIRED',
                                   status=404)
diff --git a/web/pgadmin/tools/sqleditor/utils/filter_dialog.py b/web/pgadmin/tools/sqleditor/utils/filter_dialog.py
index 62baab3de..77efd80a8 100644
--- a/web/pgadmin/tools/sqleditor/utils/filter_dialog.py
+++ b/web/pgadmin/tools/sqleditor/utils/filter_dialog.py
@@ -16,6 +16,7 @@ from pgadmin.utils.ajax import make_json_response, internal_server_error
 from pgadmin.tools.sqleditor.utils.update_session_grid_transaction import \
     update_session_grid_transaction
 from pgadmin.utils.exception import ConnectionLost, SSHTunnelConnectionLost
+from pgadmin.utils.constants import ERROR_MSG_TRANS_ID_NOT_FOUND
 
 
 class FilterDialog(object):
@@ -23,7 +24,7 @@ class FilterDialog(object):
     def get(*args):
         """To fetch the current sorted columns"""
         status, error_msg, conn, trans_obj, session_obj = args
-        if error_msg == gettext('Transaction ID not found in the session.'):
+        if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
             return make_json_response(
                 success=0,
                 errormsg=error_msg,
@@ -76,7 +77,7 @@ class FilterDialog(object):
         else:
             data = request.args or request.form
 
-        if error_msg == gettext('Transaction ID not found in the session.'):
+        if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
             return make_json_response(
                 success=0,
                 errormsg=error_msg,
diff --git a/web/pgadmin/tools/sqleditor/utils/start_running_query.py b/web/pgadmin/tools/sqleditor/utils/start_running_query.py
index ab845cc51..7bac78ba5 100644
--- a/web/pgadmin/tools/sqleditor/utils/start_running_query.py
+++ b/web/pgadmin/tools/sqleditor/utils/start_running_query.py
@@ -27,6 +27,7 @@ from pgadmin.utils.ajax import make_json_response, internal_server_error
 from pgadmin.utils.driver import get_driver
 from pgadmin.utils.exception import ConnectionLost, SSHTunnelConnectionLost,\
     CryptKeyMissing
+from pgadmin.utils.constants import ERROR_MSG_TRANS_ID_NOT_FOUND
 
 
 class StartRunningQuery:
@@ -173,7 +174,7 @@ class StartRunningQuery:
         if 'gridData' not in http_session:
             return make_json_response(
                 success=0,
-                errormsg=gettext('Transaction ID not found in the session.'),
+                errormsg=ERROR_MSG_TRANS_ID_NOT_FOUND,
                 info='DATAGRID_TRANSACTION_REQUIRED', status=404
             )
         grid_data = http_session['gridData']
@@ -181,7 +182,7 @@ class StartRunningQuery:
         if str(transaction_id) not in grid_data:
             return make_json_response(
                 success=0,
-                errormsg=gettext('Transaction ID not found in the session.'),
+                errormsg=ERROR_MSG_TRANS_ID_NOT_FOUND,
                 info='DATAGRID_TRANSACTION_REQUIRED',
                 status=404
             )
diff --git a/web/pgadmin/utils/constants.py b/web/pgadmin/utils/constants.py
index 88ae50de2..4ef032892 100644
--- a/web/pgadmin/utils/constants.py
+++ b/web/pgadmin/utils/constants.py
@@ -29,3 +29,14 @@ PGADMIN_NODE = 'pgadmin.node.%s'
 UNAUTH_REQ = "Unauthorized request."
 SERVER_CONNECTION_CLOSED = gettext(
     'Not connected to server or connection with the server has been closed.')
+
+# Data Types
+DATATYPE_TIME_WITH_TIMEZONE = 'time with time zone'
+DATATYPE_TIME_WITHOUT_TIMEZONE = 'time without time zone'
+
+DATATYPE_TIMESTAMP_WITH_TIMEZONE = 'timestamp with time zone'
+DATATYPE_TIMESTAMP_WITHOUT_TIMEZONE = 'timestamp without time zone'
+
+# Error Messages
+ERROR_MSG_TRANS_ID_NOT_FOUND = gettext(
+    'Transaction ID not found in the session.')


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin4][Patch] - SonarQube Fixes
@ 2020-09-03 13:26  Akshay Joshi <[email protected]>
  parent: Khushboo Vashi <[email protected]>
  0 siblings, 0 replies; 11+ messages in thread

From: Akshay Joshi @ 2020-09-03 13:26 UTC (permalink / raw)
  To: Khushboo Vashi <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Thu, Sep 3, 2020 at 4:39 PM Khushboo Vashi <
[email protected]> wrote:

> Hi,
>
> Please find more fixes for the sonarqube code smells having the rule "String
> literals should not be duplicated".
>
> Thanks,
> Khushboo
>
> On Wed, Aug 19, 2020 at 2:27 PM Akshay Joshi <
> [email protected]> wrote:
>
>> Thanks, patch applied.
>>
>> On Wed, Aug 19, 2020 at 2:01 PM Khushboo Vashi <
>> [email protected]> wrote:
>>
>>> Hi,
>>>
>>> Please find the attached updated patch.
>>>
>>>
>>> On Tue, Aug 4, 2020 at 12:10 PM Akshay Joshi <
>>> [email protected]> wrote:
>>>
>>>> Hi Khushboo
>>>>
>>>> As per offline discussion, multiple developers declaring the constant
>>>> for the same string and error messages. To avoid that only one developer
>>>> should work on this task.
>>>> Suggestions:
>>>>
>>>>    - We should have a common class for Constants (which are not module
>>>>    specific).
>>>>
>>>> Made a constant.py file which contains the common Constants.
>>>
>>>>
>>>>    - For module specific constants we should not declare them as
>>>>    Global variables if possible declare them as the Class variable.
>>>>
>>>>
>>>>    - For common error messages(if any) we can define functions in
>>>>    PGChildNodeView.
>>>>
>>>> Already implemented.
>>>
>>>> Please incorporate the changes send by Yogesh.
>>>>
>>> I will send another patch for Yogesh's changes as needed more changes.
>>>
>>> Thanks,
>>> Khushboo
>>>
>>>>
>>>> On Mon, Aug 3, 2020 at 1:36 PM Khushboo Vashi <
>>>> [email protected]> wrote:
>>>>
>>>>> Hi,
>>>>>
>>>>> Please find the attached patch to fix the sonarqube code smells having
>>>>> the rule "String literals should not be duplicated".
>>>>>
>>>>> Thanks,
>>>>> Khushboo
>>>>>
>>>>
>>>>
>>>> --
>>>> *Thanks & Regards*
>>>> *Akshay Joshi*
>>>> *pgAdmin Hacker | Sr. Software Architect*
>>>> *EDB Postgres <http://edbpostgres.com>*
>>>>
>>>> *Mobile: +91 976-788-8246*
>>>>
>>>
>>
>> --
>> *Thanks & Regards*
>> *Akshay Joshi*
>> *pgAdmin Hacker | Sr. Software Architect*
>> *EDB Postgres <http://edbpostgres.com>*
>>
>> *Mobile: +91 976-788-8246*
>>
>

-- 
*Thanks & Regards*
*Akshay Joshi*
*pgAdmin Hacker | Sr. Software Architect*
*EDB Postgres <http://edbpostgres.com>*

*Mobile: +91 976-788-8246*


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* [pgAdmin]:SonarQube fixes.
@ 2021-04-07 11:23  Pradip Parkale <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Pradip Parkale @ 2021-04-07 11:23 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Hackers,

Please find the attached patch for few SonaQube Fixes.

I have fixed the issues in the below files.

   1. foreign_key.js
   2. exclusion_constraint.js
   3. function.js


-- 
Thanks & Regards,
Pradip Parkale
Software Engineer | EnterpriseDB Corporation


Attachments:

  [application/octet-stream] SonarQube.patch (7.5K, 3-SonarQube.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js
index 9feea15ec..536dc9472 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js
@@ -91,8 +91,6 @@ define('pgadmin.node.function', [
       }
       return true;
     },
-    validate: function() {
-    },
   });
 
   if (!pgBrowser.Nodes['function']) {
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js
index 91579c07a..2ac92bf14 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js
@@ -125,42 +125,14 @@ define('pgadmin.node.exclusion_constraint', [
         onText: 'ASC',
         offText: 'DESC',
       },
-      editable: function(m) {
-        if (m instanceof Backbone.Collection) {
-          return true;
-        } else if ((_.has(m.collection, 'handler') &&
-          !_.isUndefined(m.collection.handler) &&
-            !_.isUndefined(m.collection.handler.get('oid')))) {
-          return false;
-        } else if (m.top.get('amname') === 'btree') {
-          m.set('is_sort_nulls_applicable', true);
-          return true;
-        } else {
-          m.set('is_sort_nulls_applicable', false);
-          return false;
-        }
-      },
+      editable: 'isEditable',
     },{
       id: 'nulls_order', label: gettext('NULLs order'), type:'switch',
       options: {
         onText: 'FIRST',
         offText: 'LAST',
       },
-      editable: function(m) {
-        if (m instanceof Backbone.Collection) {
-          return true;
-        } else if ((_.has(m.collection, 'handler') &&
-          !_.isUndefined(m.collection.handler) &&
-            !_.isUndefined(m.collection.handler.get('oid')))) {
-          return false;
-        } else if (m.top.get('amname') === 'btree') {
-          m.set('is_sort_nulls_applicable', true);
-          return true;
-        } else {
-          m.set('is_sort_nulls_applicable', false);
-          return false;
-        }
-      },
+      editable: 'isEditable',
     },{
       id: 'operator', label: gettext('Operator'), type: 'text',
       node: 'table', url: 'get_operator',
@@ -220,6 +192,21 @@ define('pgadmin.node.exclusion_constraint', [
       }),
     },
     ],
+    isEditable: function(m) {
+      if (m instanceof Backbone.Collection) {
+        return true;
+      } else if ((_.has(m.collection, 'handler') &&
+        !_.isUndefined(m.collection.handler) &&
+        !_.isUndefined(m.collection.handler.get('oid')))) {
+        return false;
+      } else if (m.top.get('amname') === 'btree') {
+        m.set('is_sort_nulls_applicable', true);
+        return true;
+      } else {
+        m.set('is_sort_nulls_applicable', false);
+        return false;
+      }
+    },
     validate: function() {
       this.errorModel.clear();
       var operator = this.get('operator'),
@@ -775,22 +762,14 @@ define('pgadmin.node.exclusion_constraint', [
             },
           }),
           select2:{allowClear:true},
-          readonly: function(m) {
-            return ((_.has(m, 'handler') &&
-              !_.isUndefined(m.handler) &&
-                !_.isUndefined(m.get('oid'))) || (_.isFunction(m.isNew) && !m.isNew()));
-          },
+          readonly: 'isReadonly',
         },{
           id: 'fillfactor', label: gettext('Fill factor'),
           type: 'int', group: gettext('Definition'), allowNull: true,
         },{
           id: 'condeferrable', label: gettext('Deferrable?'),
           type: 'switch', group: gettext('Definition'), deps: ['index'],
-          readonly: function(m) {
-            return ((_.has(m, 'handler') &&
-              !_.isUndefined(m.handler) &&
-                !_.isUndefined(m.get('oid'))) || (_.isFunction(m.isNew) && !m.isNew()));
-          },
+          readonly: 'isReadonly',
         },{
           id: 'condeferred', label: gettext('Deferred?'),
           type: 'switch', group: gettext('Definition'),
@@ -817,11 +796,7 @@ define('pgadmin.node.exclusion_constraint', [
         },{
           id: 'indconstraint', label: gettext('Constraint'), cell: 'string',
           type: 'multiline', mode: ['create', 'edit', 'properties'], editable: false,
-          group: gettext('Definition'), readonly: function(m) {
-            return ((_.has(m, 'handler') &&
-              !_.isUndefined(m.handler) &&
-                !_.isUndefined(m.get('oid'))) || (_.isFunction(m.isNew) && !m.isNew()));
-          },
+          group: gettext('Definition'), readonly: 'isReadonly',
         },{
           id: 'columns', label: gettext('Columns/Expressions'),
           type: 'collection', group: gettext('Columns'),
@@ -834,11 +809,7 @@ define('pgadmin.node.exclusion_constraint', [
           },
           control: ExclusionConstraintColumnControl,
           model: ExclusionConstraintColumnModel,
-          readonly: function(m) {
-            return ((_.has(m, 'handler') &&
-              !_.isUndefined(m.handler) &&
-                !_.isUndefined(m.get('oid'))) || (_.isFunction(m.isNew) && !m.isNew()));
-          },
+          readonly: 'isReadonly',
           cell: Backgrid.StringCell.extend({
             initialize: function() {
               Backgrid.StringCell.prototype.initialize.apply(this, arguments);
@@ -1041,6 +1012,11 @@ define('pgadmin.node.exclusion_constraint', [
             return !m.isNew();
           },
         }],
+        isReadonly: function(m) {
+          return ((_.has(m, 'handler') &&
+              !_.isUndefined(m.handler) &&
+              !_.isUndefined(m.get('oid'))) || (_.isFunction(m.isNew) && !m.isNew()));
+        },
         validate: function() {
           this.errorModel.clear();
           var columns = this.get('columns'),
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
index 6819025a5..e8d04e336 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
@@ -505,8 +505,6 @@ define('pgadmin.node.foreign_key', [
 
             newRow.addClass('new');
             $(newRow).pgMakeVisible('backform-tab');
-          } else {
-            //delete m;
           }
         }
         return false;
@@ -1083,6 +1081,15 @@ define('pgadmin.node.foreign_key', [
           },
         },
         ],
+        isReadonly:function(m) {
+          // If we are in table edit mode then
+          if (_.has(m, 'handler') && !_.isUndefined(m.handler)) {
+            // If OID is undefined then user is trying to add
+            // new constraint which should allowed for Unique
+            return !_.isUndefined(m.get('oid'));
+          }
+          return !m.isNew();
+        },
         validate: function() {
           var columns = this.get('columns'),
             msg;


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin]:SonarQube fixes.
@ 2021-04-08 06:58  Akshay Joshi <[email protected]>
  parent: Pradip Parkale <[email protected]>
  0 siblings, 0 replies; 11+ messages in thread

From: Akshay Joshi @ 2021-04-08 06:58 UTC (permalink / raw)
  To: Pradip Parkale <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Wed, Apr 7, 2021 at 4:54 PM Pradip Parkale <
[email protected]> wrote:

> Hi Hackers,
>
> Please find the attached patch for few SonaQube Fixes.
>
> I have fixed the issues in the below files.
>
>    1. foreign_key.js
>    2. exclusion_constraint.js
>    3. function.js
>
>
> --
> Thanks & Regards,
> Pradip Parkale
> Software Engineer | EnterpriseDB Corporation
>


-- 
*Thanks & Regards*
*Akshay Joshi*
*pgAdmin Hacker | Principal Software Architect*
*EDB Postgres <http://edbpostgres.com>*

*Mobile: +91 976-788-8246*


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* [pgAdmin]:SonarQube Fixes
@ 2021-04-20 08:19  Pradip Parkale <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Pradip Parkale @ 2021-04-20 08:19 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Hackers,

Please find attached the patch for some SonarQube fixes.

-- 
Thanks & Regards,
Pradip Parkale
Software Engineer | EnterpriseDB Corporation


Attachments:

  [application/octet-stream] SonarQube.patch (24.2K, 3-SonarQube.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js b/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
index b35422c8d..fcd514f19 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
@@ -189,12 +189,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         },{
           id: 'laninl', label: gettext('Inline function'), type: 'text', control: 'node-ajax-options',
@@ -214,12 +209,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         },{
           id: 'lanval', label: gettext('Validator function'), type: 'text', control: 'node-ajax-options',
@@ -239,12 +229,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         }, {
           id: 'lanacl', label: gettext('Privileges'), type: 'collection',
@@ -292,6 +277,12 @@ define('pgadmin.node.language', [
 
           return null;
         },
+        isDisabled: function(m){
+          if (m.isNew()) {
+            return m.get('template_list').indexOf(m.get('name')) != -1;
+          }
+          return false;
+        },
       }),
     });
   }
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
index 97005db23..09ef94a75 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
@@ -600,12 +600,7 @@ define('pgadmin.node.column', [
         },{
           id: 'seqstart', label: gettext('Start'), type: 'int',
           mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
-          disabled: function(m) {
-            let isIdentity = m.get('attidentity');
-            if(!_.isUndefined(isIdentity) && !_.isNull(isIdentity) && !_.isEmpty(isIdentity))
-              return false;
-            return true;
-          }, deps: ['attidentity', 'colconstype'],
+          disabled: 'isIdentityColumn', deps: ['attidentity', 'colconstype'],
           visible: 'isTypeIdentity',
         },{
           id: 'seqmin', label: gettext('Minimum'), type: 'int',
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
index e8d04e336..71b5270f6 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
@@ -737,15 +737,7 @@ define('pgadmin.node.foreign_key', [
         },{
           id: 'condeferrable', label: gettext('Deferrable?'),
           type: 'switch', group: gettext('Definition'),
-          readonly: function(m) {
-            // If we are in table edit mode then
-            if (_.has(m, 'handler') && !_.isUndefined(m.handler)) {
-              // If OID is undefined then user is trying to add
-              // new constraint which should allowed for Unique
-              return !_.isUndefined(m.get('oid'));
-            }
-            return !m.isNew();
-          },
+          readonly: 'isReadonly',
         },{
           id: 'condeferred', label: gettext('Deferred?'),
           type: 'switch', group: gettext('Definition'),
@@ -762,15 +754,7 @@ define('pgadmin.node.foreign_key', [
               return true;
             }
           },
-          readonly: function(m) {
-            // If we are in table edit mode then
-            if (_.has(m, 'handler') && !_.isUndefined(m.handler)) {
-              // If OID is undefined then user is trying to add
-              // new constraint which should allowed for Unique
-              return !_.isUndefined(m.get('oid'));
-            }
-            return !m.isNew();
-          },
+          readonly: 'isReadOnly',
         },{
           id: 'confmatchtype', label: gettext('Match type'),
           type: 'switch', group: gettext('Definition'),
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
index e236230a3..219859985 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
@@ -223,7 +223,6 @@ function(
                     t.unload(i);
                   });
               }},
-            function() {}
           );
         },
         reset_table_stats: function(args) {
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
index 2234b2ddf..ed5836152 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
@@ -374,14 +374,7 @@ define('pgadmin.node.table', [
         },{
           id: 'is_partitioned', label:gettext('Partitioned table?'), cell: 'switch',
           type: 'switch', mode: ['properties', 'create', 'edit'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           readonly: function(m) {
             if (!m.isNew())
               return true;
@@ -483,14 +476,7 @@ define('pgadmin.node.table', [
           id: 'rlspolicy', label: gettext('RLS Policy?'), cell: 'switch',
           type: 'switch', mode: ['properties','edit', 'create'],
           group: gettext('advanced'),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 90600)
-              return true;
-
-            return false;
-          },
+          visible: 'isSupported',
           disabled: function(m) {
             if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
               && !_.isUndefined(m.node_info.server.version) &&
@@ -504,14 +490,7 @@ define('pgadmin.node.table', [
           id: 'forcerlspolicy', label: gettext('Force RLS Policy?'), cell: 'switch',
           type: 'switch', mode: ['properties','edit', 'create'], deps: ['rlspolicy'],
           group: gettext('advanced'),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 90600)
-              return true;
-
-            return false;
-          },
+          visible: 'isSupported',
           disabled: function(m) {
             if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
               && !_.isUndefined(m.node_info.server.version) &&
@@ -843,31 +822,16 @@ define('pgadmin.node.table', [
           id: 'fillfactor', label: gettext('Fill factor'), type: 'int',
           mode: ['create', 'edit'], min: 10, max: 100,
           group: gettext('advanced'),
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },{
           id: 'toast_tuple_target', label: gettext('Toast tuple target'), type: 'int',
           mode: ['create', 'edit'], min: 128, min_version: 110000,
           group: gettext('advanced'),
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },{
           id: 'parallel_workers', label: gettext('Parallel workers'), type: 'int',
           mode: ['create', 'edit'], group: gettext('advanced'), min_version: 90600,
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },
         {
           id: 'relhasoids', label: gettext('Has OIDs?'), cell: 'switch',
@@ -970,14 +934,7 @@ define('pgadmin.node.table', [
             return options;
           },
           mode:['create'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (!m.get('is_partitioned'))
               return true;
@@ -1027,14 +984,7 @@ define('pgadmin.node.table', [
             );
 
           },
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (m.get('partition_keys') && m.get('partition_keys').models.length > 0) {
               setTimeout(function () {
@@ -1047,14 +997,7 @@ define('pgadmin.node.table', [
         },{
           id: 'partition_scheme', label: gettext('Partition Scheme'),
           type: 'note', group: 'partition', mode: ['edit'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (!m.isNew()) {
               this.text = m.get('partition_scheme');
@@ -1077,14 +1020,7 @@ define('pgadmin.node.table', [
             gettext('Let\'s say, we want to create a partition table based per year for the column \'saledate\', having datatype \'date/timestamp\', then we need to specify the expression as \'extract(YEAR from saledate)\' as partition key.'),
             '</li></ul>',
           ].join(''),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
         }, {
           id: 'partitions', label:gettext('Partitions'),
           model: Backform.PartitionsModel,
@@ -1138,14 +1074,7 @@ define('pgadmin.node.table', [
               return true;
             return false;
           },
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (m.isNew() && m.get('partitions') && m.get('partitions').models.length > 0) {
               setTimeout(function () {
@@ -1181,14 +1110,7 @@ define('pgadmin.node.table', [
             gettext('Enabled for hash partition.'),
             '</li></ul>',
           ].join(''),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
         },{
           // Here - we will create tab control for storage parameters
           // (auto vacuum).
@@ -1276,6 +1198,23 @@ define('pgadmin.node.table', [
           }
           return null;
         },
+        isVersionGreaterThan96: function(m) {
+          if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
+            && !_.isUndefined(m.node_info.server.version) &&
+              m.node_info.server.version >= 100000)
+            return true;
+
+          return false;
+        },
+        isSupported: function(m) {
+          // Enable when server version is greater than 95.
+          if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
+            && !_.isUndefined(m.node_info.server.version) &&
+              m.node_info.server.version >= 90600)
+            return true;
+
+          return false;
+        },
         // We will disable everything if we are under catalog node
         inSchema: function() {
           if(this.node_info &&  'catalog' in this.node_info)
@@ -1284,6 +1223,12 @@ define('pgadmin.node.table', [
           }
           return false;
         },
+        isDisabled:function(m) {
+          if(m.get('is_partitioned')) {
+            return true;
+          }
+          return m.inSchema();
+        },
         isInheritedTable: function(m) {
           if(!m.inSchema.apply(this, [m])) {
             // Either of_types or coll_inherits has value
diff --git a/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js b/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
index dcb99eb26..92a02735a 100644
--- a/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
+++ b/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
@@ -515,13 +515,7 @@ define('pgadmin.node.role', [
           filter: function(d) {
             return this.model.isNew() || (this.model.get('rolname') != d.label);
           },
-          helpMessage: function(m) {
-            if (m.has('read_only') && m.get('read_only') == false) {
-              return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
-            } else {
-              return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
-            }
-          },
+          helpMessage: 'helpMessage',
         },
         {
           id: 'rolmembers', label: gettext('Members'), type: 'collection', group: gettext('Membership'),
@@ -541,13 +535,7 @@ define('pgadmin.node.role', [
           filter: function(d) {
             return this.model.isNew() || (this.model.get('rolname') != d.label);
           },
-          helpMessage: function(m) {
-            if (m.has('read_only') && m.get('read_only') == false) {
-              return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
-            } else {
-              return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
-            }
-          },
+          helpMessage: 'helpMessage',
         },
         {
           id: 'variables', label: '', type: 'collection',
@@ -603,6 +591,13 @@ define('pgadmin.node.role', [
 
           return null;
         },
+        helpMessage: function(m) {
+          if (m.has('read_only') && m.get('read_only') == false) {
+            return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
+          } else {
+            return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
+          }
+        },
       }),
     });
   }
diff --git a/web/pgadmin/browser/static/js/node.js b/web/pgadmin/browser/static/js/node.js
index 7c2f666e0..1c5af3f57 100644
--- a/web/pgadmin/browser/static/js/node.js
+++ b/web/pgadmin/browser/static/js/node.js
@@ -1786,7 +1786,6 @@ define('pgadmin.browser.node', [
         },
         self = this,
         priority = -Infinity;
-
       var treeInfo = (_.isUndefined(item) || _.isNull(item)) ?
         info || {} : this.getTreeNodeHierarchy(item);
       var actionType = type in opURL ? opURL[type] : type;
diff --git a/web/pgadmin/tools/backup/__init__.py b/web/pgadmin/tools/backup/__init__.py
index aacb2e5d4..11536a299 100644
--- a/web/pgadmin/tools/backup/__init__.py
+++ b/web/pgadmin/tools/backup/__init__.py
@@ -115,15 +115,7 @@ class BackupMessage(IProcessDesc):
                 self.cmd += cmd_arg(arg)
 
     def get_server_details(self):
-        if Server.query.filter_by(id=self.sid,
-                                  user_id=current_user.id).first():
-            s = Server.query.filter_by(
-                id=self.sid, user_id=current_user.id
-            ).first()
-        else:
-            s = SharedServer.query.filter_by(
-                id=self.sid, user_id=current_user.id
-            ).first()
+        s = get_server(self.sid)
 
         from pgadmin.utils.driver import get_driver
         driver = get_driver(PG_DEFAULT_DRIVER)
@@ -422,14 +414,7 @@ def create_backup_objects_job(sid):
         return bad_request(errormsg=str(e))
 
     # Fetch the server details like hostname, port, roles etc
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -531,14 +516,7 @@ def check_utility_exists(sid, backup_obj_type):
     Returns:
         None
     """
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -561,3 +539,22 @@ def check_utility_exists(sid, backup_obj_type):
         )
 
     return make_json_response(success=1)
+
+
+def get_server(sid):
+    """
+    # Fetch the server  etc
+    :param sid:
+    :return: server
+    """
+
+    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
+        server = Server.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+    else:
+        server = SharedServer.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+
+    return server
diff --git a/web/pgadmin/tools/maintenance/__init__.py b/web/pgadmin/tools/maintenance/__init__.py
index 160573a1c..8fbc2e6a2 100644
--- a/web/pgadmin/tools/maintenance/__init__.py
+++ b/web/pgadmin/tools/maintenance/__init__.py
@@ -209,14 +209,8 @@ def create_maintenance_job(sid, did):
     index_name = get_index_name(data)
 
     # Fetch the server details like hostname, port, roles etc
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -306,18 +300,8 @@ def check_utility_exists(sid):
     Returns:
         None
     """
-    # server = Server.query.filter_by(
-    #     id=sid, user_id=current_user.id
-    # ).first()
 
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -338,3 +322,22 @@ def check_utility_exists(sid):
         )
 
     return make_json_response(success=1)
+
+
+def get_server(sid):
+    """
+    # Fetch the server  etc
+    :param sid:
+    :return: server
+    """
+
+    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
+        server = Server.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+    else:
+        server = SharedServer.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+
+    return server
diff --git a/web/pgadmin/tools/restore/__init__.py b/web/pgadmin/tools/restore/__init__.py
index 3bb9a9c5d..28c7f52eb 100644
--- a/web/pgadmin/tools/restore/__init__.py
+++ b/web/pgadmin/tools/restore/__init__.py
@@ -87,16 +87,9 @@ class RestoreMessage(IProcessDesc):
                 self.cmd += cmd_arg(arg)
 
     def get_server_details(self):
+
         # Fetch the server details like hostname, port, roles etc
-        if Server.query.filter_by(id=self.sid,
-                                  user_id=current_user.id).first():
-            s = Server.query.filter_by(
-                id=self.sid, user_id=current_user.id
-            ).first()
-        else:
-            s = SharedServer.query.filter_by(
-                id=self.sid, user_id=current_user.id
-            ).first()
+        s = get_server(self.sid)
 
         from pgadmin.utils.driver import get_driver
         driver = get_driver(PG_DEFAULT_DRIVER)
@@ -215,14 +208,7 @@ def _connect_server(sid):
     :param sid: Server ID.
     :return: if not error occurred then return connection data.
     """
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -477,14 +463,7 @@ def check_utility_exists(sid):
         None
     """
     # Fetch the server details like hostname, port, roles etc
-    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
-        server = Server.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
-    else:
-        server = SharedServer.query.filter_by(
-            id=sid, user_id=current_user.id
-        ).first()
+    server = get_server(sid)
 
     if server is None:
         return make_json_response(
@@ -505,3 +484,22 @@ def check_utility_exists(sid):
         )
 
     return make_json_response(success=1)
+
+
+def get_server(sid):
+    """
+    # Fetch the server  etc
+    :param sid:
+    :return: server
+    """
+
+    if Server.query.filter_by(id=sid, user_id=current_user.id).first():
+        server = Server.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+    else:
+        server = SharedServer.query.filter_by(
+            id=sid, user_id=current_user.id
+        ).first()
+
+    return server


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin]:SonarQube Fixes
@ 2021-04-22 10:50  Pradip Parkale <[email protected]>
  parent: Pradip Parkale <[email protected]>
  0 siblings, 1 reply; 11+ messages in thread

From: Pradip Parkale @ 2021-04-22 10:50 UTC (permalink / raw)
  To: pgadmin-hackers

Hi,

Please ignore my previous patch. PFA attachment of my updated patch.

On Tue, Apr 20, 2021 at 1:49 PM Pradip Parkale <
[email protected]> wrote:

> Hi Hackers,
>
> Please find attached the patch for some SonarQube fixes.
>
> --
> Thanks & Regards,
> Pradip Parkale
> Software Engineer | EnterpriseDB Corporation
>


-- 
Thanks & Regards,
Pradip Parkale
Software Engineer | EnterpriseDB Corporation


Attachments:

  [application/x-patch] SonarQube_2.patch (17.4K, 3-SonarQube_2.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js b/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
index b35422c8d..fcd514f19 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/languages/static/js/language.js
@@ -189,12 +189,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         },{
           id: 'laninl', label: gettext('Inline function'), type: 'text', control: 'node-ajax-options',
@@ -214,12 +209,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         },{
           id: 'lanval', label: gettext('Validator function'), type: 'text', control: 'node-ajax-options',
@@ -239,12 +229,7 @@ define('pgadmin.node.language', [
               });
             }
             return res;
-          }, disabled: function(m) {
-            if (m.isNew()) {
-              return m.get('template_list').indexOf(m.get('name')) != -1;
-            }
-            return false;
-          },
+          }, disabled: 'isDisabled',
           readonly: function(m) {return !m.isNew();},
         }, {
           id: 'lanacl', label: gettext('Privileges'), type: 'collection',
@@ -292,6 +277,12 @@ define('pgadmin.node.language', [
 
           return null;
         },
+        isDisabled: function(m){
+          if (m.isNew()) {
+            return m.get('template_list').indexOf(m.get('name')) != -1;
+          }
+          return false;
+        },
       }),
     });
   }
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
index 97005db23..09ef94a75 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
@@ -600,12 +600,7 @@ define('pgadmin.node.column', [
         },{
           id: 'seqstart', label: gettext('Start'), type: 'int',
           mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
-          disabled: function(m) {
-            let isIdentity = m.get('attidentity');
-            if(!_.isUndefined(isIdentity) && !_.isNull(isIdentity) && !_.isEmpty(isIdentity))
-              return false;
-            return true;
-          }, deps: ['attidentity', 'colconstype'],
+          disabled: 'isIdentityColumn', deps: ['attidentity', 'colconstype'],
           visible: 'isTypeIdentity',
         },{
           id: 'seqmin', label: gettext('Minimum'), type: 'int',
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
index e8d04e336..71b5270f6 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
@@ -737,15 +737,7 @@ define('pgadmin.node.foreign_key', [
         },{
           id: 'condeferrable', label: gettext('Deferrable?'),
           type: 'switch', group: gettext('Definition'),
-          readonly: function(m) {
-            // If we are in table edit mode then
-            if (_.has(m, 'handler') && !_.isUndefined(m.handler)) {
-              // If OID is undefined then user is trying to add
-              // new constraint which should allowed for Unique
-              return !_.isUndefined(m.get('oid'));
-            }
-            return !m.isNew();
-          },
+          readonly: 'isReadonly',
         },{
           id: 'condeferred', label: gettext('Deferred?'),
           type: 'switch', group: gettext('Definition'),
@@ -762,15 +754,7 @@ define('pgadmin.node.foreign_key', [
               return true;
             }
           },
-          readonly: function(m) {
-            // If we are in table edit mode then
-            if (_.has(m, 'handler') && !_.isUndefined(m.handler)) {
-              // If OID is undefined then user is trying to add
-              // new constraint which should allowed for Unique
-              return !_.isUndefined(m.get('oid'));
-            }
-            return !m.isNew();
-          },
+          readonly: 'isReadOnly',
         },{
           id: 'confmatchtype', label: gettext('Match type'),
           type: 'switch', group: gettext('Definition'),
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
index e236230a3..219859985 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
@@ -223,7 +223,6 @@ function(
                     t.unload(i);
                   });
               }},
-            function() {}
           );
         },
         reset_table_stats: function(args) {
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
index 2234b2ddf..ed5836152 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
@@ -374,14 +374,7 @@ define('pgadmin.node.table', [
         },{
           id: 'is_partitioned', label:gettext('Partitioned table?'), cell: 'switch',
           type: 'switch', mode: ['properties', 'create', 'edit'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           readonly: function(m) {
             if (!m.isNew())
               return true;
@@ -483,14 +476,7 @@ define('pgadmin.node.table', [
           id: 'rlspolicy', label: gettext('RLS Policy?'), cell: 'switch',
           type: 'switch', mode: ['properties','edit', 'create'],
           group: gettext('advanced'),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 90600)
-              return true;
-
-            return false;
-          },
+          visible: 'isSupported',
           disabled: function(m) {
             if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
               && !_.isUndefined(m.node_info.server.version) &&
@@ -504,14 +490,7 @@ define('pgadmin.node.table', [
           id: 'forcerlspolicy', label: gettext('Force RLS Policy?'), cell: 'switch',
           type: 'switch', mode: ['properties','edit', 'create'], deps: ['rlspolicy'],
           group: gettext('advanced'),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 90600)
-              return true;
-
-            return false;
-          },
+          visible: 'isSupported',
           disabled: function(m) {
             if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
               && !_.isUndefined(m.node_info.server.version) &&
@@ -843,31 +822,16 @@ define('pgadmin.node.table', [
           id: 'fillfactor', label: gettext('Fill factor'), type: 'int',
           mode: ['create', 'edit'], min: 10, max: 100,
           group: gettext('advanced'),
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },{
           id: 'toast_tuple_target', label: gettext('Toast tuple target'), type: 'int',
           mode: ['create', 'edit'], min: 128, min_version: 110000,
           group: gettext('advanced'),
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },{
           id: 'parallel_workers', label: gettext('Parallel workers'), type: 'int',
           mode: ['create', 'edit'], group: gettext('advanced'), min_version: 90600,
-          disabled: function(m) {
-            if(m.get('is_partitioned')) {
-              return true;
-            }
-            return m.inSchema();
-          },
+          disabled: 'isDisabled',
         },
         {
           id: 'relhasoids', label: gettext('Has OIDs?'), cell: 'switch',
@@ -970,14 +934,7 @@ define('pgadmin.node.table', [
             return options;
           },
           mode:['create'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (!m.get('is_partitioned'))
               return true;
@@ -1027,14 +984,7 @@ define('pgadmin.node.table', [
             );
 
           },
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (m.get('partition_keys') && m.get('partition_keys').models.length > 0) {
               setTimeout(function () {
@@ -1047,14 +997,7 @@ define('pgadmin.node.table', [
         },{
           id: 'partition_scheme', label: gettext('Partition Scheme'),
           type: 'note', group: 'partition', mode: ['edit'],
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (!m.isNew()) {
               this.text = m.get('partition_scheme');
@@ -1077,14 +1020,7 @@ define('pgadmin.node.table', [
             gettext('Let\'s say, we want to create a partition table based per year for the column \'saledate\', having datatype \'date/timestamp\', then we need to specify the expression as \'extract(YEAR from saledate)\' as partition key.'),
             '</li></ul>',
           ].join(''),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
         }, {
           id: 'partitions', label:gettext('Partitions'),
           model: Backform.PartitionsModel,
@@ -1138,14 +1074,7 @@ define('pgadmin.node.table', [
               return true;
             return false;
           },
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
           disabled: function(m) {
             if (m.isNew() && m.get('partitions') && m.get('partitions').models.length > 0) {
               setTimeout(function () {
@@ -1181,14 +1110,7 @@ define('pgadmin.node.table', [
             gettext('Enabled for hash partition.'),
             '</li></ul>',
           ].join(''),
-          visible: function(m) {
-            if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
-              && !_.isUndefined(m.node_info.server.version) &&
-                m.node_info.server.version >= 100000)
-              return true;
-
-            return false;
-          },
+          visible: 'isVersionGreaterThan96',
         },{
           // Here - we will create tab control for storage parameters
           // (auto vacuum).
@@ -1276,6 +1198,23 @@ define('pgadmin.node.table', [
           }
           return null;
         },
+        isVersionGreaterThan96: function(m) {
+          if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
+            && !_.isUndefined(m.node_info.server.version) &&
+              m.node_info.server.version >= 100000)
+            return true;
+
+          return false;
+        },
+        isSupported: function(m) {
+          // Enable when server version is greater than 95.
+          if(!_.isUndefined(m.node_info) && !_.isUndefined(m.node_info.server)
+            && !_.isUndefined(m.node_info.server.version) &&
+              m.node_info.server.version >= 90600)
+            return true;
+
+          return false;
+        },
         // We will disable everything if we are under catalog node
         inSchema: function() {
           if(this.node_info &&  'catalog' in this.node_info)
@@ -1284,6 +1223,12 @@ define('pgadmin.node.table', [
           }
           return false;
         },
+        isDisabled:function(m) {
+          if(m.get('is_partitioned')) {
+            return true;
+          }
+          return m.inSchema();
+        },
         isInheritedTable: function(m) {
           if(!m.inSchema.apply(this, [m])) {
             // Either of_types or coll_inherits has value
diff --git a/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js b/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
index dcb99eb26..92a02735a 100644
--- a/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
+++ b/web/pgadmin/browser/server_groups/servers/roles/static/js/role.js
@@ -515,13 +515,7 @@ define('pgadmin.node.role', [
           filter: function(d) {
             return this.model.isNew() || (this.model.get('rolname') != d.label);
           },
-          helpMessage: function(m) {
-            if (m.has('read_only') && m.get('read_only') == false) {
-              return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
-            } else {
-              return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
-            }
-          },
+          helpMessage: 'helpMessage',
         },
         {
           id: 'rolmembers', label: gettext('Members'), type: 'collection', group: gettext('Membership'),
@@ -541,13 +535,7 @@ define('pgadmin.node.role', [
           filter: function(d) {
             return this.model.isNew() || (this.model.get('rolname') != d.label);
           },
-          helpMessage: function(m) {
-            if (m.has('read_only') && m.get('read_only') == false) {
-              return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
-            } else {
-              return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
-            }
-          },
+          helpMessage: 'helpMessage',
         },
         {
           id: 'variables', label: '', type: 'collection',
@@ -603,6 +591,13 @@ define('pgadmin.node.role', [
 
           return null;
         },
+        helpMessage: function(m) {
+          if (m.has('read_only') && m.get('read_only') == false) {
+            return gettext('Select the checkbox for roles to include WITH ADMIN OPTION.');
+          } else {
+            return gettext('Roles shown with a check mark have the WITH ADMIN OPTION set.');
+          }
+        },
       }),
     });
   }
diff --git a/web/pgadmin/browser/static/js/node.js b/web/pgadmin/browser/static/js/node.js
index 7c2f666e0..1c5af3f57 100644
--- a/web/pgadmin/browser/static/js/node.js
+++ b/web/pgadmin/browser/static/js/node.js
@@ -1786,7 +1786,6 @@ define('pgadmin.browser.node', [
         },
         self = this,
         priority = -Infinity;
-
       var treeInfo = (_.isUndefined(item) || _.isNull(item)) ?
         info || {} : this.getTreeNodeHierarchy(item);
       var actionType = type in opURL ? opURL[type] : type;


^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [pgAdmin]:SonarQube Fixes
@ 2021-04-22 12:12  Akshay Joshi <[email protected]>
  parent: Pradip Parkale <[email protected]>
  0 siblings, 0 replies; 11+ messages in thread

From: Akshay Joshi @ 2021-04-22 12:12 UTC (permalink / raw)
  To: Pradip Parkale <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Thu, Apr 22, 2021 at 4:21 PM Pradip Parkale <
[email protected]> wrote:

> Hi,
>
> Please ignore my previous patch. PFA attachment of my updated patch.
>
> On Tue, Apr 20, 2021 at 1:49 PM Pradip Parkale <
> [email protected]> wrote:
>
>> Hi Hackers,
>>
>> Please find attached the patch for some SonarQube fixes.
>>
>> --
>> Thanks & Regards,
>> Pradip Parkale
>> Software Engineer | EnterpriseDB Corporation
>>
>
>
> --
> Thanks & Regards,
> Pradip Parkale
> Software Engineer | EnterpriseDB Corporation
>


-- 
*Thanks & Regards*
*Akshay Joshi*
*pgAdmin Hacker | Principal Software Architect*
*EDB Postgres <http://edbpostgres.com>*

*Mobile: +91 976-788-8246*


^ permalink  raw  reply  [nested|flat] 11+ messages in thread


end of thread, other threads:[~2021-04-22 12:12 UTC | newest]

Thread overview: 11+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2020-08-03 08:06 [pgAdmin4][Patch] - SonarQube Fixes Khushboo Vashi <[email protected]>
2020-08-04 06:40 ` Akshay Joshi <[email protected]>
2020-08-19 08:31   ` Khushboo Vashi <[email protected]>
2020-08-19 08:56     ` Akshay Joshi <[email protected]>
2020-09-03 11:09       ` Khushboo Vashi <[email protected]>
2020-09-03 13:26         ` Akshay Joshi <[email protected]>
2021-04-07 11:23 [pgAdmin]:SonarQube fixes. Pradip Parkale <[email protected]>
2021-04-08 06:58 ` Re: [pgAdmin]:SonarQube fixes. Akshay Joshi <[email protected]>
2021-04-20 08:19 [pgAdmin]:SonarQube Fixes Pradip Parkale <[email protected]>
2021-04-22 10:50 ` Re: [pgAdmin]:SonarQube Fixes Pradip Parkale <[email protected]>
2021-04-22 12:12   ` Re: [pgAdmin]:SonarQube Fixes Akshay Joshi <[email protected]>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox