public inbox for [email protected]  
help / color / mirror / Atom feed
Patch for SonarQube fixes.
10+ messages / 3 participants
[nested] [flat]

* Patch for SonarQube fixes.
@ 2021-01-18 05:45 Nikhil Mohite <[email protected]>
  2021-01-18 07:39 ` Re: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Nikhil Mohite @ 2021-01-18 05:45 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Team,

I have fixed a few sonarQube issues, PFA patch
Details as follows:

1. Preferences:

   - Refactor this function to reduce its Cognitive Complexity from 18 to
   the 15 allowed.
   - Merge this if statement with the enclosing one.
   - Define a constant instead of duplicating this literal 'tab settings' 5
   times.

2. Connection:

   - Remove this unneeded "pass".

3. Sqleditor:

   - Remove this useless assignment to variable "msgDiv".

4. Debugger:

   - Review this useless assignment: "index" already holds the assigned
   value along all execution paths.
   - 'label' is already declared in the upper scope.
   - 'label' is already declared in the upper scope.
   - 'browser_preferences' is already declared in the upper scope.

5. FileManager:

   - 'path' is already declared in the upper scope.


-- 
*Thanks & Regards,*
*Nikhil Mohite*
*Software Engineer.*
*EDB Postgres* <https://www.enterprisedb.com/;
*Mob.No: +91-7798364578.*


Attachments:

  [application/octet-stream] SonarQubeCodeSmellFixes.patch (14.2K, 3-SonarQubeCodeSmellFixes.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/register_browser_preferences.py b/web/pgadmin/browser/register_browser_preferences.py
index 3b335be1..7f909c41 100644
--- a/web/pgadmin/browser/register_browser_preferences.py
+++ b/web/pgadmin/browser/register_browser_preferences.py
@@ -444,7 +444,7 @@ def register_browser_preferences(self):
     )
 
     self.dynamic_tab_title = self.preference.register(
-        'tab settings', 'dynamic_tabs',
+        'tab_settings', 'dynamic_tabs',
         gettext("Dynamic tab size"), 'boolean', False,
         category_label=PREF_LABEL_TABS_SETTINGS,
         help_str=gettext(
@@ -453,7 +453,7 @@ def register_browser_preferences(self):
     )
 
     self.qt_tab_title = self.preference.register(
-        'tab settings', 'qt_tab_title_placeholder',
+        'tab_settings', 'qt_tab_title_placeholder',
         gettext("Query tool tab title"),
         'text', '%DATABASE%/%USERNAME%@%SERVER%',
         category_label=PREF_LABEL_DISPLAY,
@@ -466,7 +466,7 @@ def register_browser_preferences(self):
     )
 
     self.ve_edt_tab_title = self.preference.register(
-        'tab settings', 'vw_edt_tab_title_placeholder',
+        'tab_settings', 'vw_edt_tab_title_placeholder',
         gettext("View/Edit data tab title"),
         'text', '%SCHEMA%.%TABLE%/%DATABASE%/%USERNAME%@%SERVER%',
         category_label=PREF_LABEL_DISPLAY,
@@ -479,7 +479,7 @@ def register_browser_preferences(self):
     )
 
     self.debugger_tab_title = self.preference.register(
-        'tab settings', 'debugger_tab_title_placeholder',
+        'tab_settings', 'debugger_tab_title_placeholder',
         gettext("Debugger tab title"),
         'text', '%FUNCTION%(%ARGS%)',
         category_label=PREF_LABEL_DISPLAY,
@@ -492,7 +492,7 @@ def register_browser_preferences(self):
     )
 
     self.open_in_new_tab = self.preference.register(
-        'tab settings', 'new_browser_tab_open',
+        'tab_settings', 'new_browser_tab_open',
         gettext("Open in new browser tab"), 'select2', None,
         category_label=PREF_LABEL_OPTIONS,
         options=[{'label': gettext('Query Tool'), 'value': 'qt'},
diff --git a/web/pgadmin/misc/file_manager/static/js/utility.js b/web/pgadmin/misc/file_manager/static/js/utility.js
index 7e335ee8..67c4be04 100644
--- a/web/pgadmin/misc/file_manager/static/js/utility.js
+++ b/web/pgadmin/misc/file_manager/static/js/utility.js
@@ -949,18 +949,18 @@ define([
                 };
 
                 renameItem(file_data);
-                let path = $('.currentpath').val();
+                let current_path = $('.currentpath').val();
                 if(isFolder == true) {
                   // if its folder rename, remove the temporary added class
                   $(this).closest('.tbl_folder').removeClass('tbl_folder_rename');
-                  if(path.includes('\\')) {
-                    path = $('.currentpath').val().split('\\').slice(0, -2).join('\\')+'\\';
+                  if(current_path.includes('\\')) {
+                    current_path = $('.currentpath').val().split('\\').slice(0, -2).join('\\')+'\\';
                   }
                   else {
-                    path = $('.currentpath').val().split('/').slice(0, -2).join('/')+'/';
+                    current_path = $('.currentpath').val().split('/').slice(0, -2).join('/')+'/';
                   }
                 }
-                getFolderInfo(path);
+                getFolderInfo(current_path);
               }
             }
           } else {
@@ -1005,18 +1005,18 @@ define([
                     };
 
                   renameItem(file_data);
-                  let path = $('.currentpath').val();
+                  let current_path = $('.currentpath').val();
                   if(isFolder == true) {
                     // if its folder rename, remove the temporary added class
                     $(this).closest('.tbl_folder').removeClass('tbl_folder_rename');
-                    if(path.includes('\\')) {
-                      path = $('.currentpath').val().split('\\').slice(0, -2).join('\\')+'\\';
+                    if(current_path.includes('\\')) {
+                      current_path = $('.currentpath').val().split('\\').slice(0, -2).join('\\')+'\\';
                     }
                     else {
-                      path = $('.currentpath').val().split('/').slice(0, -2).join('/')+'/';
+                      current_path = $('.currentpath').val().split('/').slice(0, -2).join('/')+'/';
                     }
                   }
-                  getFolderInfo(path);
+                  getFolderInfo(current_path);
                 }
               }
             } else {
diff --git a/web/pgadmin/preferences/__init__.py b/web/pgadmin/preferences/__init__.py
index 7ef18aeb..f11f4317 100644
--- a/web/pgadmin/preferences/__init__.py
+++ b/web/pgadmin/preferences/__init__.py
@@ -204,9 +204,9 @@ def save(pid):
 
     if data['name'] in ['vw_edt_tab_title_placeholder',
                         'qt_tab_title_placeholder',
-                        'debugger_tab_title_placeholder']:
-        if data['value'].isspace():
-            data['value'] = ''
+                        'debugger_tab_title_placeholder'] \
+            and data['value'].isspace():
+        data['value'] = ''
 
     res, msg = Preferences.save(
         data['mid'], data['category_id'], data['id'], data['value'])
diff --git a/web/pgadmin/tools/debugger/static/js/debugger.js b/web/pgadmin/tools/debugger/static/js/debugger.js
index b803f692..a609cf7e 100644
--- a/web/pgadmin/tools/debugger/static/js/debugger.js
+++ b/web/pgadmin/tools/debugger/static/js/debugger.js
@@ -453,9 +453,9 @@ define([
                   if(value) {
                     // Remove the leading and trailing white spaces.
                     value = value.trim();
-                    let browser_preferences = pgBrowser.get_preferences_for_module('browser');
-                    var label = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
-                    debuggerUtils.setDebuggerTitle(panel, browser_preferences, label, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
+                    let preferences = pgBrowser.get_preferences_for_module('browser');
+                    var name = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
+                    debuggerUtils.setDebuggerTitle(panel, preferences, name, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
                   }
                 },
                 // We will execute this function when user clicks on the Cancel
@@ -597,9 +597,9 @@ define([
                         if(value) {
                           // Remove the leading and trailing white spaces.
                           value = value.trim();
-                          let browser_preferences = pgBrowser.get_preferences_for_module('browser');
-                          var label = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
-                          debuggerUtils.setDebuggerTitle(panel, browser_preferences, label, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
+                          let preferences = pgBrowser.get_preferences_for_module('browser');
+                          var name = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
+                          debuggerUtils.setDebuggerTitle(panel, preferences, name, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
                         }
                       },
                       // We will execute this function when user clicks on the Cancel
diff --git a/web/pgadmin/tools/debugger/static/js/debugger_ui.js b/web/pgadmin/tools/debugger/static/js/debugger_ui.js
index 0dd59eff..b1ffeac9 100644
--- a/web/pgadmin/tools/debugger/static/js/debugger_ui.js
+++ b/web/pgadmin/tools/debugger/static/js/debugger_ui.js
@@ -801,8 +801,8 @@ define([
                             if(value) {
                               // Remove the leading and trailing white spaces.
                               value = value.trim();
-                              var label = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
-                              debuggerUtils.setDebuggerTitle(panel, self.preferences, label, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
+                              var name = treeInfo.function ? treeInfo.function.label : treeInfo.trigger_function ? treeInfo.trigger_function.label : treeInfo.trigger ? treeInfo.trigger.label : treeInfo.procedure.label;
+                              debuggerUtils.setDebuggerTitle(panel, self.preferences, name, treeInfo.schema.label, treeInfo.database.label, value, pgBrowser);
                             }
                           },
                           // We will execute this function when user clicks on the Cancel
diff --git a/web/pgadmin/tools/debugger/static/js/debugger_utils.js b/web/pgadmin/tools/debugger/static/js/debugger_utils.js
index 6bc984ff..49675efc 100644
--- a/web/pgadmin/tools/debugger/static/js/debugger_utils.js
+++ b/web/pgadmin/tools/debugger/static/js/debugger_utils.js
@@ -76,7 +76,7 @@ function setDebuggerTitle(panel, preferences, function_name, schema_name, databa
 function get_function_name(function_name) {
   var function_data = function_name.split('(');
   function_data.splice(-1, 1);
-  var index = 0;
+  var index = null;
   var func_name = '';
   for(index=0; index < function_data.length; index++) {
     func_name = func_name.concat(function_data[index]);
diff --git a/web/pgadmin/tools/sqleditor/static/js/sqleditor.js b/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
index 48364f6c..05deebc4 100644
--- a/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
+++ b/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
@@ -2175,7 +2175,6 @@ define('tools.querytool', [
       } else{
         loadingDiv = $('#fetching_data');
         loadingDiv.removeClass('d-none');
-        msgDiv = loadingDiv.find('.sql-editor-busy-text');
       }
       self.set_selected_option(connection_details);
       $.ajax({
diff --git a/web/pgadmin/utils/driver/psycopg2/connection.py b/web/pgadmin/utils/driver/psycopg2/connection.py
index 00c28417..cd6a07b3 100644
--- a/web/pgadmin/utils/driver/psycopg2/connection.py
+++ b/web/pgadmin/utils/driver/psycopg2/connection.py
@@ -757,7 +757,6 @@ WHERE db.datname = current_database()""")
                 if cur and cur.query is not None else None
         except Exception:
             current_app.logger.warning('Error encoding query')
-            pass
 
         dsn = self.conn.get_dsn_parameters()
         current_app.logger.log(
diff --git a/web/pgadmin/utils/preferences.py b/web/pgadmin/utils/preferences.py
index 27915673..289bf268 100644
--- a/web/pgadmin/utils/preferences.py
+++ b/web/pgadmin/utils/preferences.py
@@ -111,22 +111,10 @@ class _Preference(object):
 
         # The data stored in the configuration will be in string format, we
         # need to convert them in proper format.
-        if self._type in ('boolean', 'switch', 'node'):
-            return res.value == 'True'
-        if self._type == 'options':
-            for opt in self.options:
-                if 'value' in opt and opt['value'] == res.value:
-                    return res.value
-            if self.select2 and self.select2['tags']:
-                return res.value
-            return self.default
-        if self._type == 'select2':
-            if res.value:
-                res.value = res.value.replace('[', '')
-                res.value = res.value.replace(']', '')
-                res.value = res.value.replace('\'', '')
-                return [val.strip() for val in res.value.split(',')]
-            return None
+        is_format_data, data = self._get_format_data(res)
+        if is_format_data:
+            return data
+
         if self._type == 'text' and res.value == '' and not self.allow_blanks:
             return self.default
 
@@ -144,6 +132,31 @@ class _Preference(object):
             return self.default
         return res.value
 
+    def _get_format_data(self, res):
+        """
+        Configuration data get stored in string format, convert it in to
+        required format.
+        :param res: type value.
+        """
+        if self._type in ('boolean', 'switch', 'node'):
+            return True, res.value == 'True'
+        if self._type == 'options':
+            for opt in self.options:
+                if 'value' in opt and opt['value'] == res.value:
+                    return True, res.value
+            if self.select2 and self.select2['tags']:
+                return True, res.value
+            return True, self.default
+        if self._type == 'select2':
+            if res.value:
+                res.value = res.value.replace('[', '')
+                res.value = res.value.replace(']', '')
+                res.value = res.value.replace('\'', '')
+                return True, [val.strip() for val in res.value.split(',')]
+            return True, None
+
+        return False, None
+
     def set(self, value):
         """
         set
@@ -477,12 +490,6 @@ class Preferences(object):
                          boolean, integer, numeric, date, datetime,
                          options, multiline, switch, node
         :param default:  Default value for the preference/option
-        :param min_val:  Minimum value for integer, and numeric type
-        :param max_val:  Maximum value for integer, and numeric type
-        :param options:  Allowed list of options for 'option' type
-        :param help_str: Help string show for that preference/option.
-        :param module_label: Label for the module
-        :param category_label: Label for the category
         """
         min_val = kwargs.get('min_val', None)
         max_val = kwargs.get('max_val', None)


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

* Re: Patch for SonarQube fixes.
  2021-01-18 05:45 Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
@ 2021-01-18 07:39 ` Akshay Joshi <[email protected]>
  0 siblings, 0 replies; 10+ messages in thread

