Fixed code smells 'Define a constant instead of duplicating this literal' reported by SonarQube.

This commit is contained in:
Akshay Joshi 2020-09-29 15:08:14 +05:30
parent c7c199210d
commit 1c70a43b91
22 changed files with 167 additions and 176 deletions

View File

@ -69,4 +69,5 @@ def upgrade():
def downgrade():
# pgAdmin only upgrades, downgrade not implemented.
pass

View File

@ -1192,11 +1192,13 @@ class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
self.conn, resp_data['pronamespace'], resp_data['proname']),
resp_data['proargtypenames'].lstrip('(').rstrip(')'))
pattern = '\n{2,}'
repl = '\n\n'
if not json_resp:
return re.sub('\n{2,}', '\n\n', func_def)
return re.sub(pattern, repl, func_def)
sql = sql_header + func_def
sql = re.sub('\n{2,}', '\n\n', sql)
sql = re.sub(pattern, repl, sql)
return ajax_response(response=sql)

View File

@ -153,6 +153,7 @@ class CheckConstraintView(PGChildNodeView):
- Validate check constraint.
"""
node_type = blueprint.node_type
CHECK_CONSTRAINT_PATH = 'check_constraint/sql/#{0}#'
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -201,7 +202,7 @@ class CheckConstraintView(PGChildNodeView):
kwargs['did'] in self.manager.db_info else 0
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(
self.template_path = self.CHECK_CONSTRAINT_PATH.format(
self.manager.version)
schema, table = check_utils.get_parent(self.conn, kwargs['tid'])
@ -265,7 +266,7 @@ class CheckConstraintView(PGChildNodeView):
self.qtIdent = driver.qtIdent
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(
self.template_path = self.CHECK_CONSTRAINT_PATH.format(
self.manager.version)
schema, table = check_utils.get_parent(self.conn, tid)
@ -382,7 +383,7 @@ class CheckConstraintView(PGChildNodeView):
self.qtIdent = driver.qtIdent
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(
self.template_path = self.CHECK_CONSTRAINT_PATH.format(
self.manager.version)
schema, table = check_utils.get_parent(self.conn, tid)

View File

@ -180,6 +180,7 @@ class ExclusionConstraintView(PGChildNodeView):
"""
node_type = 'exclusion_constraint'
EXCLUSION_CONSTRAINT_PATH = 'exclusion_constraint/sql/#{0}#'
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -226,7 +227,7 @@ class ExclusionConstraintView(PGChildNodeView):
if self.manager.db_info is not None and \
kwargs['did'] in self.manager.db_info else 0
self.template_path = 'exclusion_constraint/sql/#{0}#'.format(
self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
@ -327,7 +328,7 @@ class ExclusionConstraintView(PGChildNodeView):
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'exclusion_constraint/sql/#{0}#'.format(
self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
@ -438,7 +439,7 @@ class ExclusionConstraintView(PGChildNodeView):
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'exclusion_constraint/sql/#{0}#'.format(
self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name

View File

@ -184,6 +184,7 @@ class ForeignKeyConstraintView(PGChildNodeView):
"""
node_type = 'foreign_key'
FOREIGN_KEY_PATH = 'foreign_key/sql/#{0}#'
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -232,7 +233,7 @@ class ForeignKeyConstraintView(PGChildNodeView):
self.manager.db_info[kwargs['did']]['datlastsysoid'] \
if self.manager.db_info is not None and \
kwargs['did'] in self.manager.db_info else 0
self.template_path = 'foreign_key/sql/#{0}#'.format(
self.template_path = self.FOREIGN_KEY_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
@ -337,7 +338,7 @@ class ForeignKeyConstraintView(PGChildNodeView):
"""
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'foreign_key/sql/#{0}#'.format(
self.template_path = self.FOREIGN_KEY_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
@ -448,8 +449,7 @@ class ForeignKeyConstraintView(PGChildNodeView):
"""
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'foreign_key/sql/#{0}#'.format(
self.manager.version)
self.template_path = self.FOREIGN_KEY_PATH.format(self.manager.version)
# We need parent's name eg table name and schema name
schema, table = fkey_utils.get_parent(self.conn, tid)

View File

@ -200,6 +200,7 @@ class IndexConstraintView(PGChildNodeView):
node_type = 'index_constraint'
node_label = _('Index constraint')
INDEX_CONSTRAINT_PATH = 'index_constraint/sql/#{0}#'
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -245,8 +246,8 @@ class IndexConstraintView(PGChildNodeView):
self.manager.db_info[kwargs['did']]['datlastsysoid'] \
if self.manager.db_info is not None and \
kwargs['did'] in self.manager.db_info else 0
self.template_path = 'index_constraint/sql/#{0}#'\
.format(self.manager.version)
self.template_path = self.INDEX_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
schema, table = idxcons_utils.get_parent(self.conn, kwargs['tid'])
@ -344,8 +345,8 @@ class IndexConstraintView(PGChildNodeView):
"""
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'index_constraint/sql/#{0}#'\
.format(self.manager.version)
self.template_path = self.INDEX_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
schema, table = idxcons_utils.get_parent(self.conn, tid)
@ -460,8 +461,8 @@ class IndexConstraintView(PGChildNodeView):
"""
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.template_path = 'index_constraint/sql/#{0}#'\
.format(self.manager.version)
self.template_path = self.INDEX_CONSTRAINT_PATH.format(
self.manager.version)
# We need parent's name eg table name and schema name
schema, table = idxcons_utils.get_parent(self.conn, tid)

View File

@ -135,33 +135,6 @@ class ConstraintDeleteMultipleTestCase(BaseTestGenerator):
# Assert response
utils.assert_status_code(self, response)
# data = {'ids': [
# {'id': self.check_constraint_id, '_type': 'check_constraint'},
# {'id': self.check_constraint_id_1, '_type': 'check_constraint'},
# {'id': self.exclustion_constraint_id,
# '_type': 'exclustion_constraint'},
# {'id': self.foreign_key_id, '_type': 'foreign_key'},
# {'id': self.primary_key_id, '_type': 'index_constraint'},
# {'id': self.unique_constraint_id, '_type': 'index_constraint'}
# ]}
# response = self.tester.delete(self.url + str(utils.SERVER_GROUP) +
# '/' + str(self.server_id) + '/' +
# str(self.db_id) + '/' +
# str(self.schema_id) + '/' +
# str(self.table_id) + '/',
# data=json.dumps(data),
# content_type='html/json',
# follow_redirects=True)
# response = self.tester.get(self.url + str(utils.SERVER_GROUP) +
# '/' + str(self.server_id) + '/' +
# str(self.db_id) + '/' +
# str(self.schema_id) + '/' +
# str(self.table_id) + '/',
# data=json.dumps(data),
# content_type='html/json',
# follow_redirects=True)
# self.assertEquals(response.status_code, 200)
def tearDown(self):
# Disconnect the database
database_utils.disconnect_database(self, self.server_id, self.db_id)

View File

@ -83,6 +83,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
"""
node_label = "Table"
pattern = '\n{2,}'
double_newline = '\n\n'
@staticmethod
def check_precondition(f):
@ -495,7 +497,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
data=data, conn=self.conn, is_sql=True)
# Add into main sql
table_sql = re.sub('\n{2,}', '\n\n', table_sql)
table_sql = re.sub(self.pattern, self.double_newline, table_sql)
main_sql.append(table_sql.strip('\n'))
def _get_resql_for_index(self, did, tid, main_sql, json_resp, schema,
@ -523,7 +525,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
index_sql = "\n" + index_sql
# Add into main sql
index_sql = re.sub('\n{2,}', '\n\n', index_sql)
index_sql = re.sub(self.pattern, self.double_newline, index_sql)
main_sql.append(index_sql.strip('\n'))
@ -553,7 +555,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
policy_sql = "\n" + policy_sql
# Add into main sql
policy_sql = re.sub('\n{2,}', '\n\n', policy_sql)
policy_sql = re.sub(self.pattern, self.double_newline,
policy_sql)
main_sql.append(policy_sql.strip('\n'))
@ -579,7 +582,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
trigger_sql = "\n" + trigger_sql
# Add into main sql
trigger_sql = re.sub('\n{2,}', '\n\n', trigger_sql)
trigger_sql = re.sub(self.pattern, self.double_newline,
trigger_sql)
main_sql.append(trigger_sql)
def _get_resql_for_compound_triggers(self, tid, main_sql, schema, table):
@ -608,7 +612,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
# Add into main sql
compound_trigger_sql = \
re.sub('\n{2,}', '\n\n', compound_trigger_sql)
re.sub(self.pattern, self.double_newline,
compound_trigger_sql)
main_sql.append(compound_trigger_sql)
def _get_resql_for_rules(self, tid, main_sql, table, json_resp):
@ -648,7 +653,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
data=res_data, display_comments=display_comments)
# Add into main sql
rules_sql = re.sub('\n{2,}', '\n\n', rules_sql)
rules_sql = re.sub(self.pattern, self.double_newline, rules_sql)
main_sql.append(rules_sql)
def _get_resql_for_partitions(self, data, rset, json_resp,
@ -737,12 +742,12 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
data=part_data, conn=self.conn) + '\n'
# Add into main sql
partition_sql = re.sub('\n{2,}', '\n\n', partition_sql
).strip('\n')
partition_sql = re.sub(self.pattern, self.double_newline,
partition_sql).strip('\n')
partition_main_sql = partition_sql.strip('\n')
if not diff_partition_sql:
main_sql.append(
sql_header + '\n\n' + partition_main_sql
sql_header + self.double_newline + partition_main_sql
)
def get_reverse_engineered_sql(self, **kwargs):
@ -980,7 +985,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
if 'inheritedfrom' not in c:
column_sql += render_template("/".join(
[self.column_template_path, self._DELETE_SQL]),
data=c, conn=self.conn).strip('\n') + '\n\n'
data=c, conn=self.conn).strip('\n') + \
self.double_newline
return column_sql
def _check_for_column_update(self, columns, data, column_sql, tid):
@ -1023,7 +1029,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
column_sql += render_template("/".join(
[self.column_template_path, self._UPDATE_SQL]),
data=c, o_data=old_col_data, conn=self.conn
).strip('\n') + '\n\n'
).strip('\n') + self.double_newline
return column_sql
def _check_for_column_add(self, columns, data, column_sql):
@ -1039,7 +1045,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
'inheritedfromtable' not in c:
column_sql += render_template("/".join(
[self.column_template_path, self._CREATE_SQL]),
data=c, conn=self.conn).strip('\n') + '\n\n'
data=c, conn=self.conn).strip('\n') + \
self.double_newline
return column_sql
def _check_for_partitions_in_sql(self, data, old_data, sql):
@ -1069,7 +1076,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
]
),
data=temp_data,
conn=self.conn).strip('\n') + '\n\n'
conn=self.conn).strip('\n') + self.double_newline
# If partition(s) is/are added
if 'added' in partitions and 'partition_scheme' in old_data \
@ -1083,7 +1090,8 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
temp_data['partitions'] = partitions['added']
partitions_sql += \
self.get_partitions_sql(temp_data).strip('\n') + '\n\n'
self.get_partitions_sql(temp_data).strip('\n') + \
self.double_newline
# Combine all the SQL together
sql += '\n' + partitions_sql.strip('\n')
@ -1196,7 +1204,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
o_data=old_data, data=data, conn=self.conn
)
# Removes training new lines
sql = sql.strip('\n') + '\n\n'
sql = sql.strip('\n') + self.double_newline
# Parse/Format columns & create sql
if 'columns' in data:
@ -1267,7 +1275,7 @@ class BaseTableView(PGChildNodeView, BasePartitionTable):
# Append SQL for partitions
sql += '\n' + partitions_sql
sql = re.sub('\n{2,}', '\n\n', sql)
sql = re.sub(self.pattern, self.double_newline, sql)
sql = sql.strip('\n')
return sql, data['name'] if 'name' in data else old_data['name']

