Fixed following SonarQube issues:

1) Refactor function to reduce its Cognitive Complexity.
 2) Rename variable to match the regular expression ^[_a-z][a-z0-9_]*$.
This commit is contained in:
Nikhil Mohite 2020-06-26 15:03:50 +05:30 committed by Akshay Joshi
parent 8e28e0a32b
commit 115657a465
2 changed files with 183 additions and 150 deletions

View File

@ -458,6 +458,56 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
status=200 status=200
) )
def _get_argument_values(self, data):
proargtypes = [ptype for ptype in data['proargtypenames'].split(",")] \
if data['proargtypenames'] else []
proargmodes = data['proargmodes'] if data['proargmodes'] else \
['i'] * len(proargtypes)
proargnames = data['proargnames'] if data['proargnames'] else []
proargdefaultvals = [ptype for ptype in
data['proargdefaultvals'].split(",")] \
if data['proargdefaultvals'] else []
proallargtypes = data['proallargtypes'] \
if data['proallargtypes'] else []
return {'proargtypes': proargtypes, 'proargmodes': proargmodes,
'proargnames': proargnames,
'proargdefaultvals': proargdefaultvals,
'proallargtypes': proallargtypes}
def _params_list_for_display(self, proargmodes_fltrd, proargtypes,
proargnames, proargdefaultvals):
# Insert null value against the parameters which do not have
# default values.
if len(proargmodes_fltrd) > len(proargdefaultvals):
dif = len(proargmodes_fltrd) - len(proargdefaultvals)
while (dif > 0):
proargdefaultvals.insert(0, '')
dif -= 1
param = {"arguments": [
self._map_arguments_dict(
i, proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '',
proargtypes[i] if len(proargtypes) > i else '',
proargnames[i] if len(proargnames) > i else '',
proargdefaultvals[i] if len(proargdefaultvals) > i else ''
)
for i in range(len(proargtypes))]}
return param
def _display_properties_argument_list(self, proargmodes_fltrd,
proargtypes, proargnames,
proargdefaultvals):
proargs = [self._map_arguments_list(
proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '',
proargtypes[i] if len(proargtypes) > i else '',
proargnames[i] if len(proargnames) > i else '',
proargdefaultvals[i] if len(proargdefaultvals) > i else ''
)
for i in range(len(proargtypes))]
return proargs
def _format_arguments_from_db(self, data): def _format_arguments_from_db(self, data):
""" """
Create Argument list of the Function. Create Argument list of the Function.
@ -478,16 +528,12 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
proargnames: Argument Name proargnames: Argument Name
proargdefaultvals: Default Value of the Argument proargdefaultvals: Default Value of the Argument
""" """
proargtypes = [ptype for ptype in data['proargtypenames'].split(",")] \ arguments = self._get_argument_values(data)
if data['proargtypenames'] else [] proargtypes = arguments['proargtypes']
proargmodes = data['proargmodes'] if data['proargmodes'] else \ proargmodes = arguments['proargmodes']
['i'] * len(proargtypes) proargnames = arguments['proargnames']
proargnames = data['proargnames'] if data['proargnames'] else [] proargdefaultvals = arguments['proargdefaultvals']
proargdefaultvals = [ptype for ptype in proallargtypes = arguments['proallargtypes']
data['proargdefaultvals'].split(",")] \
if data['proargdefaultvals'] else []
proallargtypes = data['proallargtypes'] \
if data['proallargtypes'] else []
proargmodenames = { proargmodenames = {
'i': 'IN', 'o': 'OUT', 'b': 'INOUT', 'v': 'VARIADIC', 't': 'TABLE' 'i': 'IN', 'o': 'OUT', 'b': 'INOUT', 'v': 'VARIADIC', 't': 'TABLE'
@ -553,34 +599,16 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
for i in proargnames_fltrd: for i in proargnames_fltrd:
proargnames.remove(i) proargnames.remove(i)
# Insert null value against the parameters which do not have
# default values.
if len(proargmodes_fltrd) > len(proargdefaultvals):
dif = len(proargmodes_fltrd) - len(proargdefaultvals)
while (dif > 0):
proargdefaultvals.insert(0, '')
dif -= 1
# Prepare list of Argument list dict to be displayed in the Data Grid. # Prepare list of Argument list dict to be displayed in the Data Grid.
params = {"arguments": [ params = self._params_list_for_display(proargmodes_fltrd, proargtypes,
self._map_arguments_dict( proargnames, proargdefaultvals)
i, proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '',
proargtypes[i] if len(proargtypes) > i else '',
proargnames[i] if len(proargnames) > i else '',
proargdefaultvals[i] if len(proargdefaultvals) > i else ''
)
for i in range(len(proargtypes))]}
# Prepare string formatted Argument to be displayed in the Properties # Prepare string formatted Argument to be displayed in the Properties
# panel. # panel.
proargs = self._display_properties_argument_list(proargmodes_fltrd,
proargs = [self._map_arguments_list( proargtypes,
proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '', proargnames,
proargtypes[i] if len(proargtypes) > i else '', proargdefaultvals)
proargnames[i] if len(proargnames) > i else '',
proargdefaultvals[i] if len(proargdefaultvals) > i else ''
)
for i in range(len(proargtypes))]
proargs = {"proargs": ", ".join(proargs)} proargs = {"proargs": ", ".join(proargs)}
@ -768,22 +796,22 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
""" """
# Get SQL to create Function # Get SQL to create Function
status, SQL = self._get_sql(gid, sid, did, scid, self.request) status, sql = self._get_sql(gid, sid, did, scid, self.request)
if not status: if not status:
return internal_server_error(errormsg=SQL) return internal_server_error(errormsg=sql)
status, res = self.conn.execute_scalar(SQL) status, res = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
SQL = render_template( sql = render_template(
"/".join( "/".join(
[self.sql_template_path, 'get_oid.sql'] [self.sql_template_path, 'get_oid.sql']
), ),
nspname=self.request['pronamespace'], nspname=self.request['pronamespace'],
name=self.request['name'] name=self.request['name']
) )
status, res = self.conn.execute_dict(SQL) status, res = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
@ -834,8 +862,7 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
status, res = self.conn.execute_2darray(SQL) status, res = self.conn.execute_2darray(SQL)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
elif not res['rows']:
if not res['rows']:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=gettext( errormsg=gettext(
@ -1501,10 +1528,10 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
doid: Function Id doid: Function Id
""" """
# Fetch the function definition. # Fetch the function definition.
SQL = render_template("/".join([self.sql_template_path, sql = render_template("/".join([self.sql_template_path,
'get_definition.sql']), fnid=fnid, 'get_definition.sql']), fnid=fnid,
scid=scid) scid=scid)
status, res = self.conn.execute_2darray(SQL) status, res = self.conn.execute_2darray(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
@ -1516,9 +1543,9 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
) + '(' + res['rows'][0]['func_with_identity_arguments'] + ')' ) + '(' + res['rows'][0]['func_with_identity_arguments'] + ')'
# Fetch only arguments # Fetch only arguments
argString = name[name.rfind('('):].strip('(').strip(')') arg_string = name[name.rfind('('):].strip('(').strip(')')
if len(argString) > 0: if len(arg_string) > 0:
args = argString.split(',') args = arg_string.split(',')
# Remove unwanted spaces from arguments # Remove unwanted spaces from arguments
args = [arg.strip(' ') for arg in args] args = [arg.strip(' ') for arg in args]

View File

@ -12,7 +12,7 @@ import re
from functools import wraps from functools import wraps
import simplejson as json import simplejson as json
from flask import render_template, make_response, request, jsonify from flask import render_template, request, jsonify
from flask_babelex import gettext as _ from flask_babelex import gettext as _
import pgadmin.browser.server_groups.servers.databases as database import pgadmin.browser.server_groups.servers.databases as database
@ -22,12 +22,12 @@ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \ from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
parse_priv_to_db parse_priv_to_db
from pgadmin.browser.utils import PGChildNodeView from pgadmin.browser.utils import PGChildNodeView
from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
from pgadmin.utils.ajax import make_json_response, \ from pgadmin.utils.ajax import make_json_response, \
make_response as ajax_response, internal_server_error, \ make_response as ajax_response, internal_server_error, \
precondition_required, gone precondition_required, gone
from pgadmin.utils.driver import get_driver from pgadmin.utils.driver import get_driver
from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
class PackageModule(SchemaChildModule): class PackageModule(SchemaChildModule):
@ -139,11 +139,11 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
self.template_path = 'packages/ppas/#{0}#'.format( self.template_path = 'packages/ppas/#{0}#'.format(
self.manager.version) self.manager.version)
SQL = render_template( sql = render_template(
"/".join([self.template_path, 'get_schema.sql']), "/".join([self.template_path, 'get_schema.sql']),
scid=kwargs['scid'] scid=kwargs['scid']
) )
status, rset = self.conn.execute_scalar(SQL) status, rset = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=rset) return internal_server_error(errormsg=rset)
@ -200,12 +200,12 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
""" """
res = [] res = []
SQL = render_template( sql = render_template(
"/".join([self.template_path, 'nodes.sql']), "/".join([self.template_path, 'nodes.sql']),
scid=scid, scid=scid,
pkgid=pkgid pkgid=pkgid
) )
status, rset = self.conn.execute_dict(SQL) status, rset = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=rset) return internal_server_error(errormsg=rset)
@ -255,11 +255,11 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
""" """
res = [] res = []
SQL = render_template( sql = render_template(
"/".join([self.template_path, 'properties.sql']), "/".join([self.template_path, 'properties.sql']),
scid=scid, pkgid=pkgid scid=scid, pkgid=pkgid
) )
status, rset = self.conn.execute_dict(SQL) status, rset = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=rset) return internal_server_error(errormsg=rset)
@ -314,9 +314,9 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
:param pkgid: :param pkgid:
:return: :return:
""" """
SQL = render_template("/".join([self.template_path, 'properties.sql']), sql = render_template("/".join([self.template_path, 'properties.sql']),
scid=scid, pkgid=pkgid) scid=scid, pkgid=pkgid)
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)
@ -331,10 +331,10 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
res['rows'][0]['pkgbodysrc'] = self.get_inner( res['rows'][0]['pkgbodysrc'] = self.get_inner(
res['rows'][0]['pkgbodysrc']) res['rows'][0]['pkgbodysrc'])
SQL = render_template("/".join([self.template_path, 'acl.sql']), sql = render_template("/".join([self.template_path, 'acl.sql']),
scid=scid, scid=scid,
pkgid=pkgid) pkgid=pkgid)
status, rset1 = self.conn.execute_dict(SQL) status, rset1 = self.conn.execute_dict(sql)
if not status: if not status:
return False, internal_server_error(errormsg=rset1) return False, internal_server_error(errormsg=rset1)
@ -381,23 +381,23 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
) )
data['schema'] = self.schema data['schema'] = self.schema
SQL, name = self.getSQL(gid, sid, did, data, scid, None) sql, name = self.getSQL(gid, sid, did, data, scid, None)
status, msg = self.conn.execute_scalar(SQL) status, msg = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=msg) return internal_server_error(errormsg=msg)
# We need oid of newly created package. # We need oid of newly created package.
SQL = render_template( sql = render_template(
"/".join([ "/".join([
self.template_path, 'get_oid.sql' self.template_path, 'get_oid.sql'
]), ]),
name=data['name'], scid=scid name=data['name'], scid=scid
) )
SQL = SQL.strip('\n').strip(' ') sql = sql.strip('\n').strip(' ')
if SQL and SQL != "": if sql and sql != "":
status, pkgid = self.conn.execute_scalar(SQL) status, pkgid = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=pkgid) return internal_server_error(errormsg=pkgid)
@ -443,15 +443,15 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
try: try:
for pkgid in data['ids']: for pkgid in data['ids']:
SQL = render_template( sql = render_template(
"/".join([self.template_path, 'properties.sql']), "/".join([self.template_path, 'properties.sql']),
scid=scid, scid=scid,
pkgid=pkgid) pkgid=pkgid)
status, res = self.conn.execute_dict(SQL) status, res = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if not res['rows']: elif not res['rows']:
return make_json_response( return make_json_response(
success=0, success=0,
errormsg=_( errormsg=_(
@ -464,15 +464,15 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
res['rows'][0]['schema'] = self.schema res['rows'][0]['schema'] = self.schema
SQL = render_template("/".join([self.template_path, sql = render_template("/".join([self.template_path,
'delete.sql']), 'delete.sql']),
data=res['rows'][0], data=res['rows'][0],
cascade=cascade) cascade=cascade)
if only_sql: if only_sql:
return SQL return sql
status, res = self.conn.execute_scalar(SQL) status, res = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
@ -503,13 +503,13 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
request.data, encoding='utf-8' request.data, encoding='utf-8'
) )
SQL, name = self.getSQL(gid, sid, did, data, scid, pkgid) sql, name = self.getSQL(gid, sid, did, data, scid, pkgid)
# Most probably this is due to error # Most probably this is due to error
if not isinstance(SQL, str): if not isinstance(sql, str):
return SQL return sql
SQL = SQL.strip('\n').strip(' ') sql = sql.strip('\n').strip(' ')
status, res = self.conn.execute_scalar(SQL) status, res = self.conn.execute_scalar(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
@ -558,16 +558,16 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
).format(arg) ).format(arg)
) )
SQL, name = self.getSQL(gid, sid, did, data, scid, pkgid) sql, name = self.getSQL(gid, sid, did, data, scid, pkgid)
# Most probably this is due to error # Most probably this is due to error
if not isinstance(SQL, str): if not isinstance(sql, str):
return SQL return sql
SQL = SQL.strip('\n').strip(' ') sql = sql.strip('\n').strip(' ')
if SQL == '': if sql == '':
SQL = "--modified SQL" sql = "--modified SQL"
return make_json_response( return make_json_response(
data=SQL, data=sql,
status=200 status=200
) )
@ -586,80 +586,86 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
diff_schema: Target Schema diff_schema: Target Schema
""" """
required_args = [
u'name'
]
if diff_schema: if diff_schema:
data['schema'] = diff_schema data['schema'] = diff_schema
else: else:
data['schema'] = self.schema data['schema'] = self.schema
if pkgid is not None and not sqltab: if pkgid is not None and not sqltab:
SQL = render_template( return self.get_sql_with_pkgid(scid, pkgid, data, diff_schema)
"/".join([self.template_path, 'properties.sql']), scid=scid,
pkgid=pkgid)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(
errormsg=_("Could not find the package in the database.")
)
res['rows'][0]['pkgheadsrc'] = self.get_inner(
res['rows'][0]['pkgheadsrc'])
res['rows'][0]['pkgbodysrc'] = self.get_inner(
res['rows'][0]['pkgbodysrc'])
SQL = render_template("/".join([self.template_path, 'acl.sql']),
scid=scid,
pkgid=pkgid)
status, rset1 = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset1)
for row in rset1['rows']:
priv = parse_priv_from_db(row)
res['rows'][0].setdefault(row['deftype'], []).append(priv)
# Making copy of output for further processing
old_data = dict(res['rows'][0])
# To format privileges data coming from client
for key in ['pkgacl']:
if key in data and data[key] is not None:
if 'added' in data[key]:
data[key]['added'] = parse_priv_to_db(
data[key]['added'], self.acl)
if 'changed' in data[key]:
data[key]['changed'] = parse_priv_to_db(
data[key]['changed'], self.acl)
if 'deleted' in data[key]:
data[key]['deleted'] = parse_priv_to_db(
data[key]['deleted'], self.acl)
# If name is not present with in update data then copy it
# from old data
for arg in required_args:
if arg not in data:
data[arg] = old_data[arg]
SQL = render_template("/".join([self.template_path, 'update.sql']),
data=data, o_data=old_data, conn=self.conn,
is_schema_diff=diff_schema)
return SQL, data['name'] if 'name' in data else old_data['name']
else: else:
# To format privileges coming from client # To format privileges coming from client
if 'pkgacl' in data: if 'pkgacl' in data:
data['pkgacl'] = parse_priv_to_db(data['pkgacl'], self.acl) data['pkgacl'] = parse_priv_to_db(data['pkgacl'], self.acl)
SQL = render_template("/".join([self.template_path, 'create.sql']), sql = render_template("/".join([self.template_path, 'create.sql']),
data=data, conn=self.conn) data=data, conn=self.conn)
return SQL, data['name'] return sql, data['name']
def format_privilege_data(self, data):
# To format privileges data coming from client
for key in ['pkgacl']:
if key in data and data[key] is not None:
if 'added' in data[key]:
data[key]['added'] = parse_priv_to_db(
data[key]['added'], self.acl)
if 'changed' in data[key]:
data[key]['changed'] = parse_priv_to_db(
data[key]['changed'], self.acl)
if 'deleted' in data[key]:
data[key]['deleted'] = parse_priv_to_db(
data[key]['deleted'], self.acl)
def get_sql_with_pkgid(self, scid, pkgid, data, diff_schema):
required_args = [
u'name'
]
sql = render_template(
"/".join([self.template_path, 'properties.sql']), scid=scid,
pkgid=pkgid)
status, res = self.conn.execute_dict(sql)
if not status:
return internal_server_error(errormsg=res)
elif len(res['rows']) == 0:
return gone(
errormsg=_("Could not find the package in the database.")
)
res['rows'][0]['pkgheadsrc'] = self.get_inner(
res['rows'][0]['pkgheadsrc'])
res['rows'][0]['pkgbodysrc'] = self.get_inner(
res['rows'][0]['pkgbodysrc'])
sql = render_template("/".join([self.template_path, 'acl.sql']),
scid=scid,
pkgid=pkgid)
status, rset1 = self.conn.execute_dict(sql)
if not status:
return internal_server_error(errormsg=rset1)
for row in rset1['rows']:
priv = parse_priv_from_db(row)
res['rows'][0].setdefault(row['deftype'], []).append(priv)
# Making copy of output for further processing
old_data = dict(res['rows'][0])
# To format privileges data coming from client
self.format_privilege_data(data)
# If name is not present with in update data then copy it
# from old data
for arg in required_args:
if arg not in data:
data[arg] = old_data[arg]
sql = render_template("/".join([self.template_path, 'update.sql']),
data=data, o_data=old_data, conn=self.conn,
is_schema_diff=diff_schema)
return sql, data['name'] if 'name' in data else old_data['name']
@check_precondition(action="sql") @check_precondition(action="sql")
def sql(self, gid, sid, did, scid, pkgid, diff_schema=None, def sql(self, gid, sid, did, scid, pkgid, diff_schema=None,
@ -677,10 +683,10 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
json_resp: json response or plain text response json_resp: json response or plain text response
""" """
try: try:
SQL = render_template( sql = render_template(
"/".join([self.template_path, 'properties.sql']), scid=scid, "/".join([self.template_path, 'properties.sql']), scid=scid,
pkgid=pkgid) pkgid=pkgid)
status, res = self.conn.execute_dict(SQL) status, res = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)
if len(res['rows']) == 0: if len(res['rows']) == 0:
@ -693,10 +699,10 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
res['rows'][0]['pkgbodysrc'] = self.get_inner( res['rows'][0]['pkgbodysrc'] = self.get_inner(
res['rows'][0]['pkgbodysrc']) res['rows'][0]['pkgbodysrc'])
SQL = render_template("/".join([self.template_path, 'acl.sql']), sql = render_template("/".join([self.template_path, 'acl.sql']),
scid=scid, scid=scid,
pkgid=pkgid) pkgid=pkgid)
status, rset1 = self.conn.execute_dict(SQL) status, rset1 = self.conn.execute_dict(sql)
if not status: if not status:
return internal_server_error(errormsg=rset1) return internal_server_error(errormsg=rset1)
@ -805,9 +811,9 @@ class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
if self.manager.server_type != 'ppas': if self.manager.server_type != 'ppas':
return res return res
SQL = render_template("/".join([self.template_path, sql = render_template("/".join([self.template_path,
'nodes.sql']), scid=scid) 'nodes.sql']), scid=scid)
status, rset = self.conn.execute_2darray(SQL) status, rset = self.conn.execute_2darray(sql)
if not status: if not status:
return internal_server_error(errormsg=res) return internal_server_error(errormsg=res)