From: Akshay Joshi @ 2021-01-18 07:39 UTC (permalink / raw)
  To: Nikhil Mohite <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Mon, Jan 18, 2021 at 11:15 AM Nikhil Mohite <
[email protected]> wrote:

> Hi Team,
>
> I have fixed a few sonarQube issues, PFA patch
> Details as follows:
>
> 1. Preferences:
>
>    - Refactor this function to reduce its Cognitive Complexity from 18 to
>    the 15 allowed.
>    - Merge this if statement with the enclosing one.
>    - Define a constant instead of duplicating this literal 'tab settings'
>    5 times.
>
> 2. Connection:
>
>    - Remove this unneeded "pass".
>
> 3. Sqleditor:
>
>    - Remove this useless assignment to variable "msgDiv".
>
> 4. Debugger:
>
>    - Review this useless assignment: "index" already holds the assigned
>    value along all execution paths.
>    - 'label' is already declared in the upper scope.
>    - 'label' is already declared in the upper scope.
>    - 'browser_preferences' is already declared in the upper scope.
>
> 5. FileManager:
>
>    - 'path' is already declared in the upper scope.
>
>
> --
> *Thanks & Regards,*
> *Nikhil Mohite*
> *Software Engineer.*
> *EDB Postgres* <https://www.enterprisedb.com/;
> *Mob.No: +91-7798364578.*
>


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

