Some clumsy coding related fixes reported by SonarQube.

This commit is contained in:
Aditya Toshniwal 2020-06-12 15:24:17 +05:30 committed by Akshay Joshi
parent ee1ea47e88
commit 8c20f0c0d2
14 changed files with 222 additions and 238 deletions

View File

@ -589,9 +589,8 @@ def create_app(app_name=None):
def store_crypt_key(app, user):
# in desktop mode, master password is used to encrypt/decrypt
# and is stored in the keyManager memory
if config.SERVER_MODE:
if 'password' in request.form:
current_app.keyManager.set(request.form['password'])
if config.SERVER_MODE and 'password' in request.form:
current_app.keyManager.set(request.form['password'])
@user_logged_out.connect_via(app)
def current_user_cleanup(app, user):

View File

@ -621,18 +621,18 @@ def index():
except Exception:
current_app.logger.exception('Exception when checking for update')
if data is not None:
if data[config.UPGRADE_CHECK_KEY]['version_int'] > \
config.APP_VERSION_INT:
msg = render_template(
MODULE_NAME + "/upgrade.html",
current_version=config.APP_VERSION,
upgrade_version=data[config.UPGRADE_CHECK_KEY]['version'],
product_name=config.APP_NAME,
download_url=data[config.UPGRADE_CHECK_KEY]['download_url']
)
if data is not None and \
data[config.UPGRADE_CHECK_KEY]['version_int'] > \
config.APP_VERSION_INT:
msg = render_template(
MODULE_NAME + "/upgrade.html",
current_version=config.APP_VERSION,
upgrade_version=data[config.UPGRADE_CHECK_KEY]['version'],
product_name=config.APP_NAME,
download_url=data[config.UPGRADE_CHECK_KEY]['download_url']
)
flash(msg, 'warning')
flash(msg, 'warning')
auth_only_internal = False
auth_source = []

View File

