mirror of
https://github.com/pgadmin-org/pgadmin4.git
synced 2025-02-25 18:55:31 -06:00
Fixed following SonarQube issues:
- Remove this assignment to the local variable, the value is never used. - Rename local variables to match the regular expression - Add logic to this except clause or eliminate it and rethrow the exception automatically. - Rename fields to match the regular expression - Extract this nested conditional expression into an independent statement. - Change this default value to "None" and initialize this parameter inside the function/method. - Update this function so that its implementation is not identical to __repr__ - Refactor this method to not always return the same value - Reraise this exception to stop the application as the user expects - Add missing parameters _w _PY3. This method overrides simplejson.decoder.JSONDecoder.decode. - Remove this redundant continue. - Remove this unused function declaration - Remove this identity check; it will always be False.
This commit is contained in:
parent
eb2c554601
commit
536593bf8a
@ -165,7 +165,6 @@ def get_js_deps():
|
|||||||
if module[2] != "":
|
if module[2] != "":
|
||||||
licence = module[2]
|
licence = module[2]
|
||||||
|
|
||||||
url = "Unknown"
|
|
||||||
if module[3] != "":
|
if module[3] != "":
|
||||||
url = module[3]
|
url = module[3]
|
||||||
|
|
||||||
|
@ -1016,9 +1016,11 @@ class ServerNode(PGChildNodeView):
|
|||||||
else:
|
else:
|
||||||
return unauthorized(gettext("Unauthorized request."))
|
return unauthorized(gettext("Unauthorized request."))
|
||||||
|
|
||||||
data = request.form if request.form else json.loads(
|
data = {}
|
||||||
request.data, encoding='utf-8'
|
if request.form:
|
||||||
) if request.data else {}
|
data = request.form
|
||||||
|
elif request.data:
|
||||||
|
data = json.loads(request.data, encoding='utf-8')
|
||||||
|
|
||||||
password = None
|
password = None
|
||||||
passfile = None
|
passfile = None
|
||||||
|
@ -862,8 +862,6 @@ class DatabaseView(PGChildNodeView):
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
|
|
||||||
status = self.manager.release(did=did)
|
|
||||||
|
|
||||||
SQL = render_template(
|
SQL = render_template(
|
||||||
"/".join([self.template_path, self._DELETE_SQL]),
|
"/".join([self.template_path, self._DELETE_SQL]),
|
||||||
datname=res, conn=self.conn
|
datname=res, conn=self.conn
|
||||||
|
@ -305,9 +305,12 @@ class ForeignTableView(PGChildNodeView, DataTypeReader,
|
|||||||
data[key] = []
|
data[key] = []
|
||||||
|
|
||||||
elif key == 'typnotnull':
|
elif key == 'typnotnull':
|
||||||
data[key] = True if (req[key] == 'true' or req[key]
|
if req[key] == 'true' or req[key] is True:
|
||||||
is True) else False if \
|
data[key] = True
|
||||||
(req[key] == 'false' or req[key]) is False else ''
|
elif req[key] == 'false' or req[key] is False:
|
||||||
|
data[key] = False
|
||||||
|
else:
|
||||||
|
data[key] = ''
|
||||||
else:
|
else:
|
||||||
data[key] = req[key]
|
data[key] = req[key]
|
||||||
|
|
||||||
|
@ -450,7 +450,7 @@ class PartitionsView(BaseTableView, DataTypeReader, VacuumSettings,
|
|||||||
)
|
)
|
||||||
res[row['name']] = data
|
res[row['name']] = data
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
@BaseTableView.check_precondition
|
@BaseTableView.check_precondition
|
||||||
def sql(self, gid, sid, did, scid, tid, ptid):
|
def sql(self, gid, sid, did, scid, tid, ptid):
|
||||||
|
@ -473,15 +473,15 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
|
|||||||
|
|
||||||
# If we have length & precision both
|
# If we have length & precision both
|
||||||
if is_tlength and is_precision:
|
if is_tlength and is_precision:
|
||||||
matchObj = re.search(r'(\d+),(\d+)', row['fulltype'])
|
match_obj = re.search(r'(\d+),(\d+)', row['fulltype'])
|
||||||
if matchObj:
|
if match_obj:
|
||||||
t_len = matchObj.group(1)
|
t_len = match_obj.group(1)
|
||||||
t_prec = matchObj.group(2)
|
t_prec = match_obj.group(2)
|
||||||
elif is_tlength:
|
elif is_tlength:
|
||||||
# If we have length only
|
# If we have length only
|
||||||
matchObj = re.search(r'(\d+)', row['fulltype'])
|
match_obj = re.search(r'(\d+)', row['fulltype'])
|
||||||
if matchObj:
|
if match_obj:
|
||||||
t_len = matchObj.group(1)
|
t_len = match_obj.group(1)
|
||||||
t_prec = None
|
t_prec = None
|
||||||
|
|
||||||
type_name = DataTypeReader.parse_type_name(row['typname'])
|
type_name = DataTypeReader.parse_type_name(row['typname'])
|
||||||
|
@ -202,25 +202,6 @@ class BatchProcess(object):
|
|||||||
return file_quote(exe_file)
|
return file_quote(exe_file)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def convert_environment_variables(env):
|
|
||||||
"""
|
|
||||||
This function is use to convert environment variable to string
|
|
||||||
because environment variable must be string in popen
|
|
||||||
:param env: Dict of environment variable
|
|
||||||
:return: Encoded environment variable as string
|
|
||||||
"""
|
|
||||||
encoding = sys.getdefaultencoding()
|
|
||||||
if encoding is None or encoding == 'ascii':
|
|
||||||
encoding = 'utf-8'
|
|
||||||
temp_env = dict()
|
|
||||||
for key, value in env.items():
|
|
||||||
if not isinstance(key, str):
|
|
||||||
key = key.encode(encoding)
|
|
||||||
if not isinstance(value, str):
|
|
||||||
value = value.encode(encoding)
|
|
||||||
temp_env[key] = value
|
|
||||||
return temp_env
|
|
||||||
|
|
||||||
if self.stime is not None:
|
if self.stime is not None:
|
||||||
if self.etime is None:
|
if self.etime is None:
|
||||||
raise Exception(_('The process has already been started.'))
|
raise Exception(_('The process has already been started.'))
|
||||||
@ -409,7 +390,7 @@ class BatchProcess(object):
|
|||||||
out_completed = err_completed = False
|
out_completed = err_completed = False
|
||||||
process_output = (out != -1 and err != -1)
|
process_output = (out != -1 and err != -1)
|
||||||
enc = sys.getdefaultencoding()
|
enc = sys.getdefaultencoding()
|
||||||
if enc is None or enc == 'ascii':
|
if enc == 'ascii':
|
||||||
enc = 'utf-8'
|
enc = 'utf-8'
|
||||||
|
|
||||||
def read_log(logfile, log, pos, ctime, ecode=None):
|
def read_log(logfile, log, pos, ctime, ecode=None):
|
||||||
|
@ -671,29 +671,28 @@ class Filemanager(object):
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def check_access_permission(in_dir, path):
|
def check_access_permission(in_dir, path):
|
||||||
|
|
||||||
if not config.SERVER_MODE:
|
if config.SERVER_MODE:
|
||||||
return True
|
if in_dir is None:
|
||||||
|
in_dir = ""
|
||||||
|
orig_path = Filemanager.get_abs_path(in_dir, path)
|
||||||
|
|
||||||
if in_dir is None:
|
# This translates path with relative path notations
|
||||||
in_dir = ""
|
# like ./ and ../ to absolute path.
|
||||||
orig_path = Filemanager.get_abs_path(in_dir, path)
|
orig_path = os.path.abspath(orig_path)
|
||||||
|
|
||||||
# This translates path with relative path notations like ./ and ../ to
|
if in_dir:
|
||||||
# absolute path.
|
if _platform == 'win32':
|
||||||
orig_path = os.path.abspath(orig_path)
|
if in_dir[-1] == '\\' or in_dir[-1] == '/':
|
||||||
|
in_dir = in_dir[:-1]
|
||||||
|
else:
|
||||||
|
if in_dir[-1] == '/':
|
||||||
|
in_dir = in_dir[:-1]
|
||||||
|
|
||||||
if in_dir:
|
# Do not allow user to access outside his storage dir
|
||||||
if _platform == 'win32':
|
# in server mode.
|
||||||
if in_dir[-1] == '\\' or in_dir[-1] == '/':
|
if not orig_path.startswith(in_dir):
|
||||||
in_dir = in_dir[:-1]
|
raise Exception(
|
||||||
else:
|
gettext(u"Access denied ({0})").format(path))
|
||||||
if in_dir[-1] == '/':
|
|
||||||
in_dir = in_dir[:-1]
|
|
||||||
|
|
||||||
# Do not allow user to access outside his storage dir in server mode.
|
|
||||||
if not orig_path.startswith(in_dir):
|
|
||||||
raise Exception(
|
|
||||||
gettext(u"Access denied ({0})").format(path))
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -492,7 +492,6 @@ def init_function(node_type, sid, did, scid, fid, trid=None):
|
|||||||
for pr_arg_mode in pro_arg_modes:
|
for pr_arg_mode in pro_arg_modes:
|
||||||
if pr_arg_mode == 'o' or pr_arg_mode == 't':
|
if pr_arg_mode == 'o' or pr_arg_mode == 't':
|
||||||
data['require_input'] = False
|
data['require_input'] = False
|
||||||
continue
|
|
||||||
else:
|
else:
|
||||||
data['require_input'] = True
|
data['require_input'] = True
|
||||||
break
|
break
|
||||||
@ -2124,7 +2123,8 @@ def close_debugger_session(_trans_id, close_all=False):
|
|||||||
dbg_obj['exe_conn_id'],
|
dbg_obj['exe_conn_id'],
|
||||||
dbg_obj['database_id'])
|
dbg_obj['database_id'])
|
||||||
manager.release(conn_id=dbg_obj['exe_conn_id'])
|
manager.release(conn_id=dbg_obj['exe_conn_id'])
|
||||||
except Exception:
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
de_inst.clear()
|
de_inst.clear()
|
||||||
|
except Exception:
|
||||||
|
de_inst.clear()
|
||||||
|
raise
|
||||||
|
@ -319,7 +319,7 @@ def are_dictionaries_identical(source_dict, target_dict, ignore_whitespaces,
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def directory_diff(source_dict, target_dict, ignore_keys=[], difference={}):
|
def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
|
||||||
"""
|
"""
|
||||||
This function is used to recursively compare two dictionaries and
|
This function is used to recursively compare two dictionaries and
|
||||||
return the difference.
|
return the difference.
|
||||||
@ -330,6 +330,7 @@ def directory_diff(source_dict, target_dict, ignore_keys=[], difference={}):
|
|||||||
:param difference:
|
:param difference:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
difference = {} if difference is None else difference
|
||||||
src_keys = set(source_dict.keys())
|
src_keys = set(source_dict.keys())
|
||||||
tar_keys = set(target_dict.keys())
|
tar_keys = set(target_dict.keys())
|
||||||
|
|
||||||
|
@ -259,10 +259,7 @@ def start_view_data(trans_id):
|
|||||||
update_session_grid_transaction(trans_id, session_obj)
|
update_session_grid_transaction(trans_id, session_obj)
|
||||||
|
|
||||||
# Execute sql asynchronously
|
# Execute sql asynchronously
|
||||||
try:
|
status, result = conn.execute_async(sql)
|
||||||
status, result = conn.execute_async(sql)
|
|
||||||
except (ConnectionLost, SSHTunnelConnectionLost) as e:
|
|
||||||
raise
|
|
||||||
else:
|
else:
|
||||||
status = False
|
status = False
|
||||||
result = error_msg
|
result = error_msg
|
||||||
|
@ -137,10 +137,7 @@ class StartRunningQuery:
|
|||||||
|
|
||||||
# Execute sql asynchronously with params is None
|
# Execute sql asynchronously with params is None
|
||||||
# and formatted_error is True.
|
# and formatted_error is True.
|
||||||
try:
|
status, result = conn.execute_async(sql)
|
||||||
status, result = conn.execute_async(sql)
|
|
||||||
except (ConnectionLost, SSHTunnelConnectionLost, CryptKeyMissing):
|
|
||||||
raise
|
|
||||||
|
|
||||||
# If the transaction aborted for some reason and
|
# If the transaction aborted for some reason and
|
||||||
# Auto RollBack is True then issue a rollback to cleanup.
|
# Auto RollBack is True then issue a rollback to cleanup.
|
||||||
|
@ -31,7 +31,7 @@ class DataTypeJSONEncoder(json.JSONEncoder):
|
|||||||
|
|
||||||
|
|
||||||
class ColParamsJSONDecoder(json.JSONDecoder):
|
class ColParamsJSONDecoder(json.JSONDecoder):
|
||||||
def decode(self, obj):
|
def decode(self, obj, **kwargs):
|
||||||
retval = obj
|
retval = obj
|
||||||
try:
|
try:
|
||||||
retval = json.JSONDecoder.decode(self, obj)
|
retval = json.JSONDecoder.decode(self, obj)
|
||||||
|
@ -721,7 +721,7 @@ class DictWriter(object):
|
|||||||
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
|
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
|
||||||
% self.extrasaction)
|
% self.extrasaction)
|
||||||
dialect = kwds.get('dialect', "excel")
|
dialect = kwds.get('dialect', "excel")
|
||||||
self.Writer = Writer(f, dialect, *args, **kwds)
|
self.writer = Writer(f, dialect, *args, **kwds)
|
||||||
|
|
||||||
def writeheader(self):
|
def writeheader(self):
|
||||||
header = dict(zip(self.fieldnames, self.fieldnames))
|
header = dict(zip(self.fieldnames, self.fieldnames))
|
||||||
@ -736,7 +736,7 @@ class DictWriter(object):
|
|||||||
return (rowdict.get(key, self.restval) for key in self.fieldnames)
|
return (rowdict.get(key, self.restval) for key in self.fieldnames)
|
||||||
|
|
||||||
def writerow(self, rowdict):
|
def writerow(self, rowdict):
|
||||||
return self.Writer.writerow(self._dict_to_list(rowdict))
|
return self.writer.writerow(self._dict_to_list(rowdict))
|
||||||
|
|
||||||
def writerows(self, rowdicts):
|
def writerows(self, rowdicts):
|
||||||
return self.Writer.writerows(map(self._dict_to_list, rowdicts))
|
return self.writer.writerows(map(self._dict_to_list, rowdicts))
|
||||||
|
@ -198,12 +198,7 @@ class Connection(BaseConnection):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "PG Connection: {0} ({1}) -> {2} (ajax:{3})".format(
|
return self.__repr__()
|
||||||
self.conn_id, self.db,
|
|
||||||
'Connected' if self.conn and not self.conn.closed else
|
|
||||||
"Disconnected",
|
|
||||||
self.async_
|
|
||||||
)
|
|
||||||
|
|
||||||
def connect(self, **kwargs):
|
def connect(self, **kwargs):
|
||||||
if self.conn:
|
if self.conn:
|
||||||
@ -714,27 +709,6 @@ WHERE
|
|||||||
return False, \
|
return False, \
|
||||||
gettext('The query executed did not return any data.')
|
gettext('The query executed did not return any data.')
|
||||||
|
|
||||||
def convert_keys_to_unicode(results, conn_encoding):
|
|
||||||
"""
|
|
||||||
[ This is only for Python2.x]
|
|
||||||
We need to convert all keys to unicode as psycopg2
|
|
||||||
sends them as string
|
|
||||||
|
|
||||||
Args:
|
|
||||||
res: Query result set from psycopg2
|
|
||||||
conn_encoding: Connection encoding
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Result set (With all the keys converted to unicode)
|
|
||||||
"""
|
|
||||||
new_results = []
|
|
||||||
for row in results:
|
|
||||||
new_results.append(
|
|
||||||
dict([(k.decode(conn_encoding), v)
|
|
||||||
for k, v in row.items()])
|
|
||||||
)
|
|
||||||
return new_results
|
|
||||||
|
|
||||||
def handle_null_values(results, replace_nulls_with):
|
def handle_null_values(results, replace_nulls_with):
|
||||||
"""
|
"""
|
||||||
This function is used to replace null values with the given string
|
This function is used to replace null values with the given string
|
||||||
@ -1279,9 +1253,14 @@ WHERE
|
|||||||
)
|
)
|
||||||
|
|
||||||
except psycopg2.Error as e:
|
except psycopg2.Error as e:
|
||||||
msg = e.pgerror if e.pgerror else e.message \
|
if e.pgerror:
|
||||||
if e.message else e.diag.message_detail \
|
msg = e.pgerror
|
||||||
if e.diag.message_detail else str(e)
|
elif e.message:
|
||||||
|
msg = e.message
|
||||||
|
elif e.diag.message_detail:
|
||||||
|
msg = e.diag.message_detail
|
||||||
|
else:
|
||||||
|
msg = str(e)
|
||||||
|
|
||||||
current_app.logger.error(
|
current_app.logger.error(
|
||||||
gettext(
|
gettext(
|
||||||
|
@ -372,8 +372,11 @@ WHERE db.oid = {0}""".format(did))
|
|||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
my_id = (u'CONN:{0}'.format(conn_id)) if conn_id is not None else \
|
my_id = None
|
||||||
(u'DB:{0}'.format(database)) if database is not None else None
|
if conn_id is not None:
|
||||||
|
my_id = u'CONN:{0}'.format(conn_id)
|
||||||
|
elif database is not None:
|
||||||
|
my_id = u'DB:{0}'.format(database)
|
||||||
|
|
||||||
if my_id is not None:
|
if my_id is not None:
|
||||||
if my_id in self.connections:
|
if my_id in self.connections:
|
||||||
|
@ -103,11 +103,11 @@ class SessionManager(object):
|
|||||||
|
|
||||||
|
|
||||||
class CachingSessionManager(SessionManager):
|
class CachingSessionManager(SessionManager):
|
||||||
def __init__(self, parent, num_to_store, skip_paths=[]):
|
def __init__(self, parent, num_to_store, skip_paths=None):
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
self.num_to_store = num_to_store
|
self.num_to_store = num_to_store
|
||||||
self._cache = OrderedDict()
|
self._cache = OrderedDict()
|
||||||
self.skip_paths = skip_paths
|
self.skip_paths = [] if skip_paths is None else skip_paths
|
||||||
|
|
||||||
def _normalize(self):
|
def _normalize(self):
|
||||||
if len(self._cache) > self.num_to_store:
|
if len(self._cache) > self.num_to_store:
|
||||||
@ -187,13 +187,13 @@ class CachingSessionManager(SessionManager):
|
|||||||
|
|
||||||
class FileBackedSessionManager(SessionManager):
|
class FileBackedSessionManager(SessionManager):
|
||||||
|
|
||||||
def __init__(self, path, secret, disk_write_delay, skip_paths=[]):
|
def __init__(self, path, secret, disk_write_delay, skip_paths=None):
|
||||||
self.path = path
|
self.path = path
|
||||||
self.secret = secret
|
self.secret = secret
|
||||||
self.disk_write_delay = disk_write_delay
|
self.disk_write_delay = disk_write_delay
|
||||||
if not os.path.exists(self.path):
|
if not os.path.exists(self.path):
|
||||||
os.makedirs(self.path)
|
os.makedirs(self.path)
|
||||||
self.skip_paths = skip_paths
|
self.skip_paths = [] if skip_paths is None else skip_paths
|
||||||
|
|
||||||
def exists(self, sid):
|
def exists(self, sid):
|
||||||
fname = os.path.join(self.path, sid)
|
fname = os.path.join(self.path, sid)
|
||||||
|
@ -1129,9 +1129,9 @@ def check_binary_path_or_skip_test(cls, utility_name):
|
|||||||
cls.server['default_binary_paths'][cls.server['type']],
|
cls.server['default_binary_paths'][cls.server['type']],
|
||||||
utility_name
|
utility_name
|
||||||
)
|
)
|
||||||
ret_val = does_utility_exist(binary_path)
|
retVal = does_utility_exist(binary_path)
|
||||||
if ret_val is not None:
|
if retVal is not None:
|
||||||
cls.skipTest(ret_val)
|
cls.skipTest(retVal)
|
||||||
|
|
||||||
|
|
||||||
def get_watcher_dialogue_status(self):
|
def get_watcher_dialogue_status(self):
|
||||||
|
@ -819,6 +819,7 @@ if __name__ == '__main__':
|
|||||||
app_starter_local.stop_app()
|
app_starter_local.stop_app()
|
||||||
if handle_cleanup:
|
if handle_cleanup:
|
||||||
handle_cleanup()
|
handle_cleanup()
|
||||||
|
raise
|
||||||
else:
|
else:
|
||||||
print(
|
print(
|
||||||
"\n============= Either Selenium Grid is NOT up OR"
|
"\n============= Either Selenium Grid is NOT up OR"
|
||||||
@ -840,6 +841,7 @@ if __name__ == '__main__':
|
|||||||
except SystemExit:
|
except SystemExit:
|
||||||
if handle_cleanup:
|
if handle_cleanup:
|
||||||
handle_cleanup()
|
handle_cleanup()
|
||||||
|
raise
|
||||||
print_test_results()
|
print_test_results()
|
||||||
|
|
||||||
# Stop code coverage
|
# Stop code coverage
|
||||||
|
Loading…
Reference in New Issue
Block a user