*Mobile: +91 976-788-8246*


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

* [pgAdmin]: Patch for SonarQube fixes
@ 2021-01-19 07:27 Nikhil Mohite <[email protected]>
  2021-01-19 08:12 ` Re: [pgAdmin]: Patch for SonarQube fixes Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Nikhil Mohite @ 2021-01-19 07:27 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Team,

I have fixed a few sonarQube issues, PFA patch
Details as follows:

Schema diff:

   - Refactor this function to reduce its Cognitive Complexity from 17 to
   the 15 allowed.
   - Refactor this function to reduce its Cognitive Complexity from 44 to
   the 15 allowed.
   - Refactor this function to reduce its Cognitive Complexity from 32 to
   the 15 allowed.

bg-process:

   - Refactor this function to reduce its Cognitive Complexity from 46 to
   the 15 allowed.
   - Refactor this function to reduce its Cognitive Complexity from 36 to
   the 15 allowed.


-- 
*Thanks & Regards,*
*Nikhil Mohite*
*Software Engineer.*
*EDB Postgres* <https://www.enterprisedb.com/;
*Mob.No: +91-7798364578.*


Attachments:

  [application/octet-stream] SonarQubeCodeSmellFixes.patch (22.2K, 3-SonarQubeCodeSmellFixes.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
index 752ab912..851eb4ea 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
@@ -131,22 +131,9 @@ class SchemaDiffTableCompare(SchemaDiffObjectCompare):
         for source in source_cols:
             if 'name' in source:
                 if isinstance(target_cols, list) and target_cols:
-                    tmp = None
-                    for item in target_cols:
-                        if item['name'] == source['name']:
-                            tmp = copy.deepcopy(item)
-                    if tmp and source != tmp:
-                        tmp_updated = copy.deepcopy(source)
-                        # Preserve the column number
-                        tmp_updated['attnum'] = tmp['attnum']
-                        if item['typname'] not in tmp_updated['edit_types']:
-                            tmp_updated['col_type_conversion'] = False
-                        updated.append(tmp_updated)
-                        target_cols.remove(tmp)
-                    elif tmp and source == tmp:
-                        target_cols.remove(tmp)
-                    elif tmp is None:
-                        added.append(source)
+                    SchemaDiffTableCompare.compare_target_cols(source,
+                                                               target_cols,
+                                                               added, updated)
                 else:
                     added.append(source)
             different['columns']['added'] = added
@@ -157,6 +144,33 @@ class SchemaDiffTableCompare(SchemaDiffObjectCompare):
 
         return different
 
+    @staticmethod
+    def compare_target_cols(source, target_cols, added, updated):
+        """
+        Compare target col with source.
+        :param source:
+        :param target_cols:
+        :param added:
+        :param updated:
+        :return:
+        """
+        tmp = None
+        for item in target_cols:
+            if item['name'] == source['name']:
+                tmp = copy.deepcopy(item)
+        if tmp and source != tmp:
+            tmp_updated = copy.deepcopy(source)
+            # Preserve the column number
+            tmp_updated['attnum'] = tmp['attnum']
+            if item['typname'] not in tmp_updated['edit_types']:
+                tmp_updated['col_type_conversion'] = False
+            updated.append(tmp_updated)
+            target_cols.remove(tmp)
+        elif tmp and source == tmp:
+            target_cols.remove(tmp)
+        elif tmp is None:
+            added.append(source)
+
     @staticmethod
     def table_constraint_comp(source_table, target_table):
         """
diff --git a/web/pgadmin/misc/bgprocess/processes.py b/web/pgadmin/misc/bgprocess/processes.py
index 2c209b76..058d1702 100644
--- a/web/pgadmin/misc/bgprocess/processes.py
+++ b/web/pgadmin/misc/bgprocess/processes.py
@@ -231,20 +231,11 @@ class BatchProcess(object):
         db.session.add(j)
         db.session.commit()
 
-    def start(self, cb=None):
-
-        def which(program, paths):
-            def is_exe(fpath):
-                return os.path.exists(fpath) and os.access(fpath, os.X_OK)
-
-            for path in paths:
-                if not os.path.isdir(path):
-                    continue
-                exe_file = os.path.join(u_encode(path, fs_encoding), program)
-                if is_exe(exe_file):
-                    return file_quote(exe_file)
-            return None
-
+    def check_start_end_time(self):
+        """
+        Check start and end time to check process is still executing or not.
+        :return:
+        """
         if self.stime is not None:
             if self.etime is None:
                 raise RuntimeError(_('The process has already been started.'))
@@ -252,74 +243,20 @@ class BatchProcess(object):
                 _('The process has already finished and cannot be restarted.')
             )
 
+    def start(self, cb=None):
+        self.check_start_end_time()
+
         executor = file_quote(os.path.join(
             os.path.dirname(u_encode(__file__)), 'process_executor.py'
         ))
         paths = os.environ['PATH'].split(os.pathsep)
-        interpreter = None
 
         current_app.logger.info(
             "Process Executor: Operating System Path %s",
             str(paths)
         )
 
-        if os.name == 'nt':
-            paths.insert(0, os.path.join(u_encode(sys.prefix), 'Scripts'))
-            paths.insert(0, u_encode(sys.prefix))
-
-            interpreter = which('pythonw.exe', paths)
-            if interpreter is None:
-                interpreter = which('python.exe', paths)
-
-            current_app.logger.info(
-                "Process Executor: Interpreter value in path: %s",
-                str(interpreter)
-            )
-            if interpreter is None and current_app.PGADMIN_RUNTIME:
-                # We've faced an issue with Windows 2008 R2 (x86) regarding,
-                # not honouring the environment variables set under the Qt
-                # (e.g. runtime), and also setting PYTHONHOME same as
-                # sys.executable (i.e. pgAdmin4.exe).
-                #
-                # As we know, we're running it under the runtime, we can assume
-                # that 'venv' directory will be available outside of 'bin'
-                # directory.
-                #
-                # We would try out luck to find python executable based on that
-                # assumptions.
-                bin_path = os.path.dirname(sys.executable)
-
-                venv = os.path.realpath(
-                    os.path.join(bin_path, '..\\venv')
-                )
-
-                interpreter = which('pythonw.exe', [venv])
-                if interpreter is None:
-                    interpreter = which('python.exe', [venv])
-
-                current_app.logger.info(
-                    "Process Executor: Interpreter value in virtual "
-                    "environment: %s", str(interpreter)
-                )
-
-                if interpreter is not None:
-                    # Our assumptions are proven right.
-                    # Let's append the 'bin' directory to the PATH environment
-                    # variable. And, also set PYTHONHOME environment variable
-                    # to 'venv' directory.
-                    os.environ['PATH'] = bin_path + ';' + os.environ['PATH']
-                    os.environ['PYTHONHOME'] = venv
-        else:
-            # Let's not use sys.prefix in runtime.
-            # 'sys.prefix' is not identified on *nix systems for some unknown
-            # reason, while running under the runtime.
-            # We're already adding '<installation path>/pgAdmin 4/venv/bin'
-            # directory in the PATH environment variable. Hence - it will
-            # anyway be the redundant value in paths.
-            if not current_app.PGADMIN_RUNTIME:
-                paths.insert(0, os.path.join(u_encode(sys.prefix), 'bin'))
-            python_binary_name = 'python{0}'.format(sys.version_info[0])
-            interpreter = which(u_encode(python_binary_name), paths)
+        interpreter = self.get_interpreter(paths)
 
         p = None
         cmd = [
@@ -368,34 +305,14 @@ class BatchProcess(object):
                 creationflags=(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
             )
         else:
-            def preexec_function():
-                import signal
-                # Detaching from the parent process group
-                os.setpgrp()
-                # Explicitly ignoring signals in the child process
-                signal.signal(signal.SIGINT, signal.SIG_IGN)
-
             # if in debug mode, wait for process to complete and
             # get the stdout and stderr of popen.
             if config.CONSOLE_LOG_LEVEL <= logging.DEBUG:
-                p = Popen(
-                    cmd, close_fds=True, stdout=PIPE, stderr=PIPE, stdin=None,
-                    preexec_fn=preexec_function, env=env
-                )
-
-                output, errors = p.communicate()
-                output = output.decode() \
-                    if hasattr(output, 'decode') else output
-                errors = errors.decode() \
-                    if hasattr(errors, 'decode') else errors
-                current_app.logger.debug(
-                    'Process Watcher Out:{0}'.format(output))
-                current_app.logger.debug(
-                    'Process Watcher Err:{0}'.format(errors))
+                output, error = self.get_process_output(cmd, env)
             else:
                 p = Popen(
                     cmd, close_fds=True, stdout=None, stderr=None, stdin=None,
-                    preexec_fn=preexec_function, env=env
+                    preexec_fn=self.preexec_function, env=env
                 )
 
         self.ecode = p.poll()
@@ -423,60 +340,167 @@ class BatchProcess(object):
             p.process_state = PROCESS_STARTED
             db.session.commit()
 
-    def status(self, out=0, err=0):
-        import re
+    def get_process_output(self, cmd, env):
+        """
+        :param cmd:
+        :param env:
+        :return:
+        """
+        p = Popen(
+            cmd, close_fds=True, stdout=PIPE, stderr=PIPE, stdin=None,
+            preexec_fn=self.preexec_function, env=env
+        )
 
-        ctime = get_current_time(format='%y%m%d%H%M%S%f')
+        output, errors = p.communicate()
+        output = output.decode() \
+            if hasattr(output, 'decode') else output
+        errors = errors.decode() \
+            if hasattr(errors, 'decode') else errors
+        current_app.logger.debug(
+            'Process Watcher Out:{0}'.format(output))
+        current_app.logger.debug(
+            'Process Watcher Err:{0}'.format(errors))
+
+        return output, errors
+
+    def preexec_function(self):
+        import signal
+        # Detaching from the parent process group
+        os.setpgrp()
+        # Explicitly ignoring signals in the child process
+        signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+    def get_interpreter(self, paths):
+        """
+        Get interpreter.
+        :param paths:
+        :return:
+        """
+        if os.name == 'nt':
+            paths.insert(0, os.path.join(u_encode(sys.prefix), 'Scripts'))
+            paths.insert(0, u_encode(sys.prefix))
 
-        stdout = []
-        stderr = []
-        out_completed = err_completed = False
-        process_output = (out != -1 and err != -1)
-        enc = sys.getdefaultencoding()
-        if enc == 'ascii':
-            enc = 'utf-8'
+            interpreter = self.which('pythonw.exe', paths)
+            if interpreter is None:
+                interpreter = self.which('python.exe', paths)
+
+            current_app.logger.info(
+                "Process Executor: Interpreter value in path: %s",
+                str(interpreter)
+            )
+            if interpreter is None and current_app.PGADMIN_RUNTIME:
+                # We've faced an issue with Windows 2008 R2 (x86) regarding,
+                # not honouring the environment variables set under the Qt
+                # (e.g. runtime), and also setting PYTHONHOME same as
+                # sys.executable (i.e. pgAdmin4.exe).
+                #
+                # As we know, we're running it under the runtime, we can assume
+                # that 'venv' directory will be available outside of 'bin'
+                # directory.
+                #
+                # We would try out luck to find python executable based on that
+                # assumptions.
+                bin_path = os.path.dirname(sys.executable)
 
-        def read_log(logfile, log, pos, ctime, ecode=None):
-            completed = True
-            idx = 0
-            c = re.compile(r"(\d+),(.*$)")
+                venv = os.path.realpath(
+                    os.path.join(bin_path, '..\\venv')
+                )
 
-            if not os.path.isfile(logfile):
-                return 0, False
+                interpreter = self.which('pythonw.exe', [venv])
+                if interpreter is None:
+                    interpreter = self.which('python.exe', [venv])
 
-            with open(logfile, 'rb') as f:
-                eofs = os.fstat(f.fileno()).st_size
-                f.seek(pos, 0)
-                if pos == eofs and ecode is None:
-                    completed = False
+                current_app.logger.info(
+                    "Process Executor: Interpreter value in virtual "
+                    "environment: %s", str(interpreter)
+                )
 
-                while pos < eofs:
-                    idx += 1
-                    line = f.readline()
-                    line = line.decode(enc, 'replace')
-                    r = c.split(line)
-                    if len(r) < 3:
-                        # ignore this line
-                        pos = f.tell()
-                        continue
-                    if r[1] > ctime:
-                        completed = False
-                        break
-                    log.append([r[1], r[2]])
+                if interpreter is not None:
+                    # Our assumptions are proven right.
+                    # Let's append the 'bin' directory to the PATH environment
+                    # variable. And, also set PYTHONHOME environment variable
+                    # to 'venv' directory.
+                    os.environ['PATH'] = bin_path + ';' + os.environ['PATH']
+                    os.environ['PYTHONHOME'] = venv
+        else:
+            # Let's not use sys.prefix in runtime.
+            # 'sys.prefix' is not identified on *nix systems for some unknown
+            # reason, while running under the runtime.
+            # We're already adding '<installation path>/pgAdmin 4/venv/bin'
+            # directory in the PATH environment variable. Hence - it will
+            # anyway be the redundant value in paths.
+            if not current_app.PGADMIN_RUNTIME:
+                paths.insert(0, os.path.join(u_encode(sys.prefix), 'bin'))
+            python_binary_name = 'python{0}'.format(sys.version_info[0])
+            interpreter = self.which(u_encode(python_binary_name), paths)
+
+        return interpreter
+
+    def which(self, program, paths):
+        def is_exe(fpath):
+            return os.path.exists(fpath) and os.access(fpath, os.X_OK)
+
+        for path in paths:
+            if not os.path.isdir(path):
+                continue
+            exe_file = os.path.join(u_encode(path, fs_encoding), program)
+            if is_exe(exe_file):
+                return file_quote(exe_file)
+        return None
+
+    def read_log(self, logfile, log, pos, ctime, ecode=None, enc='utf-8'):
+        import re
+        completed = True
+        idx = 0
+        c = re.compile(r"(\d+),(.*$)")
+
+        if not os.path.isfile(logfile):
+            return 0, False
+
+        with open(logfile, 'rb') as f:
+            eofs = os.fstat(f.fileno()).st_size
+            f.seek(pos, 0)
+            if pos == eofs and ecode is None:
+                completed = False
+
+            while pos < eofs:
+                idx += 1
+                line = f.readline()
+                line = line.decode(enc, 'replace')
+                r = c.split(line)
+                if len(r) < 3:
+                    # ignore this line
                     pos = f.tell()
-                    if idx >= 1024:
+                    continue
+                if r[1] > ctime:
+                    completed = False
+                    break
+                log.append([r[1], r[2]])
+                pos = f.tell()
+                if idx >= 1024:
+                    completed = False
+                    break
+                if pos == eofs:
+                    if ecode is None:
                         completed = False
-                        break
-                    if pos == eofs:
-                        if ecode is None:
-                            completed = False
-                        break
+                    break
 
-            return pos, completed
+        return pos, completed
+
+    def status(self, out=0, err=0):
+        ctime = get_current_time(format='%y%m%d%H%M%S%f')
+
+        stdout = []
+        stderr = []
+        out_completed = err_completed = False
+        process_output = (out != -1 and err != -1)
 
         j = Process.query.filter_by(
             pid=self.id, user_id=current_user.id
         ).first()
+        enc = sys.getdefaultencoding()
+        if enc == 'ascii':
+            enc = 'utf-8'
 
         execution_time = None
 
@@ -495,11 +519,11 @@ class BatchProcess(object):
                 execution_time = BatchProcess.total_seconds(etime - stime)
 
             if process_output:
-                out, out_completed = read_log(
-                    self.stdout, stdout, out, ctime, self.ecode
+                out, out_completed = self.read_log(
+                    self.stdout, stdout, out, ctime, self.ecode, enc
                 )
-                err, err_completed = read_log(
-                    self.stderr, stderr, err, ctime, self.ecode
+                err, err_completed = self.read_log(
+                    self.stderr, stderr, err, ctime, self.ecode, enc
                 )
         else:
             out_completed = err_completed = False
diff --git a/web/pgadmin/tools/schema_diff/directory_compare.py b/web/pgadmin/tools/schema_diff/directory_compare.py
index 280bebbe..8a1f5348 100644
--- a/web/pgadmin/tools/schema_diff/directory_compare.py
+++ b/web/pgadmin/tools/schema_diff/directory_compare.py
@@ -418,18 +418,18 @@ def are_lists_identical(source_list, target_list, ignore_keys):
     if source_list is None or target_list is None or \
             len(source_list) != len(target_list):
         return False
-    else:
-        for index in range(len(source_list)):
-            # Check the type of the value if it is an dictionary then
-            # call are_dictionaries_identical() function.
-            if isinstance(source_list[index], dict):
-                if not are_dictionaries_identical(source_list[index],
-                                                  target_list[index],
-                                                  ignore_keys):
-                    return False
-            else:
-                if source_list[index] != target_list[index]:
-                    return False
+
+    for index in range(len(source_list)):
+        # Check the type of the value if it is an dictionary then
+        # call are_dictionaries_identical() function.
+        if isinstance(source_list[index], dict):
+            if not are_dictionaries_identical(source_list[index],
+                                              target_list[index],
+                                              ignore_keys):
+                return False
+        else:
+            if source_list[index] != target_list[index]:
+                return False
     return True
 
 
@@ -459,15 +459,15 @@ def are_dictionaries_identical(source_dict, target_dict, ignore_keys):
         current_app.logger.debug("Schema Diff: Number of keys are different "
                                  "in source and target")
         return False
-    else:
-        # If number of keys are same but key is not present in target then
-        # return False
-        for key in src_only:
-            if key not in tar_only:
-                current_app.logger.debug(
-                    "Schema Diff: Number of keys are same but key is not"
-                    " present in target")
-                return False
+
+    # If number of keys are same but key is not present in target then
+    # return False
+    for key in src_only:
+        if key not in tar_only:
+            current_app.logger.debug(
+                "Schema Diff: Number of keys are same but key is not"
+                " present in target")
+            return False
 
     for key in source_dict.keys():
         # Continue if key is available in ignore_keys
@@ -491,17 +491,9 @@ def are_dictionaries_identical(source_dict, target_dict, ignore_keys):
         else:
             source_value = source_dict[key]
             target_value = target_dict[key]
-
-            # If ignore_whitespaces is True then check the source_value and
-            # target_value if of type string. If the values is of type string
-            # then using translate function ignore all the whitespaces.
-            if ignore_whitespaces:
-                if isinstance(source_value, str):
-                    source_value = source_value.translate(
-                        str.maketrans('', '', string.whitespace))
-                if isinstance(target_value, str):
-                    target_value = target_value.translate(
-                        str.maketrans('', '', string.whitespace))
+            # Check if ignore whitespaces or not.
+            source_value, target_value = check_for_ignore_whitespaces(
+                ignore_whitespaces, source_value, target_value)
 
             # We need a proper solution as sometimes we observe that
             # source_value is '' and target_value is None or vice versa
@@ -522,6 +514,28 @@ def are_dictionaries_identical(source_dict, target_dict, ignore_keys):
     return True
 
 
+def check_for_ignore_whitespaces(ignore_whitespaces, source_value,
+                                 target_value):
+    """
+    If ignore_whitespaces is True then check the source_value and
+    target_value if of type string. If the values is of type string
+    then using translate function ignore all the whitespaces.
+    :param ignore_whitespaces: flag to check ignore whitespace.
+    :param source_value: source schema diff value
+    :param target_value: target schema diff value
+    :return: return source and target values.
+    """
+    if ignore_whitespaces:
+        if isinstance(source_value, str):
+            source_value = source_value.translate(
+                str.maketrans('', '', string.whitespace))
+        if isinstance(target_value, str):
+            target_value = target_value.translate(
+                str.maketrans('', '', string.whitespace))
+
+    return source_value, target_value
+
+
 def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
     """
     This function is used to recursively compare two dictionaries and


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

* Re: [pgAdmin]: Patch for SonarQube fixes
  2021-01-19 07:27 [pgAdmin]: Patch for SonarQube fixes Nikhil Mohite <[email protected]>
@ 2021-01-19 08:12 ` Akshay Joshi <[email protected]>
  0 siblings, 0 replies; 10+ messages in thread