View File

@ -178,6 +178,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
"""
node_type = blueprint.node_type
icon_str = "icon-%s"
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -326,7 +327,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
rset['rows'][0]['oid'],
scid,
rset['rows'][0]['name'],
icon="icon-%s" % self.node_type
icon=self.icon_str % self.node_type
)
return make_json_response(
@ -367,7 +368,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
row['oid'],
scid,
row['name'],
icon="icon-%s" % self.node_type
icon=self.icon_str % self.node_type
))
return make_json_response(
@ -723,7 +724,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
res = [{'label': '', 'value': ''}]
try:
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
subtype=True)
status, rset = self.conn.execute_2darray(SQL)
if not status:
@ -753,7 +754,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
try:
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
subtype_opclass=True, data=data)
if SQL:
status, rset = self.conn.execute_2darray(SQL)
@ -784,14 +785,14 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
try:
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
get_opcintype=True, data=data)
if SQL:
status, opcintype = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=opcintype)
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
opcintype=opcintype, conn=self.conn)
status, rset = self.conn.execute_2darray(SQL)
if not status:
@ -825,7 +826,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
# We want to send data only if in we are in edit mode
# else we will disable the combobox
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
getoid=True, data=data)
if SQL:
status, oid = self.conn.execute_scalar(SQL)
@ -836,7 +837,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
canonical = False
SQL = render_template("/".join([self.template_path,
'get_subtypes.sql']),
self._GET_SUBTYPES_SQL]),
canonical=canonical, conn=self.conn, oid=oid)
if SQL:
status, rset = self.conn.execute_2darray(SQL)
@ -868,7 +869,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
# The SQL generated below will populate Input/Output/Send/
# Receive/Analyze/TypModeIN/TypModOUT combo box
sql = render_template("/".join([self.template_path,
'get_external_functions.sql']),
self._GET_EXTERNAL_FUNCTIONS_SQL]),
extfunc=True)
if sql:
status, rset = self.conn.execute_2darray(sql)
@ -882,7 +883,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
# The SQL generated below will populate TypModeIN combo box
sql = render_template("/".join([self.template_path,
'get_external_functions.sql']),
self._GET_EXTERNAL_FUNCTIONS_SQL]),
typemodin=True)
if sql:
status, rset = self.conn.execute_2darray(sql)
@ -912,7 +913,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
:return:
"""
sql = render_template("/".join([self.template_path,
'get_external_functions.sql']),
self._GET_EXTERNAL_FUNCTIONS_SQL]),
typemodout=True)
if sql:
status, rset = self.conn.execute_2darray(sql)
@ -1076,7 +1077,7 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
tid,
scid,
name,
icon="icon-%s" % self.node_type
icon=self.icon_str % self.node_type
)
)
except Exception as e:
@ -1248,22 +1249,23 @@ class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
'typtype'
]
definition_incomplete = "-- definition incomplete"
for arg in required_args:
if arg not in data:
return "-- definition incomplete"
return definition_incomplete
# Additional checks go here
# If type is range then check if subtype is defined or not
if data.get(arg, None) == 'r' and \
data.get('typname', None) is None:
return "-- definition incomplete"
return definition_incomplete
# If type is external then check if input/output
# conversion function is defined
if data.get(arg, None) == 'b' and (
data.get('typinput', None) is None or
data.get('typoutput', None) is None):
return "-- definition incomplete"
return definition_incomplete
# Privileges
if data.get('typacl', None):