@ -522,13 +522,13 @@ class ServerNode(PGChildNodeView):
if 'db_res' in data:
data['db_res'] = ','.join(data['db_res'])
if 'hostaddr' in data and data['hostaddr'] and data['hostaddr'] != '':
if not is_valid_ipaddress(data['hostaddr']):
return make_json_response(
success=0,
status=400,
errormsg=gettext('Host address not valid')
)
if 'hostaddr' in data and data['hostaddr'] and data['hostaddr'] != '' \
and not is_valid_ipaddress(data['hostaddr']):
return make_json_response(
success=0,
status=400,
errormsg=gettext('Host address not valid')
)
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
conn = manager.connection()
@ -741,13 +741,13 @@ class ServerNode(PGChildNodeView):
).format(arg)
)
if 'hostaddr' in data and data['hostaddr'] and data['hostaddr'] != '':
if not is_valid_ipaddress(data['hostaddr']):
return make_json_response(
success=0,
status=400,
errormsg=gettext('Not a valid Host address')
)
if 'hostaddr' in data and data['hostaddr'] and data['hostaddr'] != '' \
and not is_valid_ipaddress(data['hostaddr']):
return make_json_response(
success=0,
status=400,
errormsg=gettext('Not a valid Host address')
)
# To check ssl configuration
is_ssl, data = self.check_ssl_fields(data)
@ -1287,22 +1287,21 @@ class ServerNode(PGChildNodeView):
# If there is no password found for the server
# then check for pgpass file
if not server.password and not manager.password:
if server.passfile and \
manager.passfile and \
server.passfile == manager.passfile:
is_passfile = True
if not server.password and not manager.password and \
server.passfile and manager.passfile and \
server.passfile == manager.passfile:
is_passfile = True
# Check for password only if there is no pgpass file used
if not is_passfile:
if data and ('password' not in data or data['password'] == ''):
return make_json_response(
status=400,
success=0,
errormsg=gettext(
"Could not find the required parameter(s)."
)
if not is_passfile and data and \
('password' not in data or data['password'] == ''):
return make_json_response(
status=400,
success=0,
errormsg=gettext(
"Could not find the required parameter(s)."
)
)
if data and ('newPassword' not in data or
data['newPassword'] == '' or
@ -1490,11 +1489,10 @@ class ServerNode(PGChildNodeView):
errormsg=gettext('Please connect the server.')
)
if not server.password or not manager.password:
if server.passfile and \
manager.passfile and \
server.passfile == manager.passfile:
is_pgpass = True
if (not server.password or not manager.password) and \
server.passfile and manager.passfile and \
server.passfile == manager.passfile:
is_pgpass = True
return make_json_response(
success=1,
data=dict({'is_pgpass': is_pgpass}),

View File

@ -487,9 +487,8 @@ It may have been removed by another user.
if not status:
return internal_server_error(errormsg=rset)
if scid is not None:
if len(rset['rows']) == 0:
return gone(gettext("""
if scid is not None and len(rset['rows']) == 0:
return gone(gettext("""
Could not find the schema in the database.
It may have been removed by another user.
"""))

View File

@ -410,28 +410,26 @@ class CollationView(PGChildNodeView, SchemaDiffObjectCompare):
for arg in definition_args:
if (
arg == 'locale' and
(arg not in data or data[arg] == '')
(arg not in data or data[arg] == '') and
'copy_collation' not in data and
'lc_collate' not in data and 'lc_type' not in data
):
if 'copy_collation' not in data and (
'lc_collate' not in data and 'lc_type' not in data
):
missing_definition_flag = True
missing_definition_flag = True
if (
arg == 'copy_collation' and
(arg not in data or data[arg] == '')
(arg not in data or data[arg] == '') and
'locale' not in data and
'lc_collate' not in data and 'lc_type' not in data
):
if 'locale' not in data and (
'lc_collate' not in data and 'lc_type' not in data
):
missing_definition_flag = True
missing_definition_flag = True
if (
(arg == 'lc_collate' or arg == 'lc_type') and
(arg not in data or data[arg] == '')
(arg not in data or data[arg] == '') and
'copy_collation' not in data and 'locale' not in data
):
if 'copy_collation' not in data and 'locale' not in data:
missing_definition_flag = True
missing_definition_flag = True
return missing_definition_flag

View File

@ -1163,22 +1163,21 @@ class ForeignTableView(PGChildNodeView, DataTypeReader,
data['columns'] = cols['rows']
# Get Inherited table names from their OID
if inherits:
if 'inherits' in data and data['inherits']:
inherits = tuple([int(x) for x in data['inherits']])
if len(inherits) == 1:
inherits = "(" + str(inherits[0]) + ")"
if inherits and 'inherits' in data and data['inherits']:
inherits = tuple([int(x) for x in data['inherits']])
if len(inherits) == 1:
inherits = "(" + str(inherits[0]) + ")"
SQL = render_template("/".join([self.template_path,
'get_tables.sql']),
attrelid=inherits)
status, res = self.conn.execute_dict(SQL)
SQL = render_template("/".join([self.template_path,
'get_tables.sql']),
attrelid=inherits)
status, res = self.conn.execute_dict(SQL)
if not status:
return False, internal_server_error(errormsg=res)
if not status:
return False, internal_server_error(errormsg=res)
if 'inherits' in res['rows'][0]:
data['inherits'] = res['rows'][0]['inherits']
if 'inherits' in res['rows'][0]:
data['inherits'] = res['rows'][0]['inherits']
return True, data

View File

@ -394,12 +394,12 @@ class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
res['rows'][0]['oid'] <= self.datlastsysoid)
# Handle templates and its schema name properly
if res['rows'][0]['template_schema'] is not None:
if res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template']
)
if res['rows'][0]['template_schema'] is not None and \
res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template']
)
if res['rows'][0]['options'] is not None:
res['rows'][0]['options'] = self.tokenize_options(
@ -669,12 +669,12 @@ class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
data['schema'] = old_data['schema']
# Handle templates and its schema name properly
if old_data['template_schema'] is not None:
if old_data['template_schema'] != "pg_catalog":
old_data['template'] = self.qtIdent(
self.conn, old_data['template_schema'],
old_data['template']
)
if old_data['template_schema'] is not None and \
old_data['template_schema'] != "pg_catalog":
old_data['template'] = self.qtIdent(
self.conn, old_data['template_schema'],
old_data['template']
)
# If user has changed the schema then fetch new schema directly
# using its oid otherwise fetch old schema name using its oid
@ -802,12 +802,12 @@ class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
))
# Handle templates and its schema name properly
if res['rows'][0]['template_schema'] is not None:
if res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template']
)
if res['rows'][0]['template_schema'] is not None and \
res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template']
)
if res['rows'][0]['options'] is not None:
res['rows'][0]['options'] = self.tokenize_options(

View File

@ -222,9 +222,10 @@ def get_sql(conn, data, did, tid, ctype, cid=None, template_path=None):
for arg in required_args:
if isinstance(arg, list):
for param in arg:
if param in data:
if is_key_str(param, data) or is_key_list(param, data):
break
if param in data and \
(is_key_str(param, data) or
is_key_list(param, data)):
break
else:
return _('-- definition incomplete'), name

View File

@ -538,11 +538,10 @@ class RuleView(PGChildNodeView, SchemaDiffObjectCompare):
SQL = ''
if data:
if source_schema:
if 'statements' in data:
# Replace the source schema with the target schema
data['statements'] = data['statements'].replace(
source_schema, diff_schema)
if source_schema and 'statements' in data:
# Replace the source schema with the target schema
data['statements'] = data['statements'].replace(
source_schema, diff_schema)
old_data = res_data
SQL = render_template(
"/".join([self.template_path, 'update.sql']),

View File

@ -1540,13 +1540,13 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
reset_values = []
for data_row in data[vacuum_key]['changed']:
for old_data_row in old_data[vacuum_key]:
if data_row['name'] == old_data_row['name']:
if 'value' in data_row:
if data_row['value'] is not None:
set_values.append(data_row)
elif data_row['value'] is None and \
'value' in old_data_row:
reset_values.append(data_row)
if data_row['name'] == old_data_row['name'] and \
'value' in data_row:
if data_row['value'] is not None:
set_values.append(data_row)
elif data_row['value'] is None and \
'value' in old_data_row:
reset_values.append(data_row)
if len(set_values) > 0:
data[vacuum_key]['set_values'] = set_values

View File

@ -946,32 +946,30 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
)
# Additional checks goes here
# If type is range then check if subtype is defined or not
if data and data[arg] == 'r':
if 'typname' not in data or data['typname'] is None:
return make_json_response(
status=410,
success=0,
errormsg=gettext(
'Subtype must be defined for range types.'
)
if data and data[arg] == 'r' and \
('typname' not in data or data['typname'] is None):
return make_json_response(
status=410,
success=0,
errormsg=gettext(
'Subtype must be defined for range types.'
)
)
# If type is external then check if input/output
# conversion function is defined
if data and data[arg] == 'b':
if (
if data and data[arg] == 'b' and (
'typinput' not in data or
'typoutput' not in data or
data['typinput'] is None or
data['typoutput'] is None
):
return make_json_response(
status=410,
success=0,
errormsg=gettext(
'External types require both input and output '
'conversion functions.'
)
data['typoutput'] is None):
return make_json_response(
status=410,
success=0,
errormsg=gettext(
'External types require both input and output '
'conversion functions.'
)
)
# To format privileges coming from client
if 'typacl' in data and data['typacl'] is not None:
@ -1307,20 +1305,18 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
# Additional checks go here
# If type is range then check if subtype is defined or not
if data and data[arg] == 'r':
if 'typname' not in data or data['typname'] is None:
return "-- definition incomplete"
if data and data[arg] == 'r' and \
('typname' not in data or data['typname'] is None):
return "-- definition incomplete"
# If type is external then check if input/output
# conversion function is defined
if data and data[arg] == 'b':
if (
if data and data[arg] == 'b' and (
'typinput' not in data or
'typoutput' not in data or
data['typinput'] is None or
data['typoutput'] is None
):
return "-- definition incomplete"
data['typoutput'] is None):
return "-- definition incomplete"
# Privileges
if 'typacl' in data and data['typacl'] is not None:

View File

@ -1637,34 +1637,32 @@ class MViewNode(ViewNode, VacuumSettings):
data['vacuum_data']['reset'] = []
# table vacuum: separate list of changed and reset data for
if 'vacuum_table' in data:
if 'changed' in data['vacuum_table']:
for item in data['vacuum_table']['changed']:
if 'value' in item.keys():
if item['value'] is None:
if old_data[item['name']] != item['value']:
data['vacuum_data']['reset'].append(item)
else:
if (old_data[item['name']] is None or
(float(old_data[item['name']]) != float(
item['value']))):
data['vacuum_data']['changed'].append(item)
if 'vacuum_table' in data and 'changed' in data['vacuum_table']:
for item in data['vacuum_table']['changed']:
if 'value' in item.keys():
if item['value'] is None:
if old_data[item['name']] != item['value']:
data['vacuum_data']['reset'].append(item)
else:
if (old_data[item['name']] is None or
(float(old_data[item['name']]) != float(
item['value']))):
data['vacuum_data']['changed'].append(item)
# toast autovacuum: separate list of changed and reset data
if 'vacuum_toast' in data:
if 'changed' in data['vacuum_toast']:
for item in data['vacuum_toast']['changed']:
if 'value' in item.keys():
toast_key = 'toast_' + item['name']
item['name'] = 'toast.' + item['name']
if item['value'] is None:
if old_data[toast_key] != item['value']:
data['vacuum_data']['reset'].append(item)
else:
if (old_data[toast_key] is None or
(float(old_data[toast_key]) != float(
item['value']))):
data['vacuum_data']['changed'].append(item)
if 'vacuum_toast' in data and 'changed' in data['vacuum_toast']:
for item in data['vacuum_toast']['changed']:
if 'value' in item.keys():
toast_key = 'toast_' + item['name']
item['name'] = 'toast.' + item['name']
if item['value'] is None:
if old_data[toast_key] != item['value']:
data['vacuum_data']['reset'].append(item)
else:
if (old_data[toast_key] is None or
(float(old_data[toast_key]) != float(
item['value']))):
data['vacuum_data']['changed'].append(item)
acls = []
try:

View File

@ -48,9 +48,8 @@ class JobModule(CollectionNodeModule):
return servers.ServerModule.NODE_TYPE
def BackendSupported(self, manager, **kwargs):
if hasattr(self, 'show_node'):
if not self.show_node:
return False
if hasattr(self, 'show_node') and not self.show_node:
return False
conn = manager.connection()
@ -576,33 +575,32 @@ SELECT EXISTS(
format_schedule_data(changed_schedule)
has_connection_str = self.manager.db_info['pgAgent']['has_connstr']
if 'jsteps' in data and has_connection_str:
if 'changed' in data['jsteps']:
for changed_step in data['jsteps']['changed']:
if 'jstconntype' not in changed_step and (
'jstdbname' in changed_step or
'jstconnstr' in changed_step):
status, rset = self.conn.execute_dict(
render_template(
"/".join([self.template_path, 'steps.sql']),
jid=data['jobid'],
jstid=changed_step['jstid'],
conn=self.conn,
has_connstr=has_connection_str
)
if 'jsteps' in data and has_connection_str and \
'changed' in data['jsteps']:
for changed_step in data['jsteps']['changed']:
if 'jstconntype' not in changed_step and (
'jstdbname' in changed_step or
'jstconnstr' in changed_step):
status, rset = self.conn.execute_dict(
render_template(
"/".join([self.template_path, 'steps.sql']),
jid=data['jobid'],
jstid=changed_step['jstid'],
conn=self.conn,
has_connstr=has_connection_str
)
if not status:
return internal_server_error(errormsg=rset)
)
if not status:
return internal_server_error(errormsg=rset)
row = rset['rows'][0]
changed_step['jstconntype'] = row['jstconntype']
if row['jstconntype']:
if not ('jstdbname' in changed_step):
changed_step['jstdbname'] = row['jstdbname']
else:
if not ('jstconnstr' in changed_step):
changed_step['jstconnstr'] = row['jstconnstr']
row = rset['rows'][0]
changed_step['jstconntype'] = row['jstconntype']
if row['jstconntype']:
if not ('jstdbname' in changed_step):
changed_step['jstdbname'] = row['jstdbname']
else:
if not ('jstconnstr' in changed_step):
changed_step['jstconnstr'] = row['jstconnstr']
JobView.register_node_view(blueprint)

View File

@ -135,11 +135,11 @@ class RoleView(PGChildNodeView):
else:
data[key] = val
if u'rid' not in kwargs or kwargs['rid'] == -1:
if u'rolname' not in data:
return precondition_required(
_("Name must be specified.")
)
if (u'rid' not in kwargs or kwargs['rid'] == -1) and \
u'rolname' not in data:
return precondition_required(
_("Name must be specified.")
)
if u'rolvaliduntil' in data:
# Make date explicit so that it works with every
@ -275,10 +275,9 @@ rolmembership:{
else:
data[u'admins'].append(r[u'role'])
if self.manager.version >= 90200:
if u'seclabels' in data:
if u'rid' not in kwargs or kwargs['rid'] == -1:
msg = _("""
if self.manager.version >= 90200 and u'seclabels' in data:
if u'rid' not in kwargs or kwargs['rid'] == -1:
msg = _("""
Security Label must be passed as an array of JSON objects in the following
format:
seclabels:[{
@ -287,16 +286,16 @@ seclabels:[{
},
...
]""")
if type(data[u'seclabels']) != list:
return precondition_required(msg)
if type(data[u'seclabels']) != list:
return precondition_required(msg)
for s in data[u'seclabels']:
if type(s) != dict or \
u'provider' not in s or \
u'label' not in s:
return precondition_required(msg)
else:
msg = _("""
for s in data[u'seclabels']:
if type(s) != dict or \
u'provider' not in s or \
u'label' not in s:
return precondition_required(msg)
else:
msg = _("""
Security Label must be passed as an array of JSON objects in the following
format:
seclabels:{
@ -319,44 +318,44 @@ seclabels:{
...
]
""")
seclabels = data[u'seclabels']
if type(seclabels) != dict:
seclabels = data[u'seclabels']
if type(seclabels) != dict:
return precondition_required(msg)
if u'added' in seclabels:
new_seclabels = seclabels[u'added']
if type(new_seclabels) != list:
return precondition_required(msg)
if u'added' in seclabels:
new_seclabels = seclabels[u'added']
if type(new_seclabels) != list:
for s in new_seclabels:
if type(s) != dict or \
u'provider' not in s or \
u'label' not in s:
return precondition_required(msg)
for s in new_seclabels:
if type(s) != dict or \
u'provider' not in s or \
u'label' not in s:
return precondition_required(msg)
if u'deleted' in seclabels:
removed_seclabels = seclabels[u'deleted']
if u'deleted' in seclabels:
removed_seclabels = seclabels[u'deleted']
if type(removed_seclabels) != list:
return precondition_required(msg)
if type(removed_seclabels) != list:
for s in removed_seclabels:
if (type(s) != dict or u'provider' not in s):
return precondition_required(msg)
for s in removed_seclabels:
if (type(s) != dict or u'provider' not in s):
return precondition_required(msg)
if u'changed' in seclabels:
changed_seclabels = seclabels[u'deleted']
if u'changed' in seclabels:
changed_seclabels = seclabels[u'deleted']
if type(changed_seclabels) != list:
return precondition_required(msg)
if type(changed_seclabels) != list:
for s in changed_seclabels:
if type(s) != dict or \
u'provider' not in s and \
u'label' not in s:
return precondition_required(msg)
for s in changed_seclabels:
if type(s) != dict or \
u'provider' not in s and \
u'label' not in s:
return precondition_required(msg)
if u'variables' in data:
if u'rid' not in kwargs or kwargs['rid'] == -1:
msg = _("""
@ -521,11 +520,11 @@ rolmembership:{
user = self.manager.user_info
if not user['is_superuser'] and \
not user['can_create_role']:
if action != 'update' or 'rid' in kwargs:
if kwargs['rid'] != -1:
if user['id'] != kwargs['rid']:
return forbidden(forbidden_msg)
not user['can_create_role'] and \
(action != 'update' or 'rid' in kwargs) and \
kwargs['rid'] != -1 and \
user['id'] != kwargs['rid']:
return forbidden(forbidden_msg)
if fetch_name:
status, res = self.conn.execute_dict(