From: Akshay Joshi @ 2021-01-19 08:12 UTC (permalink / raw)
  To: Nikhil Mohite <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Tue, Jan 19, 2021 at 12:58 PM Nikhil Mohite <
[email protected]> wrote:

> Hi Team,
>
> I have fixed a few sonarQube issues, PFA patch
> Details as follows:
>
> Schema diff:
>
>    - Refactor this function to reduce its Cognitive Complexity from 17 to
>    the 15 allowed.
>    - Refactor this function to reduce its Cognitive Complexity from 44 to
>    the 15 allowed.
>    - Refactor this function to reduce its Cognitive Complexity from 32 to
>    the 15 allowed.
>
> bg-process:
>
>    - Refactor this function to reduce its Cognitive Complexity from 46 to
>    the 15 allowed.
>    - Refactor this function to reduce its Cognitive Complexity from 36 to
>    the 15 allowed.
>
>
> --
> *Thanks & Regards,*
> *Nikhil Mohite*
> *Software Engineer.*
> *EDB Postgres* <https://www.enterprisedb.com/;
> *Mob.No: +91-7798364578.*
>


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

*Mobile: +91 976-788-8246*


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

* [pgAdmin]: Patch for SonarQube fixes.
@ 2021-03-01 10:42 Nikhil Mohite <[email protected]>
  2021-03-01 11:07 ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Nikhil Mohite @ 2021-03-01 10:42 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Team,

