mirror of
https://github.com/pgadmin-org/pgadmin4.git
synced 2025-02-25 18:55:31 -06:00
Code tidy.
This commit is contained in:
@@ -129,5 +129,5 @@ class PgAdminModule(Blueprint):
|
||||
for key, value in module.menu_items.items():
|
||||
menu_items[key].extend(value)
|
||||
menu_items = dict((key, sorted(value, key=attrgetter('priority')))
|
||||
for key, value in menu_items.items())
|
||||
for key, value in menu_items.items())
|
||||
return menu_items
|
||||
|
||||
@@ -42,88 +42,88 @@ def make_json_response(success=1, errormsg='', info='', result=None,
|
||||
doc['data'] = data
|
||||
|
||||
return Response(
|
||||
response=json.dumps(doc, cls=DataTypeJSONEncoder),
|
||||
status=status,
|
||||
mimetype="text/json"
|
||||
)
|
||||
response=json.dumps(doc, cls=DataTypeJSONEncoder),
|
||||
status=status,
|
||||
mimetype="text/json"
|
||||
)
|
||||
|
||||
|
||||
def make_response(response=None, status=200):
|
||||
"""Create a JSON response handled by the backbone models."""
|
||||
return Response(
|
||||
response=json.dumps(response, cls=DataTypeJSONEncoder),
|
||||
status=status,
|
||||
mimetype="text/json"
|
||||
)
|
||||
response=json.dumps(response, cls=DataTypeJSONEncoder),
|
||||
status=status,
|
||||
mimetype="text/json"
|
||||
)
|
||||
|
||||
|
||||
def internal_server_error(errormsg=''):
|
||||
"""Create a response with HTTP status code 500 - Internal Server Error."""
|
||||
return make_json_response(
|
||||
status=500,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=500,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
|
||||
def forbidden(errmsg=''):
|
||||
"""Create a response with HTTP status code 403 - Forbidden."""
|
||||
return make_json_response(
|
||||
status=403,
|
||||
success=0,
|
||||
errormsg=errmsg
|
||||
)
|
||||
status=403,
|
||||
success=0,
|
||||
errormsg=errmsg
|
||||
)
|
||||
|
||||
|
||||
def unauthorized(errormsg=''):
|
||||
"""Create a response with HTTP status code 401 - Unauthorized."""
|
||||
return make_json_response(
|
||||
status=401,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=401,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
|
||||
def bad_request(errormsg=''):
|
||||
"""Create a response with HTTP status code 400 - Bad Request."""
|
||||
return make_json_response(
|
||||
status=400,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=400,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
|
||||
def precondition_required(errormsg=''):
|
||||
"""Create a response with HTTP status code 428 - Precondition Required."""
|
||||
return make_json_response(
|
||||
status=428,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=428,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
|
||||
def success_return(message=''):
|
||||
"""Create a response with HTTP status code 200 - OK."""
|
||||
return make_json_response(
|
||||
status=200,
|
||||
success=1,
|
||||
info=message
|
||||
)
|
||||
status=200,
|
||||
success=1,
|
||||
info=message
|
||||
)
|
||||
|
||||
|
||||
def gone(errormsg=''):
|
||||
"""Create a response with HTTP status code 410 - GONE."""
|
||||
return make_json_response(
|
||||
status=410,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=410,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
|
||||
def not_implemented(errormsg=_('Not implemented.')):
|
||||
"""Create a response with HTTP status code 501 - Not Implemented."""
|
||||
return make_json_response(
|
||||
status=501,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
status=501,
|
||||
success=0,
|
||||
errormsg=errormsg
|
||||
)
|
||||
|
||||
@@ -72,7 +72,6 @@ def pad(str):
|
||||
|
||||
|
||||
def pqencryptpassword(password, user):
|
||||
|
||||
"""
|
||||
pqencryptpassword -- to encrypt a password
|
||||
This is intended to be used by client applications that wish to send
|
||||
|
||||
@@ -13,7 +13,6 @@ from .registry import DriverRegistry
|
||||
|
||||
|
||||
def get_driver(type, app=None):
|
||||
|
||||
if app is not None:
|
||||
DriverRegistry.load_drivers()
|
||||
|
||||
@@ -33,6 +32,7 @@ def get_driver(type, app=None):
|
||||
|
||||
return driver
|
||||
|
||||
|
||||
def init_app(app):
|
||||
drivers = dict()
|
||||
|
||||
|
||||
@@ -58,8 +58,10 @@ def register_date_typecasters(connection):
|
||||
Casts date and timestamp values to string, resolves issues
|
||||
with out of range dates (e.g. BC) which psycopg2 can't handle
|
||||
"""
|
||||
|
||||
def cast_date(value, cursor):
|
||||
return value
|
||||
|
||||
cursor = connection.cursor()
|
||||
cursor.execute('SELECT NULL::date')
|
||||
date_oid = cursor.description[0][1]
|
||||
@@ -149,9 +151,10 @@ class Connection(BaseConnection):
|
||||
normal error message.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, manager, conn_id, db, auto_reconnect=True, async=0):
|
||||
assert(manager is not None)
|
||||
assert(conn_id is not None)
|
||||
assert (manager is not None)
|
||||
assert (conn_id is not None)
|
||||
|
||||
self.conn_id = conn_id
|
||||
self.manager = manager
|
||||
@@ -189,7 +192,7 @@ class Connection(BaseConnection):
|
||||
'Connected' if self.conn and not self.conn.closed else
|
||||
"Disconnected",
|
||||
self.async
|
||||
)
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return "PG Connection: {0} ({1}) -> {2} (ajax:{3})".format(
|
||||
@@ -197,7 +200,7 @@ class Connection(BaseConnection):
|
||||
'Connected' if self.conn and not self.conn.closed else
|
||||
"Disconnected",
|
||||
self.async
|
||||
)
|
||||
)
|
||||
|
||||
def connect(self, **kwargs):
|
||||
if self.conn:
|
||||
@@ -227,9 +230,9 @@ class Connection(BaseConnection):
|
||||
except Exception as e:
|
||||
current_app.logger.exception(e)
|
||||
return False, \
|
||||
_("Failed to decrypt the saved password!\nError: {0}").format(
|
||||
str(e)
|
||||
)
|
||||
_("Failed to decrypt the saved password!\nError: {0}").format(
|
||||
str(e)
|
||||
)
|
||||
|
||||
# password is in bytes, for python3 we need it in string
|
||||
if isinstance(password, bytes):
|
||||
@@ -239,13 +242,13 @@ class Connection(BaseConnection):
|
||||
import os
|
||||
os.environ['PGAPPNAME'] = '{0} - {1}'.format(config.APP_NAME, self.conn_id)
|
||||
pg_conn = psycopg2.connect(
|
||||
host=mgr.host,
|
||||
port=mgr.port,
|
||||
database=self.db,
|
||||
user=mgr.user,
|
||||
password=password,
|
||||
async=self.async
|
||||
)
|
||||
host=mgr.host,
|
||||
port=mgr.port,
|
||||
database=self.db,
|
||||
user=mgr.user,
|
||||
password=password,
|
||||
async=self.async
|
||||
)
|
||||
|
||||
# If connection is asynchronous then we will have to wait
|
||||
# until the connection is ready to use.
|
||||
@@ -262,11 +265,11 @@ class Connection(BaseConnection):
|
||||
current_app.logger.info("""
|
||||
Failed to connect to the database server(#{server_id}) for connection ({conn_id}) with error message as below:
|
||||
{msg}""".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=msg
|
||||
)
|
||||
)
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=msg
|
||||
)
|
||||
)
|
||||
|
||||
return False, msg
|
||||
|
||||
@@ -302,15 +305,15 @@ SET client_encoding='UNICODE';""")
|
||||
Connect to the database server (#{server_id}) for connection ({conn_id}), but - failed to setup the role with error message as below:
|
||||
{msg}
|
||||
""".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=res
|
||||
)
|
||||
)
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=res
|
||||
)
|
||||
)
|
||||
return False, \
|
||||
_("Failed to setup the role with error message:\n{0}").format(
|
||||
res
|
||||
)
|
||||
_("Failed to setup the role with error message:\n{0}").format(
|
||||
res
|
||||
)
|
||||
|
||||
if mgr.ver is None:
|
||||
status, res = self.execute_scalar("SELECT version()")
|
||||
@@ -325,11 +328,11 @@ Connect to the database server (#{server_id}) for connection ({conn_id}), but -
|
||||
Failed to fetch the version information on the established connection to the database server (#{server_id}) for '{conn_id}' with below error message:
|
||||
{msg}
|
||||
""".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=res
|
||||
)
|
||||
)
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
msg=res
|
||||
)
|
||||
)
|
||||
return False, res
|
||||
|
||||
status, res = self.execute_dict("""
|
||||
@@ -390,20 +393,20 @@ WHERE
|
||||
current_app.logger.warning("""
|
||||
Connection to database server (#{server_id}) for the connection - '{conn_id}' has been lost.
|
||||
""".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id
|
||||
)
|
||||
)
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id
|
||||
)
|
||||
)
|
||||
|
||||
if self.auto_reconnect:
|
||||
status, errmsg = self.connect()
|
||||
|
||||
if not status:
|
||||
errmsg = gettext(
|
||||
"""
|
||||
"""
|
||||
Attempt to reconnect failed with the error:
|
||||
{0}""".format(errmsg)
|
||||
)
|
||||
)
|
||||
|
||||
if not status:
|
||||
msg = gettext("Connection lost.\n{0}").format(errmsg)
|
||||
@@ -428,7 +431,7 @@ Attempting to reconnect to the database server (#{server_id}) for the connection
|
||||
""".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id
|
||||
)
|
||||
)
|
||||
)
|
||||
status, cur = self.connect()
|
||||
if not status:
|
||||
@@ -437,7 +440,7 @@ Attempting to reconnect to the database server (#{server_id}) for the connection
|
||||
Connection for server#{0} with database "{1}" was lost.
|
||||
Attempt to reconnect it failed with the error:
|
||||
{2}"""
|
||||
).format(self.driver.server_id, self.database, cur)
|
||||
).format(self.driver.server_id, self.database, cur)
|
||||
current_app.logger.error(msg)
|
||||
|
||||
return False, cur
|
||||
@@ -473,27 +476,27 @@ Attempt to reconnect it failed with the error:
|
||||
query_id = random.randint(1, 9999999)
|
||||
|
||||
current_app.logger.log(25,
|
||||
"Execute (scalar) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
"Execute (scalar) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
try:
|
||||
self.__internal_blocking_execute(cur, query, params)
|
||||
except psycopg2.Error as pe:
|
||||
cur.close()
|
||||
errmsg = self._formatted_exception_msg(pe, formatted_exception_msg)
|
||||
current_app.logger.error(
|
||||
"Failed to execute query (execute_scalar) for the server #{server_id} - {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
"Failed to execute query (execute_scalar) for the server #{server_id} - {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
return False, errmsg
|
||||
|
||||
self.row_count = cur.rowcount
|
||||
@@ -527,8 +530,8 @@ Execute (async) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{qu
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
self.execution_aborted = False
|
||||
@@ -545,7 +548,7 @@ Failed to execute query (execute_async) for the server #{server_id} - {conn_id}
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
return False, errmsg
|
||||
|
||||
@@ -577,8 +580,8 @@ Execute (void) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{que
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
self.__internal_blocking_execute(cur, query, params)
|
||||
@@ -594,7 +597,7 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
return False, errmsg
|
||||
|
||||
@@ -611,34 +614,34 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
|
||||
|
||||
query_id = random.randint(1, 9999999)
|
||||
current_app.logger.log(25,
|
||||
"Execute (2darray) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
"Execute (2darray) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
try:
|
||||
self.__internal_blocking_execute(cur, query, params)
|
||||
except psycopg2.Error as pe:
|
||||
cur.close()
|
||||
errmsg = self._formatted_exception_msg(pe, formatted_exception_msg)
|
||||
current_app.logger.error(
|
||||
"Failed to execute query (execute_2darray) for the server #{server_id} - {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
"Failed to execute query (execute_2darray) for the server #{server_id} - {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
errmsg=errmsg,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
return False, errmsg
|
||||
|
||||
import copy
|
||||
# Get Resultset Column Name, Type and size
|
||||
columns = cur.description and [
|
||||
copy.deepcopy(desc._asdict()) for desc in cur.description
|
||||
] or []
|
||||
copy.deepcopy(desc._asdict()) for desc in cur.description
|
||||
] or []
|
||||
|
||||
rows = []
|
||||
self.row_count = cur.rowcount
|
||||
@@ -656,33 +659,33 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
|
||||
return False, str(cur)
|
||||
query_id = random.randint(1, 9999999)
|
||||
current_app.logger.log(25,
|
||||
"Execute (dict) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
"Execute (dict) for server #{server_id} - {conn_id} (Query-id: {query_id}):\n{query}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query=query,
|
||||
query_id=query_id
|
||||
)
|
||||
)
|
||||
try:
|
||||
self.__internal_blocking_execute(cur, query, params)
|
||||
except psycopg2.Error as pe:
|
||||
cur.close()
|
||||
errmsg = self._formatted_exception_msg(pe, formatted_exception_msg)
|
||||
current_app.logger.error(
|
||||
"Failed to execute query (execute_dict) for the server #{server_id}- {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query_id=query_id,
|
||||
errmsg=errmsg
|
||||
)
|
||||
)
|
||||
"Failed to execute query (execute_dict) for the server #{server_id}- {conn_id} (Query-id: {query_id}):\nError Message:{errmsg}".format(
|
||||
server_id=self.manager.sid,
|
||||
conn_id=self.conn_id,
|
||||
query_id=query_id,
|
||||
errmsg=errmsg
|
||||
)
|
||||
)
|
||||
return False, errmsg
|
||||
|
||||
import copy
|
||||
# Get Resultset Column Name, Type and size
|
||||
columns = cur.description and [
|
||||
copy.deepcopy(desc._asdict()) for desc in cur.description
|
||||
] or []
|
||||
copy.deepcopy(desc._asdict()) for desc in cur.description
|
||||
] or []
|
||||
|
||||
rows = []
|
||||
self.row_count = cur.rowcount
|
||||
@@ -719,12 +722,12 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
|
||||
|
||||
try:
|
||||
pg_conn = psycopg2.connect(
|
||||
host=mgr.host,
|
||||
port=mgr.port,
|
||||
database=self.db,
|
||||
user=mgr.user,
|
||||
password=password
|
||||
)
|
||||
host=mgr.host,
|
||||
port=mgr.port,
|
||||
database=self.db,
|
||||
user=mgr.user,
|
||||
password=password
|
||||
)
|
||||
|
||||
except psycopg2.Error as e:
|
||||
msg = e.pgerror if e.pgerror else e.message \
|
||||
@@ -736,8 +739,8 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
|
||||
"""
|
||||
Failed to reset the connection to the server due to following error:
|
||||
{0}"""
|
||||
).Format(msg)
|
||||
)
|
||||
).Format(msg)
|
||||
)
|
||||
return False, msg
|
||||
|
||||
self.conn = pg_conn
|
||||
@@ -824,7 +827,7 @@ Failed to reset the connection to the server due to following error:
|
||||
else:
|
||||
raise psycopg2.OperationalError(
|
||||
"poll() returned %s from _wait_timeout function" % state
|
||||
)
|
||||
)
|
||||
|
||||
def poll(self, formatted_exception_msg=False):
|
||||
"""
|
||||
@@ -842,14 +845,14 @@ Failed to reset the connection to the server due to following error:
|
||||
if not cur:
|
||||
return False, gettext(
|
||||
"Cursor could not be found for the async connection."
|
||||
), None
|
||||
), None
|
||||
|
||||
current_app.logger.log(
|
||||
25,
|
||||
"Polling result for (Query-id: {query_id})".format(
|
||||
query_id=self.__async_query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
status = self._wait_timeout(self.conn, ASYNC_WAIT_TIMEOUT)
|
||||
@@ -901,8 +904,8 @@ Failed to reset the connection to the server due to following error:
|
||||
25,
|
||||
"Status message for (Query-id: {query_id})".format(
|
||||
query_id=self.__async_query_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
return cur.statusmessage
|
||||
|
||||
@@ -1014,7 +1017,7 @@ Failed to reset the connection to the server due to following error:
|
||||
if exception_obj.diag.severity is not None \
|
||||
and exception_obj.diag.message_primary is not None:
|
||||
errmsg += exception_obj.diag.severity + ": " + \
|
||||
exception_obj.diag.message_primary
|
||||
exception_obj.diag.message_primary
|
||||
elif exception_obj.diag.message_primary is not None:
|
||||
errmsg += exception_obj.diag.message_primary
|
||||
|
||||
@@ -1058,14 +1061,15 @@ class ServerManager(object):
|
||||
This class contains the information about the given server.
|
||||
And, acts as connection manager for that particular session.
|
||||
"""
|
||||
|
||||
def __init__(self, server):
|
||||
self.connections = dict()
|
||||
|
||||
self.update(server)
|
||||
|
||||
def update(self, server):
|
||||
assert(server is not None)
|
||||
assert(isinstance(server, Server))
|
||||
assert (server is not None)
|
||||
assert (isinstance(server, Server))
|
||||
|
||||
self.ver = None
|
||||
self.sversion = None
|
||||
@@ -1140,10 +1144,10 @@ class ServerManager(object):
|
||||
|
||||
def connection(
|
||||
self, database=None, conn_id=None, auto_reconnect=True, did=None
|
||||
):
|
||||
):
|
||||
msg_active_conn = gettext(
|
||||
"Server has no active connection. Please connect to the server."
|
||||
)
|
||||
)
|
||||
|
||||
if database is None:
|
||||
if did is None:
|
||||
@@ -1172,13 +1176,13 @@ WHERE db.oid = {0}""".format(did))
|
||||
if did not in self.db_info:
|
||||
raise Exception(gettext(
|
||||
"Couldn't find the specified database."
|
||||
))
|
||||
))
|
||||
|
||||
if database is None:
|
||||
raise Exception(msg_active_conn)
|
||||
|
||||
my_id = ('CONN:' + str(conn_id)) if conn_id is not None else \
|
||||
('DB:' + str(database))
|
||||
('DB:' + str(database))
|
||||
|
||||
self.pinged = datetime.datetime.now()
|
||||
|
||||
@@ -1187,8 +1191,8 @@ WHERE db.oid = {0}""".format(did))
|
||||
else:
|
||||
async = 1 if conn_id is not None else 0
|
||||
self.connections[my_id] = Connection(
|
||||
self, my_id, database, auto_reconnect, async
|
||||
)
|
||||
self, my_id, database, auto_reconnect, async
|
||||
)
|
||||
|
||||
return self.connections[my_id]
|
||||
|
||||
@@ -1217,13 +1221,13 @@ WHERE db.oid = {0}""".format(did))
|
||||
conn = self.connections[conn_info['conn_id']] = Connection(
|
||||
self, conn_info['conn_id'], conn_info['database'],
|
||||
True, conn_info['async']
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
conn.connect(
|
||||
password=data['password'],
|
||||
server_types=ServerType.types()
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
current_app.logger.exception(e)
|
||||
self.connections.pop(conn_info['conn_id'])
|
||||
@@ -1238,7 +1242,7 @@ WHERE db.oid = {0}""".format(did))
|
||||
return False
|
||||
|
||||
my_id = ('CONN:' + str(conn_id)) if conn_id is not None else \
|
||||
('DB:' + str(database)) if database is not None else None
|
||||
('DB:' + str(database)) if database is not None else None
|
||||
|
||||
if my_id is not None:
|
||||
if my_id in self.connections:
|
||||
@@ -1330,6 +1334,7 @@ class Driver(BaseDriver):
|
||||
* connection_manager(sid, reset)
|
||||
- It returns the server connection manager for this session.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.managers = dict()
|
||||
|
||||
@@ -1392,12 +1397,12 @@ class Driver(BaseDriver):
|
||||
return version
|
||||
|
||||
raise Exception(
|
||||
"Driver Version information for psycopg2 is not available!"
|
||||
)
|
||||
"Driver Version information for psycopg2 is not available!"
|
||||
)
|
||||
|
||||
def get_connection(
|
||||
self, sid, database=None, conn_id=None, auto_reconnect=True
|
||||
):
|
||||
):
|
||||
"""
|
||||
get_connection(...)
|
||||
|
||||
@@ -1455,7 +1460,7 @@ class Driver(BaseDriver):
|
||||
|
||||
if (curr_time - sess_mgr['pinged'] >= session_idle_timeout):
|
||||
for mgr in [m for m in sess_mgr if isinstance(m,
|
||||
ServerManager)]:
|
||||
ServerManager)]:
|
||||
mgr.release()
|
||||
|
||||
@staticmethod
|
||||
@@ -1497,7 +1502,7 @@ class Driver(BaseDriver):
|
||||
'tinyint': 3,
|
||||
'tinytext': 3,
|
||||
'varchar2': 3
|
||||
};
|
||||
};
|
||||
|
||||
return (key in extraKeywords and extraKeywords[key]) or ScanKeyword(key)
|
||||
|
||||
@@ -1529,7 +1534,7 @@ class Driver(BaseDriver):
|
||||
u'time with time zone',
|
||||
u'"trigger"',
|
||||
u'"unknown"'
|
||||
]:
|
||||
]:
|
||||
return False
|
||||
|
||||
if u'0' <= valNoArray[0] <= u'9':
|
||||
|
||||
@@ -17,12 +17,12 @@ import os
|
||||
import re
|
||||
|
||||
if __name__ == '__main__':
|
||||
include_dir = os.popen('pg_config --includedir').read().rstrip()
|
||||
version = os.popen('pg_config --version').read().rstrip()
|
||||
include_dir = os.popen('pg_config --includedir').read().rstrip()
|
||||
version = os.popen('pg_config --version').read().rstrip()
|
||||
|
||||
keywords_file = open('keywords.py', 'w')
|
||||
keywords_file = open('keywords.py', 'w')
|
||||
|
||||
keywords_file.write("""##########################################################################
|
||||
keywords_file.write("""##########################################################################
|
||||
#
|
||||
# pgAdmin 4 - PostgreSQL Tools
|
||||
#
|
||||
@@ -31,32 +31,32 @@ if __name__ == '__main__':
|
||||
#
|
||||
##########################################################################
|
||||
""")
|
||||
keywords_file.write('# ScanKeyword function for ' + version)
|
||||
keywords_file.write('\n\ndef ScanKeyword(key):')
|
||||
keywords_file.write('\n keywordDict = {\n')
|
||||
keywords_file.write('# ScanKeyword function for ' + version)
|
||||
keywords_file.write('\n\ndef ScanKeyword(key):')
|
||||
keywords_file.write('\n keywordDict = {\n')
|
||||
|
||||
idx = 0
|
||||
idx = 0
|
||||
|
||||
with open(include_dir + "/postgresql/server/parser/kwlist.h", "rb") as ins:
|
||||
with open(include_dir + "/postgresql/server/parser/kwlist.h", "rb") as ins:
|
||||
|
||||
pattern = re.compile(r'"([^"]+)",\s*[^,]*\s*,\s*(.*)$')
|
||||
keyword_types = [
|
||||
u'UNRESERVED_KEYWORD', u'COL_NAME_KEYWORD',
|
||||
u'TYPE_FUNC_NAME_KEYWORD', u'RESERVED_KEYWORD'
|
||||
]
|
||||
pattern = re.compile(r'"([^"]+)",\s*[^,]*\s*,\s*(.*)$')
|
||||
keyword_types = [
|
||||
u'UNRESERVED_KEYWORD', u'COL_NAME_KEYWORD',
|
||||
u'TYPE_FUNC_NAME_KEYWORD', u'RESERVED_KEYWORD'
|
||||
]
|
||||
|
||||
for line in ins:
|
||||
line = line.decode().rstrip()
|
||||
if line[0:11] == 'PG_KEYWORD(' and line[-1] == ')':
|
||||
match = pattern.match(line[11:-1])
|
||||
if idx != 0:
|
||||
keywords_file.write(", ")
|
||||
else:
|
||||
keywords_file.write(" ")
|
||||
keywords_file.write(
|
||||
'"' + match.group(1) + u'": ' +
|
||||
str(keyword_types.index(match.group(2)))
|
||||
)
|
||||
idx += 1
|
||||
keywords_file.write('\n }\n')
|
||||
keywords_file.write(' return (key in keywordDict and keywordDict[key]) or None')
|
||||
for line in ins:
|
||||
line = line.decode().rstrip()
|
||||
if line[0:11] == 'PG_KEYWORD(' and line[-1] == ')':
|
||||
match = pattern.match(line[11:-1])
|
||||
if idx != 0:
|
||||
keywords_file.write(", ")
|
||||
else:
|
||||
keywords_file.write(" ")
|
||||
keywords_file.write(
|
||||
'"' + match.group(1) + u'": ' +
|
||||
str(keyword_types.index(match.group(2)))
|
||||
)
|
||||
idx += 1
|
||||
keywords_file.write('\n }\n')
|
||||
keywords_file.write(' return (key in keywordDict and keywordDict[key]) or None')
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -72,8 +72,8 @@ class DriverRegistry(ABCMeta):
|
||||
return DriverRegistry.drivers[name]
|
||||
|
||||
raise NotImplementedError(
|
||||
gettext("Driver '{0}' has not been implemented.").format(name)
|
||||
)
|
||||
gettext("Driver '{0}' has not been implemented.").format(name)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def load_drivers(cls):
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
|
||||
PRIORITY = 100
|
||||
|
||||
class MenuItem(object):
|
||||
|
||||
class MenuItem(object):
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(**kwargs)
|
||||
|
||||
class Panel(object):
|
||||
|
||||
class Panel(object):
|
||||
def __init__(self, name, title, content='', width=500, height=600, isIframe=True,
|
||||
showTitle=True, isCloseable=True, isPrivate=False, priority=None,
|
||||
icon=None, data=None, events=None):
|
||||
|
||||
@@ -18,7 +18,6 @@ import config
|
||||
|
||||
@login_required
|
||||
def get_storage_directory():
|
||||
|
||||
if config.SERVER_MODE is not True:
|
||||
return None
|
||||
|
||||
@@ -47,7 +46,6 @@ def get_storage_directory():
|
||||
|
||||
|
||||
def init_app(app):
|
||||
|
||||
if config.SERVER_MODE is not True:
|
||||
return None
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ class _Preference(object):
|
||||
def __init__(
|
||||
self, cid, name, label, _type, default, help_str=None, min_val=None,
|
||||
max_val=None, options=None
|
||||
):
|
||||
):
|
||||
"""
|
||||
__init__
|
||||
Constructor/Initializer for the internal _Preference object.
|
||||
@@ -70,7 +70,7 @@ class _Preference(object):
|
||||
# preference.
|
||||
res = PrefTable.query.filter_by(
|
||||
name=name
|
||||
).first()
|
||||
).first()
|
||||
|
||||
if res is None:
|
||||
# Couldn't find in the configuration table, we will create new
|
||||
@@ -80,7 +80,7 @@ class _Preference(object):
|
||||
db.session.commit()
|
||||
res = PrefTable.query.filter_by(
|
||||
name=name
|
||||
).first()
|
||||
).first()
|
||||
|
||||
# Save this id for letter use.
|
||||
self.pid = res.id
|
||||
@@ -96,7 +96,7 @@ class _Preference(object):
|
||||
"""
|
||||
res = UserPrefTable.query.filter_by(
|
||||
pid=self.pid
|
||||
).filter_by(uid=current_user.id).first()
|
||||
).filter_by(uid=current_user.id).first()
|
||||
|
||||
# Couldn't find any preference for this user, return default value.
|
||||
if res is None:
|
||||
@@ -105,7 +105,7 @@ class _Preference(object):
|
||||
# The data stored in the configuration will be in string format, we
|
||||
# need to convert them in proper format.
|
||||
if self._type == 'boolean' or self._type == 'switch' or \
|
||||
self._type == 'node':
|
||||
self._type == 'node':
|
||||
return res.value == 'True'
|
||||
if self._type == 'integer':
|
||||
try:
|
||||
@@ -144,7 +144,7 @@ class _Preference(object):
|
||||
# We can't store the values in the given format, we need to convert
|
||||
# them in string first. We also need to validate the value type.
|
||||
if self._type == 'boolean' or self._type == 'switch' or \
|
||||
self._type == 'node':
|
||||
self._type == 'node':
|
||||
if type(value) != bool:
|
||||
return False, gettext("Invalid value for a boolean option.")
|
||||
elif self._type == 'integer':
|
||||
@@ -174,12 +174,12 @@ class _Preference(object):
|
||||
|
||||
pref = UserPrefTable.query.filter_by(
|
||||
pid=self.pid
|
||||
).filter_by(uid=current_user.id).first()
|
||||
).filter_by(uid=current_user.id).first()
|
||||
|
||||
if pref is None:
|
||||
pref = UserPrefTable(
|
||||
uid=current_user.id, pid=self.pid, value=str(value)
|
||||
)
|
||||
)
|
||||
db.session.add(pref)
|
||||
else:
|
||||
pref.value = str(value)
|
||||
@@ -205,7 +205,7 @@ class _Preference(object):
|
||||
'max_val': self.max_val,
|
||||
'options': self.options,
|
||||
'value': self.get()
|
||||
}
|
||||
}
|
||||
return res
|
||||
|
||||
|
||||
@@ -289,7 +289,7 @@ class Preferences(object):
|
||||
'id': cat['id'],
|
||||
'label': cat['label'] or cat['name'],
|
||||
'preferences': []
|
||||
}
|
||||
}
|
||||
|
||||
res['categories'].append(interm)
|
||||
|
||||
@@ -321,7 +321,7 @@ class Preferences(object):
|
||||
|
||||
cat = PrefCategoryTbl.query.filter_by(
|
||||
mid=self.mid
|
||||
).filter_by(name=name).first()
|
||||
).filter_by(name=name).first()
|
||||
|
||||
if cat is None:
|
||||
cat = PrefCategoryTbl(name=name, mid=self.mid)
|
||||
@@ -329,20 +329,20 @@ class Preferences(object):
|
||||
db.session.commit()
|
||||
cat = PrefCategoryTbl.query.filter_by(
|
||||
mid=self.mid
|
||||
).filter_by(name=name).first()
|
||||
).filter_by(name=name).first()
|
||||
|
||||
self.categories[name] = res = {
|
||||
'id': cat.id,
|
||||
'name': name,
|
||||
'label': label,
|
||||
'preferences': dict()
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
|
||||
def register(
|
||||
self, category, name, label, _type, default, min_val=None,
|
||||
max_val=None, options=None, help_str=None, category_label=None
|
||||
self, category, name, label, _type, default, min_val=None,
|
||||
max_val=None, options=None, help_str=None, category_label=None
|
||||
):
|
||||
"""
|
||||
register
|
||||
@@ -373,12 +373,12 @@ class Preferences(object):
|
||||
assert _type in (
|
||||
'boolean', 'integer', 'numeric', 'date', 'datetime',
|
||||
'options', 'multiline', 'switch', 'node', 'text'
|
||||
), "Type can not be found in the defined list!"
|
||||
), "Type can not be found in the defined list!"
|
||||
|
||||
(cat['preferences'])[name] = res = _Preference(
|
||||
cat['id'], name, label, _type, default, help_str, min_val,
|
||||
max_val, options
|
||||
)
|
||||
)
|
||||
|
||||
return res
|
||||
|
||||
@@ -417,7 +417,7 @@ Did you forget to register it?"""
|
||||
cls, module, category, name, label, _type, default, min_val=None,
|
||||
max_val=None, options=None, help_str=None, module_label=None,
|
||||
category_label=None
|
||||
):
|
||||
):
|
||||
"""
|
||||
register
|
||||
Register/Refer a preference in the system for any module.
|
||||
@@ -449,7 +449,7 @@ Did you forget to register it?"""
|
||||
return m.register(
|
||||
category, name, label, _type, default, min_val, max_val,
|
||||
options, help_str, category_label
|
||||
)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def module(cls, name):
|
||||
@@ -507,7 +507,7 @@ Did you forget to register it?"""
|
||||
|
||||
if category is None:
|
||||
return False, gettext(
|
||||
"Module '{0}' does not have category with id '{1}'"
|
||||
"Module '{0}' does not have category with id '{1}'"
|
||||
).format(module.name, cid)
|
||||
|
||||
preference = None
|
||||
@@ -521,7 +521,7 @@ Did you forget to register it?"""
|
||||
|
||||
if preference is None:
|
||||
return False, gettext(
|
||||
"Could not find the specified preference."
|
||||
"Could not find the specified preference."
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -41,7 +41,7 @@ class SqliteSessionStorage(MutableMapping, SessionMixin):
|
||||
' key TEXT PRIMARY KEY,'
|
||||
' val BLOB'
|
||||
')'
|
||||
)
|
||||
)
|
||||
_get_sql = 'SELECT val FROM pg_session WHERE key = ?'
|
||||
_set_sql = 'REPLACE INTO pg_session (key, val) VALUES (?, ?)'
|
||||
_del_sql = 'DELETE FROM pg_session WHERE key = ?'
|
||||
@@ -166,7 +166,7 @@ class SqliteSessionStorage(MutableMapping, SessionMixin):
|
||||
if callable(attr):
|
||||
return SqliteSessionStorage.CallableAttributeProxy(
|
||||
self.session, self.key, self.obj, attr
|
||||
)
|
||||
)
|
||||
return attr
|
||||
|
||||
def setdefault(self, key, value):
|
||||
@@ -179,7 +179,7 @@ class SqliteSessionStorage(MutableMapping, SessionMixin):
|
||||
|
||||
return SqliteSessionStorage.PersistedObjectProxy(
|
||||
self, key, self[key]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ServerSideSessionInterface(SessionInterface):
|
||||
@@ -227,10 +227,10 @@ class ServerSideSessionInterface(SessionInterface):
|
||||
response.delete_cookie(
|
||||
app.session_cookie_name,
|
||||
domain=domain
|
||||
)
|
||||
)
|
||||
return
|
||||
cookie_exp = self.get_expiration_time(app, session)
|
||||
response.set_cookie(
|
||||
app.session_cookie_name, session.sid,
|
||||
expires=cookie_exp, httponly=True, domain=domain
|
||||
)
|
||||
)
|
||||
|
||||
@@ -455,7 +455,7 @@ class SQLAutoComplete(object):
|
||||
status, res = self.conn.execute_dict(query)
|
||||
if status:
|
||||
for record in res['rows']:
|
||||
columns.append(record['column_name'])
|
||||
columns.append(record['column_name'])
|
||||
else:
|
||||
# Schema not specified, so traverse the search path looking for
|
||||
# a table or view that matches. Note that in order to get proper
|
||||
@@ -503,7 +503,7 @@ class SQLAutoComplete(object):
|
||||
status, res = self.conn.execute_dict(query)
|
||||
if status:
|
||||
for record in res['rows']:
|
||||
columns.append(record['column_name'])
|
||||
columns.append(record['column_name'])
|
||||
|
||||
return columns
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ class Completion(object):
|
||||
:param get_display_meta: Lazy `display_meta`. Retrieve meta information
|
||||
only when meta is displayed.
|
||||
"""
|
||||
|
||||
def __init__(self, text, start_position=0, display=None, display_meta=None,
|
||||
get_display_meta=None):
|
||||
self.text = text
|
||||
|
||||
@@ -87,7 +87,7 @@ class Counter(dict):
|
||||
for elem, count in iterable.iteritems():
|
||||
self[elem] = self_get(elem, 0) + count
|
||||
else:
|
||||
dict.update(self, iterable) # fast path when counter is empty
|
||||
dict.update(self, iterable) # fast path when counter is empty
|
||||
else:
|
||||
self_get = self.get
|
||||
for elem in iterable:
|
||||
|
||||
@@ -7,7 +7,6 @@ table_def_regex = re.compile(r'^TABLE\s*\((.+)\)$', re.IGNORECASE)
|
||||
|
||||
|
||||
class FunctionMetadata(object):
|
||||
|
||||
def __init__(self, schema_name, func_name, arg_list, return_type, is_aggregate,
|
||||
is_window, is_set_returning):
|
||||
"""Class for describing a postgresql function"""
|
||||
@@ -29,8 +28,8 @@ class FunctionMetadata(object):
|
||||
|
||||
def __hash__(self):
|
||||
return hash((self.schema_name, self.func_name, self.arg_list,
|
||||
self.return_type, self.is_aggregate, self.is_window,
|
||||
self.is_set_returning))
|
||||
self.return_type, self.is_aggregate, self.is_window,
|
||||
self.is_set_returning))
|
||||
|
||||
def __repr__(self):
|
||||
return (('%s(schema_name=%r, func_name=%r, arg_list=%r, return_type=%r,'
|
||||
|
||||
@@ -6,15 +6,15 @@ from sqlparse.sql import IdentifierList, Identifier, Function
|
||||
from sqlparse.tokens import Keyword, DML, Punctuation, Token, Error
|
||||
|
||||
cleanup_regex = {
|
||||
# This matches only alphanumerics and underscores.
|
||||
'alphanum_underscore': re.compile(r'(\w+)$'),
|
||||
# This matches everything except spaces, parens, colon, and comma
|
||||
'many_punctuations': re.compile(r'([^():,\s]+)$'),
|
||||
# This matches everything except spaces, parens, colon, comma, and period
|
||||
'most_punctuations': re.compile(r'([^\.():,\s]+)$'),
|
||||
# This matches everything except a space.
|
||||
'all_punctuations': re.compile('([^\s]+)$'),
|
||||
}
|
||||
# This matches only alphanumerics and underscores.
|
||||
'alphanum_underscore': re.compile(r'(\w+)$'),
|
||||
# This matches everything except spaces, parens, colon, and comma
|
||||
'many_punctuations': re.compile(r'([^():,\s]+)$'),
|
||||
# This matches everything except spaces, parens, colon, comma, and period
|
||||
'most_punctuations': re.compile(r'([^\.():,\s]+)$'),
|
||||
# This matches everything except a space.
|
||||
'all_punctuations': re.compile('([^\s]+)$'),
|
||||
}
|
||||
|
||||
|
||||
def last_word(text, include='alphanum_underscore'):
|
||||
@@ -51,7 +51,7 @@ def last_word(text, include='alphanum_underscore'):
|
||||
'"foo*bar'
|
||||
"""
|
||||
|
||||
if not text: # Empty string
|
||||
if not text: # Empty string
|
||||
return ''
|
||||
|
||||
if text[-1].isspace():
|
||||
@@ -118,7 +118,7 @@ def extract_from_part(parsed, stop_at_punctuation=True):
|
||||
elif isinstance(item, IdentifierList):
|
||||
for identifier in item.get_identifiers():
|
||||
if (identifier.ttype is Keyword and
|
||||
identifier.value.upper() == 'FROM'):
|
||||
identifier.value.upper() == 'FROM'):
|
||||
tbl_prefix_seen = True
|
||||
break
|
||||
|
||||
@@ -202,7 +202,7 @@ def find_prev_keyword(sql):
|
||||
|
||||
for t in reversed(flattened):
|
||||
if t.value == '(' or (t.is_keyword and (
|
||||
t.value.upper() not in logical_operators)):
|
||||
t.value.upper() not in logical_operators)):
|
||||
# Find the location of token t in the original parsed statement
|
||||
# We can't use parsed.token_index(t) because t may be a child token
|
||||
# inside a TokenList, in which case token_index thows an error
|
||||
@@ -215,7 +215,7 @@ def find_prev_keyword(sql):
|
||||
# Combine the string values of all tokens in the original list
|
||||
# up to and including the target keyword token t, to produce a
|
||||
# query string with everything after the keyword token removed
|
||||
text = ''.join(tok.value for tok in flattened[:idx+1])
|
||||
text = ''.join(tok.value for tok in flattened[:idx + 1])
|
||||
return t, text
|
||||
|
||||
return None, ''
|
||||
@@ -245,7 +245,7 @@ def _parsed_is_open_quote(parsed):
|
||||
elif (tok.ttype in Token.Name.Builtin
|
||||
and dollar_quote_regex.match(tok.value)):
|
||||
# Find the matching closing dollar quote sign
|
||||
for (j, tok2) in enumerate(tokens[i+1:], i+1):
|
||||
for (j, tok2) in enumerate(tokens[i + 1:], i + 1):
|
||||
if tok2.match(Token.Name.Builtin, tok.value):
|
||||
# Found the matching closing quote - continue our scan for
|
||||
# open quotes thereafter
|
||||
|
||||
@@ -45,6 +45,3 @@ class PrevalenceCounter(object):
|
||||
|
||||
def name_count(self, name):
|
||||
return self.name_counts[name]
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user