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): def store_crypt_key(app, user):
# in desktop mode, master password is used to encrypt/decrypt # in desktop mode, master password is used to encrypt/decrypt
# and is stored in the keyManager memory # and is stored in the keyManager memory
if config.SERVER_MODE: if config.SERVER_MODE and 'password' in request.form:
if 'password' in request.form: current_app.keyManager.set(request.form['password'])
current_app.keyManager.set(request.form['password'])
@user_logged_out.connect_via(app) @user_logged_out.connect_via(app)
def current_user_cleanup(app, user): def current_user_cleanup(app, user):

View File

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

View File

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

View File

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

View File

@ -410,28 +410,26 @@ class CollationView(PGChildNodeView, SchemaDiffObjectCompare):
for arg in definition_args: for arg in definition_args:
if ( if (
arg == 'locale' and 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 ( missing_definition_flag = True
'lc_collate' not in data and 'lc_type' not in data
):
missing_definition_flag = True
if ( if (
arg == 'copy_collation' and 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 ( missing_definition_flag = True
'lc_collate' not in data and 'lc_type' not in data
):
missing_definition_flag = True
if ( if (
(arg == 'lc_collate' or arg == 'lc_type') and (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 return missing_definition_flag

View File

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

View File

@ -394,12 +394,12 @@ class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
res['rows'][0]['oid'] <= self.datlastsysoid) res['rows'][0]['oid'] <= self.datlastsysoid)
# Handle templates and its schema name properly # Handle templates and its schema name properly
if res['rows'][0]['template_schema'] is not None: if res['rows'][0]['template_schema'] is not None and \
if res['rows'][0]['template_schema'] != "pg_catalog": res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent( res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'], self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template'] res['rows'][0]['template']
) )
if res['rows'][0]['options'] is not None: if res['rows'][0]['options'] is not None:
res['rows'][0]['options'] = self.tokenize_options( res['rows'][0]['options'] = self.tokenize_options(
@ -669,12 +669,12 @@ class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
data['schema'] = old_data['schema'] data['schema'] = old_data['schema']
# Handle templates and its schema name properly # Handle templates and its schema name properly
if old_data['template_schema'] is not None: if old_data['template_schema'] is not None and \
if old_data['template_schema'] != "pg_catalog": old_data['template_schema'] != "pg_catalog":
old_data['template'] = self.qtIdent( old_data['template'] = self.qtIdent(
self.conn, old_data['template_schema'], self.conn, old_data['template_schema'],
old_data['template'] old_data['template']
) )
# If user has changed the schema then fetch new schema directly # If user has changed the schema then fetch new schema directly
# using its oid otherwise fetch old schema name using its oid # 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 # Handle templates and its schema name properly
if res['rows'][0]['template_schema'] is not None: if res['rows'][0]['template_schema'] is not None and \
if res['rows'][0]['template_schema'] != "pg_catalog": res['rows'][0]['template_schema'] != "pg_catalog":
res['rows'][0]['template'] = self.qtIdent( res['rows'][0]['template'] = self.qtIdent(
self.conn, res['rows'][0]['template_schema'], self.conn, res['rows'][0]['template_schema'],
res['rows'][0]['template'] res['rows'][0]['template']
) )
if res['rows'][0]['options'] is not None: if res['rows'][0]['options'] is not None:
res['rows'][0]['options'] = self.tokenize_options( 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: for arg in required_args:
if isinstance(arg, list): if isinstance(arg, list):
for param in arg: for param in arg:
if param in data: if param in data and \
if is_key_str(param, data) or is_key_list(param, data): (is_key_str(param, data) or
break is_key_list(param, data)):
break
else: else:
return _('-- definition incomplete'), name return _('-- definition incomplete'), name

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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