I have fixed a few sonarQube issues, PFA patch
Details as follows:

1. Back-form  (backform.pgadmin.js):

   - TypeError can be thrown as "$tabContent" might be null or undefined
   here.

2. User Management (user_management.js):

   - 'self' is already declared in the upper scope.
   - 'res' is already declared in the upper scope.
   - 'self' is already declared in the upper scope.
   - 'ownershipModel' is already declared in the upper scope.


-- 
*Thanks & Regards,*
*Nikhil Mohite*
*Software Engineer.*
*EDB Postgres* <https://www.enterprisedb.com/;
*Mob.No: +91-7798364578.*


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

* Re: [pgAdmin]: Patch for SonarQube fixes.
  2021-03-01 10:42 [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
@ 2021-03-01 11:07 ` Akshay Joshi <[email protected]>
  2021-03-01 11:12   ` Re: [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Akshay Joshi @ 2021-03-01 11:07 UTC (permalink / raw)
  To: Nikhil Mohite <[email protected]>; +Cc: pgadmin-hackers

Hi Nikhil

You forgot to attach the patch :)

On Mon, Mar 1, 2021 at 4:12 PM Nikhil Mohite <[email protected]>
wrote:

> Hi Team,
>
> I have fixed a few sonarQube issues, PFA patch
> Details as follows:
>
> 1. Back-form  (backform.pgadmin.js):
>
>    - TypeError can be thrown as "$tabContent" might be null or undefined
>    here.
>
> 2. User Management (user_management.js):
>
>    - 'self' is already declared in the upper scope.
>    - 'res' is already declared in the upper scope.
>    - 'self' is already declared in the upper scope.
>    - 'ownershipModel' is already declared in the upper scope.
>
>
> --
> *Thanks & Regards,*
> *Nikhil Mohite*
> *Software Engineer.*
> *EDB Postgres* <https://www.enterprisedb.com/;
> *Mob.No: +91-7798364578.*
>


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

*Mobile: +91 976-788-8246*


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

* Re: [pgAdmin]: Patch for SonarQube fixes.
  2021-03-01 10:42 [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
  2021-03-01 11:07 ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
@ 2021-03-01 11:12   ` Nikhil Mohite <[email protected]>
  2021-03-01 12:30     ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Nikhil Mohite @ 2021-03-01 11:12 UTC (permalink / raw)
  To: Akshay Joshi <[email protected]>; +Cc: pgadmin-hackers

Hi Akshay,

Sorry for the inconvenience, Please find the attached patch.

Regards,
Nikhil Mohite.

On Mon, Mar 1, 2021 at 4:37 PM Akshay Joshi <[email protected]>
wrote:

> Hi Nikhil
>
> You forgot to attach the patch :)
>
> On Mon, Mar 1, 2021 at 4:12 PM Nikhil Mohite <
> [email protected]> wrote:
>
>> Hi Team,
>>
>> I have fixed a few sonarQube issues, PFA patch
>> Details as follows:
>>
>> 1. Back-form  (backform.pgadmin.js):
>>
>>    - TypeError can be thrown as "$tabContent" might be null or undefined
>>    here.
>>
>> 2. User Management (user_management.js):
>>
>>    - 'self' is already declared in the upper scope.
>>    - 'res' is already declared in the upper scope.
>>    - 'self' is already declared in the upper scope.
>>    - 'ownershipModel' is already declared in the upper scope.
>>
>>
>> --
>> *Thanks & Regards,*
>> *Nikhil Mohite*
>> *Software Engineer.*
>> *EDB Postgres* <https://www.enterprisedb.com/;
>> *Mob.No: +91-7798364578.*
>>
>
>
> --
> *Thanks & Regards*
> *Akshay Joshi*
> *pgAdmin Hacker | Principal Software Architect*
> *EDB Postgres <http://edbpostgres.com>*
>
> *Mobile: +91 976-788-8246*
>


Attachments:

  [application/octet-stream] SonarQubeCodeSmellFixes.patch (4.9K, 3-SonarQubeCodeSmellFixes.patch)
  download | inline diff:
diff --git a/web/pgadmin/static/js/backform.pgadmin.js b/web/pgadmin/static/js/backform.pgadmin.js
index 1611cb59..91a3df4c 100644
--- a/web/pgadmin/static/js/backform.pgadmin.js
+++ b/web/pgadmin/static/js/backform.pgadmin.js
@@ -1901,8 +1901,8 @@ define([
             'height: ' + ($tabContent.height() + 8) + 'px !important;'
           );
         }
+        this.sqlCtrl.setSize($tabContent.width() + 'px', $tabContent.height() + 'px');
       }
-      this.sqlCtrl.setSize($tabContent.width() + 'px', $tabContent.height() + 'px');
     },
     remove: function() {
       if (this.sqlCtrl) {
diff --git a/web/pgadmin/tools/user_management/static/js/user_management.js b/web/pgadmin/tools/user_management/static/js/user_management.js
index 531c8c59..cfa6e5a2 100644
--- a/web/pgadmin/tools/user_management/static/js/user_management.js
+++ b/web/pgadmin/tools/user_management/static/js/user_management.js
@@ -612,8 +612,8 @@ define([
 
             let ownershipSelect2Control = Backform.Select2Control.extend({
               fetchData: function(){
-                let self = this;
-                let url = self.field.get('url');
+                let that = this;
+                let url = that.field.get('url');
 
                 url = url_for(url, {'uid': uid});
 
@@ -622,24 +622,24 @@ define([
                   headers: {
                     'Cache-Control' : 'no-cache',
                   },
-                }).done(function (res) {
-                  var transform = self.field.get('transform');
-                  if(res.data.status){
-                    let data = res.data.result.data;
+                }).done(function (res_data) {
+                  var transform = that.field.get('transform');
+                  if(res_data.data.status){
+                    let data = res_data.data.result.data;
 
                     if (transform && _.isFunction(transform)) {
-                      self.field.set('options', transform.bind(self, data));
+                      that.field.set('options', transform.bind(that, data));
                     } else {
-                      self.field.set('options', data);
+                      that.field.set('options', data);
                     }
                   } else {
                     if (transform && _.isFunction(transform)) {
-                      self.field.set('options', transform.bind(self, []));
+                      that.field.set('options', transform.bind(that, []));
                     } else {
-                      self.field.set('options', []);
+                      that.field.set('options', []);
                     }
                   }
-                  Backform.Select2Control.prototype.render.apply(self, arguments);
+                  Backform.Select2Control.prototype.render.apply(that, arguments);
                 }).fail(function(e){
                   let msg = '';
                   if(e.status == 404) {
@@ -728,15 +728,15 @@ define([
                     };
                   },
                   prepare: function() {
-                    let self = this;
+                    let that = this;
                     $container.html('');
 
-                    self.ownershipModel = new ownershipModel();
-                    let fields = pgBackform.generateViewSchema(null, self.ownershipModel, 'create', null, null, true, null);
+                    that.ownershipModel = new ownershipModel();
+                    let fields = pgBackform.generateViewSchema(null, that.ownershipModel, 'create', null, null, true, null);
 
                     let view = this.view = new pgBackform.Dialog({
                       el: '<div></div>',
-                      model: self.ownershipModel,
+                      model: that.ownershipModel,
                       schema: fields,
                     });
                     //Render change ownership dialog.
@@ -745,8 +745,8 @@ define([
                   callback: function(e) {
                     if(e.button['data-btn-name'] === 'ok') {
                       e.cancel = true; // Do not close dialog
-                      let ownershipModel = this.ownershipModel.toJSON();
-                      if (ownershipModel.user == '' || ownershipModel.user == undefined) {
+                      let newOwnershipModel = this.ownershipModel.toJSON();
+                      if (newOwnershipModel.user == '' || newOwnershipModel.user == undefined) {
                         alertify.confirm(
                           gettext('Delete user?'),
                           gettext('The shared servers owned by <b>'+ self.model.get('username') +'</b> will be deleted. Do you wish to continue?'),
@@ -772,7 +772,7 @@ define([
                           }
                         );
                       } else {
-                        self.changeOwner(ownershipModel.user, uid);
+                        self.changeOwner(newOwnershipModel.user, uid);
                       }
                     } else {
                       alertify.changeOwnershipDialog().destroy();


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

* Re: [pgAdmin]: Patch for SonarQube fixes.
  2021-03-01 10:42 [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
  2021-03-01 11:07 ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
  2021-03-01 11:12   ` Re: [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
@ 2021-03-01 12:30     ` Akshay Joshi <[email protected]>
  0 siblings, 0 replies; 10+ messages in thread

From: Akshay Joshi @ 2021-03-01 12:30 UTC (permalink / raw)
  To: Nikhil Mohite <[email protected]>; +Cc: pgadmin-hackers

Thanks, patch applied.

On Mon, Mar 1, 2021 at 4:42 PM Nikhil Mohite <[email protected]>
wrote:

> Hi Akshay,
>
> Sorry for the inconvenience, Please find the attached patch.
>
> Regards,
> Nikhil Mohite.
>
> On Mon, Mar 1, 2021 at 4:37 PM Akshay Joshi <[email protected]>
> wrote:
>
>> Hi Nikhil
>>
>> You forgot to attach the patch :)
>>
>> On Mon, Mar 1, 2021 at 4:12 PM Nikhil Mohite <
>> [email protected]> wrote:
>>
>>> Hi Team,
>>>
>>> I have fixed a few sonarQube issues, PFA patch
>>> Details as follows:
>>>
>>> 1. Back-form  (backform.pgadmin.js):
>>>
>>>    - TypeError can be thrown as "$tabContent" might be null or
>>>    undefined here.
>>>
>>> 2. User Management (user_management.js):
>>>
>>>    - 'self' is already declared in the upper scope.
>>>    - 'res' is already declared in the upper scope.
>>>    - 'self' is already declared in the upper scope.
>>>    - 'ownershipModel' is already declared in the upper scope.
>>>
>>>
>>> --
>>> *Thanks & Regards,*
>>> *Nikhil Mohite*
>>> *Software Engineer.*
>>> *EDB Postgres* <https://www.enterprisedb.com/;
>>> *Mob.No: +91-7798364578.*
>>>
>>
>>
>> --
>> *Thanks & Regards*
>> *Akshay Joshi*
>> *pgAdmin Hacker | Principal Software Architect*
>> *EDB Postgres <http://edbpostgres.com>*
>>
>> *Mobile: +91 976-788-8246*
>>
>

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

*Mobile: +91 976-788-8246*


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

* [pgAdmin]:Patch for SonarQube fixes.
@ 2021-03-18 09:21 Pradip Parkale <[email protected]>
  2021-03-19 06:26 ` Re: [pgAdmin]:Patch for SonarQube fixes. Akshay Joshi <[email protected]>
  0 siblings, 1 reply; 10+ messages in thread

From: Pradip Parkale @ 2021-03-18 09:21 UTC (permalink / raw)
  To: pgadmin-hackers

Hi Hackers,

I have fixed a few sonarQube issues.PFA patch.

   - Fts Configuration


   1. Remove this commented-out code.


   - Funtion


   1. Update this function so that its implementation is not identical to
   the one on line 51.
   2. Unexpected empty method 'validate'.


   - Trigger function


   1. Update this function so that its implementation is not identical to
   the one on line 41.


   - Exclusion constraint


   1. Update this function so that its implementation is not identical to
   the one on line 128.


   - File manager


   1. Remove the unused local variable "e".


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


Attachments:

  [application/octet-stream] sonarqube.patch (4.5K, 3-sonarqube.patch)
  download | inline diff:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js
index fefe309b1..b9b24fee4 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js
@@ -367,7 +367,6 @@ define('pgadmin.node.fts_configuration', [
           self.$grid.find('.new').removeClass('new');
           var newRow = self.grid.body.rows[idx].$el;
           newRow.addClass('new');
-          //$(newRow).pgMakeVisible('table-bordered');
           $(newRow).pgMakeVisible('backform-tab');
         }
 
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 2420fcf2f..9feea15ec 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
@@ -48,13 +48,7 @@ define('pgadmin.node.function', [
       id: 'argtype', label: gettext('Data type'), cell:
         'node-ajax-options', cellHeaderClasses: 'width_percent_30',
       control: 'node-ajax-options', type: 'text', url: 'get_types',
-      editable: function(m) {
-        var node_info = this.get('node_info');
-        if(node_info && 'catalog' in node_info) {
-          return false;
-        }
-        return _.isUndefined(m.isNew) ? true : m.isNew();
-      }, first_empty: true,
+      editable: 'isEditable', first_empty: true,
     },{
       id: 'argmode', label: gettext('Mode'), type: 'options',
       control: 'node-ajax-options', cellHeaderClasses:'width_percent_20',
@@ -66,13 +60,7 @@ define('pgadmin.node.function', [
         {'label': 'OUT', 'value': 'OUT'},
         {'label': 'INOUT', 'value': 'INOUT'},
         {'label': 'VARIADIC', 'value': 'VARIADIC'},
-      ], editable: function(m) {
-        var node_info = this.get('node_info');
-        if(node_info && 'catalog' in node_info) {
-          return false;
-        }
-        return _.isUndefined(m.isNew) ? true : m.isNew();
-      },
+      ], editable: 'isEditable',
     },{
       id: 'argname', label: gettext('Argument name'), type: 'text',
       cell: 'string', editable: 'isInCatalog', cellHeaderClasses:'width_percent_30',
@@ -82,6 +70,13 @@ define('pgadmin.node.function', [
     },
     ],
     toJSON: Backbone.Model.prototype.toJSON,
+    isEditable: function(m) {
+      var node_info = this.get('node_info');
+      if(node_info && 'catalog' in node_info) {
+        return false;
+      }
+      return _.isUndefined(m.isNew) ? true : m.isNew();
+    },
     isInCatalog: function(m){
       var node_info = this.get('node_info');
       if(node_info && 'catalog' in node_info) {
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js b/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js
index a480a96b6..94d9e9a7b 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js
@@ -48,12 +48,7 @@ define('pgadmin.node.trigger_function', [
       },
       hasSQL: true,
       showMenu: function(itemData, item) {
-        let node = pgBrowser.treeMenu.findNodeByDomElement(item);
-
-        if (!node || node.parentNode.getData()._type === 'trigger')
-          return false;
-
-        return true;
+        return this.canEdit(itemData, item);
       },
       hasDepends: true,
       hasStatistics: true,
diff --git a/web/pgadmin/misc/file_manager/__init__.py b/web/pgadmin/misc/file_manager/__init__.py
index 6a98d4bce..0973df4a2 100644
--- a/web/pgadmin/misc/file_manager/__init__.py
+++ b/web/pgadmin/misc/file_manager/__init__.py
@@ -608,7 +608,7 @@ class Filemanager(object):
                 created = time.ctime(os.path.getctime(system_path))
                 modified = time.ctime(os.path.getmtime(system_path))
                 file_extension = str(splitext(system_path))
-            except Exception as e:
+            except Exception:
                 continue
 
             # set protected to 1 if no write or read permission


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

* Re: [pgAdmin]:Patch for SonarQube fixes.
  2021-03-18 09:21 [pgAdmin]:Patch for SonarQube fixes. Pradip Parkale <[email protected]>
@ 2021-03-19 06:26 ` Akshay Joshi <[email protected]>
  0 siblings, 0 replies; 10+ messages in thread

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

Thanks, patch applied.

On Thu, Mar 18, 2021 at 2:51 PM Pradip Parkale <
[email protected]> wrote:

> Hi Hackers,
>
> I have fixed a few sonarQube issues.PFA patch.
>
>    - Fts Configuration
>
>
>    1. Remove this commented-out code.
>
>
>    - Funtion
>
>
>    1. Update this function so that its implementation is not identical to
>    the one on line 51.
>    2. Unexpected empty method 'validate'.
>
>
>    - Trigger function
>
>
>    1. Update this function so that its implementation is not identical to
>    the one on line 41.
>
>
>    - Exclusion constraint
>
>
>    1. Update this function so that its implementation is not identical to
>    the one on line 128.
>
>
>    - File manager
>
>
>    1. Remove the unused local variable "e".
>
>
> --
> 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] 10+ messages in thread


end of thread, other threads:[~2021-03-19 06:26 UTC | newest]

Thread overview: 10+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2021-01-18 05:45 Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
2021-01-18 07:39 ` Akshay Joshi <[email protected]>
2021-01-19 07:27 [pgAdmin]: Patch for SonarQube fixes Nikhil Mohite <[email protected]>
2021-01-19 08:12 ` Re: [pgAdmin]: Patch for SonarQube fixes Akshay Joshi <[email protected]>
2021-03-01 10:42 [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
2021-03-01 11:07 ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
2021-03-01 11:12   ` Re: [pgAdmin]: Patch for SonarQube fixes. Nikhil Mohite <[email protected]>
2021-03-01 12:30     ` Re: [pgAdmin]: Patch for SonarQube fixes. Akshay Joshi <[email protected]>
2021-03-18 09:21 [pgAdmin]:Patch for SonarQube fixes. Pradip Parkale <[email protected]>
2021-03-19 06:26 ` Re: [pgAdmin]:Patch for 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