View File

@ -313,6 +313,7 @@ class ViewNode(PGChildNodeView, VacuumSettings, SchemaDiffObjectCompare):
node_type = view_blueprint.node_type
_SQL_PREFIX = 'sql/'
_ALLOWED_PRIVS_JSON = 'sql/allowed_privs.json'
PROPERTIES_PATH = 'sql/{0}/#{1}#/properties.sql'
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -1098,7 +1099,7 @@ class ViewNode(PGChildNodeView, VacuumSettings, SchemaDiffObjectCompare):
for trigger in data['rows']:
SQL = render_template("/".join(
[self.ct_trigger_temp_path,
'sql/{0}/#{1}#/properties.sql'.format(
self.PROPERTIES_PATH.format(
self.manager.server_type, self.manager.version)]),
tid=vid,
trid=trigger['oid']
@ -1194,7 +1195,7 @@ class ViewNode(PGChildNodeView, VacuumSettings, SchemaDiffObjectCompare):
sql_data = ''
SQL = render_template("/".join(
[self.trigger_temp_path,
'sql/{0}/#{1}#/properties.sql'.format(
self.PROPERTIES_PATH.format(
self.manager.server_type, self.manager.version)]),
tid=vid)
@ -1205,7 +1206,7 @@ class ViewNode(PGChildNodeView, VacuumSettings, SchemaDiffObjectCompare):
for trigger in data['rows']:
SQL = render_template("/".join(
[self.trigger_temp_path,
'sql/{0}/#{1}#/properties.sql'.format(
self.PROPERTIES_PATH.format(
self.manager.server_type, self.manager.version)]),
tid=vid,
trid=trigger['oid']
@ -1743,6 +1744,7 @@ class MViewNode(ViewNode, VacuumSettings):
"""
node_type = mview_blueprint.node_type
operations = mview_operations
TOAST_STR = 'toast.'
def __init__(self, *args, **kwargs):
"""
@ -1879,7 +1881,7 @@ class MViewNode(ViewNode, VacuumSettings):
if 'value' in item.keys() and
item['value'] is not None]
vacuum_toast = [
{'name': 'toast.' + item['name'], 'value': item['value']}
{'name': self.TOAST_STR + item['name'], 'value': item['value']}
for item in data.get('vacuum_toast', [])
if 'value' in item.keys() and item['value'] is not None]
@ -1953,7 +1955,7 @@ class MViewNode(ViewNode, VacuumSettings):
if
'value' in item.keys() and item['value'] is not None]
vacuum_toast = [
{'name': 'toast.' + item['name'], 'value': item['value']}
{'name': self.TOAST_STR + item['name'], 'value': item['value']}
for item in result['vacuum_toast'] if
'value' in item.keys() and item['value'] is not None]
@ -2111,7 +2113,7 @@ class MViewNode(ViewNode, VacuumSettings):
res['rows'][0]['vacuum_settings_str'] += '\n' \
if res['rows'][0]['vacuum_settings_str'] != "" else ""
res['rows'][0]['vacuum_settings_str'] += '\n'.\
join(map(lambda o: 'toast.' + o,
join(map(lambda o: self.TOAST_STR + o,
res['rows'][0]['toast_reloptions']))
res['rows'][0]['vacuum_settings_str'] = res['rows'][0][

View File

@ -146,6 +146,7 @@ class JobStepView(PGChildNodeView):
"""
node_type = blueprint.node_type
STEP_NOT_FOUND = "Could not find the specified job step."
parent_ids = [
{'type': 'int', 'id': 'gid'},
@ -266,7 +267,7 @@ SELECT EXISTS(
if jstid is not None:
if len(result['rows']) == 0:
return gone(errormsg="Could not find the specified job step.")
return gone(errormsg=self.STEP_NOT_FOUND)
row = result['rows'][0]
return make_json_response(
@ -322,7 +323,7 @@ SELECT EXISTS(
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(errormsg="Could not find the specified job step.")
return gone(errormsg=self.STEP_NOT_FOUND)
return ajax_response(
response=res['rows'][0],
@ -423,9 +424,7 @@ SELECT EXISTS(
if len(res['rows']) == 0:
return gone(
errormsg=gettext(
"Could not find the specified job step."
)
errormsg=gettext(self.STEP_NOT_FOUND)
)
row = res['rows'][0]
data['jstconntype'] = row['jstconntype']
@ -549,9 +548,7 @@ SELECT EXISTS(
if len(res['rows']) == 0:
return gone(
errormsg=gettext(
"Could not find the specified job step."
)
errormsg=gettext(self.STEP_NOT_FOUND)
)
row = res['rows'][0]
data['jstconntype'] = row['jstconntype']

View File

@ -113,9 +113,9 @@ class PGChildModule(object):
super(PGChildModule, self).__init__()
def backend_supported(self, manager, **kwargs):
if hasattr(self, 'show_node'):
if not self.show_node:
if hasattr(self, 'show_node') and not self.show_node:
return False
sversion = getattr(manager, 'sversion', None)
if sversion is None or not isinstance(sversion, int):
@ -391,6 +391,8 @@ class PGChildNodeView(NodeView):
_GET_SCHEMA_OID_SQL = 'get_schema_oid.sql'
_GET_COLUMNS_SQL = 'get_columns.sql'
_GET_COLUMNS_FOR_TABLE_SQL = 'get_columns_for_table.sql'
_GET_SUBTYPES_SQL = 'get_subtypes.sql'
_GET_EXTERNAL_FUNCTIONS_SQL = 'get_external_functions.sql'
def get_children_nodes(self, manager, **kwargs):
"""

View File

@ -70,6 +70,8 @@ class DashboardModule(PgAdminModule):
register_preferences
Register preferences for this module.
"""
help_string = gettext('The number of seconds between graph samples.')
# Register options for the PG and PPAS help paths
self.dashboard_preference = Preferences(
'dashboards', gettext('Dashboards')
@ -80,7 +82,7 @@ class DashboardModule(PgAdminModule):
gettext("Session statistics refresh rate"), 'integer',
1, min_val=1, max_val=999999,
category_label=gettext('Graphs'),
help_str=gettext('The number of seconds between graph samples.')
help_str=help_string
)
self.tps_stats_refresh = self.dashboard_preference.register(
@ -88,7 +90,7 @@ class DashboardModule(PgAdminModule):
gettext("Transaction throughput refresh rate"), 'integer',
1, min_val=1, max_val=999999,
category_label=gettext('Graphs'),
help_str=gettext('The number of seconds between graph samples.')
help_str=help_string
)
self.ti_stats_refresh = self.dashboard_preference.register(
@ -96,7 +98,7 @@ class DashboardModule(PgAdminModule):
gettext("Tuples in refresh rate"), 'integer',
1, min_val=1, max_val=999999,
category_label=gettext('Graphs'),
help_str=gettext('The number of seconds between graph samples.')
help_str=help_string
)
self.to_stats_refresh = self.dashboard_preference.register(
@ -104,7 +106,7 @@ class DashboardModule(PgAdminModule):
gettext("Tuples out refresh rate"), 'integer',
1, min_val=1, max_val=999999,
category_label=gettext('Graphs'),
help_str=gettext('The number of seconds between graph samples.')
help_str=help_string
)
self.bio_stats_refresh = self.dashboard_preference.register(
@ -112,7 +114,7 @@ class DashboardModule(PgAdminModule):
gettext("Block I/O statistics refresh rate"), 'integer',
1, min_val=1, max_val=999999,
category_label=gettext('Graphs'),
help_str=gettext('The number of seconds between graph samples.')
help_str=help_string
)
self.display_graphs = self.dashboard_preference.register(

View File

@ -38,6 +38,7 @@ PROCESS_NOT_STARTED = 0
PROCESS_STARTED = 1
PROCESS_FINISHED = 2
PROCESS_TERMINATED = 3
PROCESS_NOT_FOUND = _("Could not find a process with the specified ID.")
def get_current_time(format='%Y-%m-%d %H:%M:%S.%f %z'):
@ -78,9 +79,7 @@ class BatchProcess(object):
p = Process.query.filter_by(pid=_id, user_id=current_user.id).first()
if p is None:
raise LookupError(
_("Could not find a process with the specified ID.")
)
raise LookupError(PROCESS_NOT_FOUND)
tmp_desc = loads(p.desc)
@ -623,9 +622,7 @@ class BatchProcess(object):
).first()
if p is None:
raise LookupError(
_("Could not find a process with the specified ID.")
)
raise LookupError(PROCESS_NOT_FOUND)
if p.end_time is not None:
logdir = p.logdir
@ -666,9 +663,7 @@ class BatchProcess(object):
).first()
if p is None:
raise LookupError(
_("Could not find a process with the specified ID.")
)
raise LookupError(PROCESS_NOT_FOUND)
try:
process = psutil.Process(p.utility_pid)

View File

@ -785,6 +785,8 @@ class Filemanager(object):
Returns a JSON object containing information
about the given file.
"""
date_created = 'Date Created'
date_modified = 'Date Modified'
path = unquote(path)
if self.dir is None:
self.dir = ""
@ -801,8 +803,8 @@ class Filemanager(object):
'Code': 0,
'Info': '',
'Properties': {
'Date Created': '',
'Date Modified': '',
date_created: '',
date_modified: '',
'Width': '',
'Height': '',
'Size': ''
@ -819,8 +821,8 @@ class Filemanager(object):
'Code': 1,
'Info': '',
'Properties': {
'Date Created': '',
'Date Modified': '',
date_created: '',
date_modified: '',
'Width': '',
'Height': '',
'Size': ''
@ -842,8 +844,8 @@ class Filemanager(object):
created = time.ctime(os.path.getctime(orig_path))
modified = time.ctime(os.path.getmtime(orig_path))
thefile['Properties']['Date Created'] = created
thefile['Properties']['Date Modified'] = modified
thefile['Properties'][date_created] = created
thefile['Properties'][date_modified] = modified
thefile['Properties']['Size'] = sizeof_fmt(getsize(orig_path))
return thefile

View File

@ -38,11 +38,12 @@ SCHEMA_VERSION = 27
##########################################################################
db = SQLAlchemy()
USER_ID = 'user.id'
# Define models
roles_users = db.Table(
'roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('user_id', db.Integer(), db.ForeignKey(USER_ID)),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)
@ -80,7 +81,7 @@ class User(db.Model, UserMixin):
class Setting(db.Model):
"""Define a setting object"""
__tablename__ = 'setting'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey(USER_ID), primary_key=True)
setting = db.Column(db.String(256), primary_key=True)
value = db.Column(db.String(1024))
@ -89,7 +90,7 @@ class ServerGroup(db.Model):
"""Define a server group for the treeview"""
__tablename__ = 'servergroup'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey(USER_ID), nullable=False)
name = db.Column(db.String(128), nullable=False)
__table_args__ = (db.UniqueConstraint('user_id', 'name'),)
@ -101,7 +102,7 @@ class Server(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer,
db.ForeignKey('user.id'),
db.ForeignKey(USER_ID),
nullable=False
)
servergroup_id = db.Column(
@ -214,7 +215,7 @@ class UserPreference(db.Model):
db.Integer, db.ForeignKey('preferences.id'), primary_key=True
)
uid = db.Column(
db.Integer, db.ForeignKey('user.id'), primary_key=True
db.Integer, db.ForeignKey(USER_ID), primary_key=True
)
value = db.Column(db.String(1024), nullable=False)
@ -256,7 +257,7 @@ class Process(db.Model):
pid = db.Column(db.String(), nullable=False, primary_key=True)
user_id = db.Column(
db.Integer,
db.ForeignKey('user.id'),
db.ForeignKey(USER_ID),
nullable=False
)
command = db.Column(db.String(), nullable=False)
@ -283,7 +284,7 @@ class QueryHistoryModel(db.Model):
__tablename__ = 'query_history'
srno = db.Column(db.Integer(), nullable=False, primary_key=True)
uid = db.Column(
db.Integer, db.ForeignKey('user.id'), nullable=False, primary_key=True
db.Integer, db.ForeignKey(USER_ID), nullable=False, primary_key=True
)
sid = db.Column(
db.Integer(), db.ForeignKey('server.id'), nullable=False,
@ -315,7 +316,7 @@ class SharedServer(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer,
db.ForeignKey('user.id')
db.ForeignKey(USER_ID)
)
server_owner = db.Column(
db.String(128),
@ -410,7 +411,7 @@ class UserMacros(db.Model):
db.Integer, db.ForeignKey('macros.id'), primary_key=True
)
uid = db.Column(
db.Integer, db.ForeignKey('user.id'), primary_key=True
db.Integer, db.ForeignKey(USER_ID), primary_key=True
)
name = db.Column(db.String(1024), nullable=False)
sql = db.Column(db.Text(), nullable=False)

View File

@ -10,6 +10,9 @@
import os
import getpass
FAILED_CREATE_DIR = \
"ERROR : Failed to create the directory {}:\n {}"
def _create_directory_if_not_exists(_path):
if _path and not os.path.exists(_path):
@ -24,8 +27,7 @@ def create_app_data_directory(config):
try:
_create_directory_if_not_exists(os.path.dirname(config.SQLITE_PATH))
except PermissionError as e:
print("ERROR : Failed to create the directory {}:\n {}".
format(os.path.dirname(config.SQLITE_PATH), e))
print(FAILED_CREATE_DIR.format(os.path.dirname(config.SQLITE_PATH), e))
print(
"HINT : Create the directory {}, ensure it is writeable by\n"
" '{}', and try again, or, create a config_local.py file\n"
@ -56,8 +58,7 @@ def create_app_data_directory(config):
try:
_create_directory_if_not_exists(os.path.dirname(config.LOG_FILE))
except PermissionError as e:
print("ERROR : Failed to create the directory {}:\n {}".
format(os.path.dirname(config.LOG_FILE), e))
print(FAILED_CREATE_DIR.format(os.path.dirname(config.LOG_FILE), e))
print(
"HINT : Create the directory {}, ensure it is writeable by\n"
" '{}', and try again, or, create a config_local.py file\n"
@ -73,8 +74,7 @@ def create_app_data_directory(config):
try:
_create_directory_if_not_exists(config.SESSION_DB_PATH)
except PermissionError as e:
print("ERROR : Failed to create the directory {}:\n {}".
format(config.SESSION_DB_PATH, e))
print(FAILED_CREATE_DIR.format(config.SESSION_DB_PATH, e))
print(
"HINT : Create the directory {}, ensure it is writeable by\n"
" '{}', and try again, or, create a config_local.py file\n"
@ -93,8 +93,7 @@ def create_app_data_directory(config):
try:
_create_directory_if_not_exists(config.STORAGE_DIR)
except PermissionError as e:
print("ERROR : Failed to create the directory {}\n {}:".
format(config.STORAGE_DIR, e))
print(FAILED_CREATE_DIR.format(config.STORAGE_DIR, e))
print(
"HINT : Create the directory {}, ensure it is writable by\n"
" '{}', and try again, or, create a config_local.py file\n"

View File

@ -98,6 +98,7 @@ class BackupMessage(IProcessDesc):
self.bfile = _bfile
self.database = _kwargs['database'] if 'database' in _kwargs else None
self.cmd = ''
self.args_str = "{0} ({1}:{2})"
def cmd_arg(x):
if x:
@ -151,22 +152,19 @@ class BackupMessage(IProcessDesc):
return _(
"Backing up an object on the server '{0}' "
"from database '{1}'"
).format(
"{0} ({1}:{2})".format(
name, host, port
),
).format(self.args_str.format(name, host, port),
html.safe_str(self.database)
)
if self.backup_type == BACKUP.GLOBALS:
return _("Backing up the global objects on "
"the server '{0}'").format(
"{0} ({1}:{2})".format(
self.args_str.format(
name, host, port
)
)
elif self.backup_type == BACKUP.SERVER:
return _("Backing up the server '{0}'").format(
"{0} ({1}:{2})".format(
self.args_str.format(
name, host, port
)
)
@ -184,7 +182,7 @@ class BackupMessage(IProcessDesc):
"Backing up an object on the server '{0}' "
"from database '{1}'..."
).format(
"{0} ({1}:{2})".format(
self.args_str.format(
name, host, port
),
self.database
@ -193,14 +191,14 @@ class BackupMessage(IProcessDesc):
elif self.backup_type == BACKUP.GLOBALS:
msg = _("Backing up the global objects on "
"the server '{0}'...").format(
"{0} ({1}:{2})".format(
self.args_str.format(
name, host, port
)
)
res += html.safe_str(msg)
elif self.backup_type == BACKUP.SERVER:
msg = _("Backing up the server '{0}'...").format(
"{0} ({1}:{2})".format(
self.args_str.format(
name, host, port
)
)

View File

@ -50,6 +50,7 @@ from pgadmin.tools.sqleditor.utils.macros import get_macros,\
get_user_macros, set_macros
MODULE_NAME = 'sqleditor'
TRANSACTION_STATUS_CHECK_FAILED = gettext("Transaction status check failed.")
class SqlEditorModule(PgAdminModule):
@ -1292,16 +1293,17 @@ def save_file():
enc = get_file_encoding_of_loaded_file(os.path.basename(file_path))
file_content = file_data['file_content'].encode(enc)
error_str = gettext("Error: {0}")
# write to file
try:
with open(file_path, 'wb+') as output_file:
output_file.write(file_content)
except IOError as e:
err_msg = gettext("Error: {0}").format(e.strerror)
err_msg = error_str.format(e.strerror)
return internal_server_error(errormsg=err_msg)
except Exception as e:
err_msg = gettext("Error: {0}").format(e.strerror)
err_msg = error_str.format(e.strerror)
return internal_server_error(errormsg=err_msg)
return make_json_response(
@ -1324,7 +1326,7 @@ def start_query_download_tool(trans_id):
if not status or sync_conn is None or trans_obj is None or \
session_obj is None:
return internal_server_error(
errormsg=gettext("Transaction status check failed.")
errormsg=TRANSACTION_STATUS_CHECK_FAILED
)
data = request.values if request.values else None
@ -1443,11 +1445,11 @@ def query_tool_status(trans_id):
)
else:
return internal_server_error(
errormsg=gettext("Transaction status check failed.")
errormsg=TRANSACTION_STATUS_CHECK_FAILED
)
else:
return internal_server_error(
errormsg=gettext("Transaction status check failed.")
errormsg=TRANSACTION_STATUS_CHECK_FAILED
)

View File

@ -361,6 +361,7 @@ class GridCommand(BaseCommand, SQLFilter, FetchedRowTracker):
self.conn_id = kwargs['conn_id'] if 'conn_id' in kwargs else None
self.cmd_type = kwargs['cmd_type'] if 'cmd_type' in kwargs else None
self.limit = -1
self._OBJECT_QUERY_SQL = 'objectquery.sql'
if self.cmd_type in (VIEW_FIRST_100_ROWS, VIEW_LAST_100_ROWS):
self.limit = 100
@ -499,14 +500,14 @@ class TableCommand(GridCommand):
if sql_filter is None:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name,
nsp_name=self.nsp_name, limit=self.limit, has_oids=has_oids,
data_sorting=data_sorting
)
else:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name,
nsp_name=self.nsp_name, limit=self.limit, has_oids=has_oids,
sql_filter=sql_filter, data_sorting=data_sorting
@ -716,13 +717,13 @@ class ViewCommand(GridCommand):
if sql_filter is None:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
limit=self.limit, data_sorting=data_sorting
)
else:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
sql_filter=sql_filter, limit=self.limit,
data_sorting=data_sorting
@ -777,13 +778,13 @@ class ForeignTableCommand(GridCommand):
if sql_filter is None:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
limit=self.limit, data_sorting=data_sorting
)
else:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
sql_filter=sql_filter, limit=self.limit,
data_sorting=data_sorting
@ -828,13 +829,13 @@ class CatalogCommand(GridCommand):
if sql_filter is None:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
limit=self.limit, data_sorting=data_sorting
)
else:
sql = render_template(
"/".join([self.sql_path, 'objectquery.sql']),
"/".join([self.sql_path, self._OBJECT_QUERY_SQL]),
object_name=self.object_name, nsp_name=self.nsp_name,
sql_filter=sql_filter, limit=self.limit,
data_sorting=data_sorting

View File

@ -140,6 +140,10 @@ class Connection(BaseConnection):
- This function will return the encrypted password for database server
- greater than or equal to 10.
"""
UNAUTHORIZED_REQUEST = gettext("Unauthorized request.")
CURSOR_NOT_FOUND = \
gettext("Cursor could not be found for the async connection.")
ARGS_STR = "{0}#{1}"
def __init__(self, manager, conn_id, db, auto_reconnect=True, async_=0,
use_binary_placeholder=False, array_to_string=False):
@ -245,7 +249,7 @@ class Connection(BaseConnection):
user = User.query.filter_by(id=current_user.id).first()
if user is None:
return False, gettext("Unauthorized request.")
return False, self.UNAUTHORIZED_REQUEST
try:
password = decrypt(encpass, crypt_key)
@ -401,7 +405,7 @@ class Connection(BaseConnection):
self.execution_aborted = False
self.__backend_pid = self.conn.get_backend_pid()
setattr(g, "{0}#{1}".format(
setattr(g, self.ARGS_STR.format(
self.manager.sid,
self.conn_id.encode('utf-8')
), None)
@ -563,7 +567,7 @@ WHERE db.datname = current_database()""")
self.db,
None if self.conn_id[0:3] == 'DB:' else self.conn_id[5:]
)
cur = getattr(g, "{0}#{1}".format(
cur = getattr(g, self.ARGS_STR.format(
self.manager.sid,
self.conn_id.encode('utf-8')
), None)
@ -635,7 +639,7 @@ WHERE db.datname = current_database()""")
)
setattr(
g, "{0}#{1}".format(
g, self.ARGS_STR.format(
self.manager.sid, self.conn_id.encode('utf-8')
), cur
)
@ -1031,7 +1035,7 @@ WHERE db.datname = current_database()""")
def __attempt_execution_reconnect(self, fn, *args, **kwargs):
self.reconnecting = True
setattr(g, "{0}#{1}".format(
setattr(g, self.ARGS_STR.format(
self.manager.sid,
self.conn_id.encode('utf-8')
), None)
@ -1187,9 +1191,7 @@ WHERE db.datname = current_database()""")
"""
cur = self.__async_cursor
if not cur:
return False, gettext(
"Cursor could not be found for the async connection."
)
return False, self.CURSOR_NOT_FOUND
if self.conn.isexecuting():
return False, gettext(
@ -1242,7 +1244,7 @@ WHERE db.datname = current_database()""")
user = User.query.filter_by(id=current_user.id).first()
if user is None:
return False, gettext("Unauthorized request."), password
return False, self.UNAUTHORIZED_REQUEST, password
crypt_key_present, crypt_key = get_crypt_key()
if not crypt_key_present:
@ -1404,9 +1406,7 @@ Failed to reset the connection to the server due to following error:
cur = self.__async_cursor
if not cur:
return False, gettext(
"Cursor could not be found for the async connection."
)
return False, self.CURSOR_NOT_FOUND
current_app.logger.log(
25,
@ -1505,9 +1505,7 @@ Failed to reset the connection to the server due to following error:
"""
cur = self.__async_cursor
if not cur:
return gettext(
"Cursor could not be found for the async connection."
)
return self.CURSOR_NOT_FOUND
current_app.logger.log(
25,
@ -1559,7 +1557,7 @@ Failed to reset the connection to the server due to following error:
# Fetch Logged in User Details.
user = User.query.filter_by(id=current_user.id).first()
if user is None:
return False, gettext("Unauthorized request.")
return False, self.UNAUTHORIZED_REQUEST
crypt_key_present, crypt_key = get_crypt_key()
if not crypt_key_present:

View File

@ -14,6 +14,8 @@ from flask import request
from pgadmin.utils.ajax import service_unavailable, gone, internal_server_error
SERVICE_UNAVAILABLE = 'Service Unavailable'
class ConnectionLost(HTTPException):
"""
@ -28,7 +30,7 @@ class ConnectionLost(HTTPException):
@property
def name(self):
return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
return service_unavailable(
@ -61,7 +63,7 @@ class SSHTunnelConnectionLost(HTTPException):
@property
def name(self):
return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
return service_unavailable(
@ -86,25 +88,26 @@ class CryptKeyMissing(HTTPException):
"""
Exception
"""
CRYPT_KEY_MISSING = "Crypt key is missing."
def __init__(self):
HTTPException.__init__(self)
@property
def name(self):
return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
return service_unavailable(
_("Crypt key is missing."),
_(self.CRYPT_KEY_MISSING),
info="CRYPTKEY_MISSING",
)
def __str__(self):
return "Crypt key is missing."
return self.CRYPT_KEY_MISSING
def __repr__(self):
return "Crypt key is missing."
return self.CRYPT_KEY_MISSING
class ObjectGone(HTTPException):