-
Notifications
You must be signed in to change notification settings - Fork 831
Expand file tree
/
Copy path__init__.py
More file actions
3186 lines (2700 loc) · 105 KB
/
__init__.py
File metadata and controls
3186 lines (2700 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2026, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
"""A blueprint module implementing the sqleditor frame."""
import os
import pickle
import re
import secrets
from urllib.parse import unquote
from threading import Lock
from io import BytesIO
import threading
import math
import json
from sqlalchemy import or_
from config import PG_DEFAULT_DRIVER, ALLOW_SAVE_PASSWORD
from werkzeug.user_agent import UserAgent
from flask import Response, url_for, render_template, session, current_app, \
send_file
from flask import request
from flask_babel import gettext
from pgadmin.tools.sqleditor.utils.query_tool_connection_check \
import query_tool_connection_check
from pgadmin.user_login_check import pga_login_required
from flask_security import current_user, permissions_required
from pgadmin.misc.file_manager import Filemanager
from pgadmin.tools.sqleditor.command import QueryToolCommand, ObjectRegistry, \
SQLFilter
from pgadmin.tools.sqleditor.utils.constant_definition import ASYNC_OK, \
ASYNC_EXECUTION_ABORTED, \
CONNECTION_STATUS_MESSAGE_MAPPING, TX_STATUS_INERROR
from pgadmin.tools.sqleditor.utils.start_running_query import StartRunningQuery
from pgadmin.tools.sqleditor.utils.update_session_grid_transaction import \
update_session_grid_transaction
from pgadmin.utils import PgAdminModule
from pgadmin.utils import get_storage_directory
from pgadmin.utils.ajax import make_json_response, bad_request, \
success_return, internal_server_error, service_unavailable, gone
from pgadmin.utils.driver import get_driver
from pgadmin.utils.exception import ConnectionLost, SSHTunnelConnectionLost, \
CryptKeyMissing, ObjectGone
from pgadmin.browser.utils import underscore_escape
from pgadmin.utils.menu import MenuItem
from pgadmin.utils.csrf import pgCSRFProtect
from pgadmin.utils.sqlautocomplete.autocomplete import SQLAutoComplete
from pgadmin.tools.sqleditor.utils.query_tool_preferences import \
register_query_tool_preferences
from pgadmin.tools.sqleditor.utils.filter_dialog import FilterDialog
from pgadmin.tools.sqleditor.utils.query_history import QueryHistory
from pgadmin.tools.sqleditor.utils.macros import get_macros, \
get_user_macros, set_macros
from pgadmin.utils.constants import MIMETYPE_APP_JS, \
SERVER_CONNECTION_CLOSED, ERROR_MSG_TRANS_ID_NOT_FOUND, \
ERROR_FETCHING_DATA, MY_STORAGE, ACCESS_DENIED_MESSAGE, \
ERROR_MSG_FAIL_TO_PROMOTE_QT
from pgadmin.model import Server, ServerGroup
from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
from pgadmin.settings import get_setting
from pgadmin.utils.preferences import Preferences
from pgadmin.tools.sqleditor.utils.apply_explain_plan_wrapper import \
get_explain_query_length
from pgadmin.tools.user_management.PgAdminPermissions import AllPermissionTypes
from pgadmin.browser.server_groups.servers.utils import \
convert_connection_parameter, get_db_disp_restriction
from pgadmin.misc.workspaces import check_and_delete_adhoc_server
from pgadmin.utils.driver.psycopg3.typecast import \
register_binary_data_typecasters
MODULE_NAME = 'sqleditor'
TRANSACTION_STATUS_CHECK_FAILED = gettext("Transaction status check failed.")
_NODES_SQL = 'nodes.sql'
sqleditor_close_session_lock = Lock()
auto_complete_objects = dict()
class SqlEditorModule(PgAdminModule):
"""
class SqlEditorModule(PgAdminModule)
A module class for SQL Grid derived from PgAdminModule.
"""
LABEL = gettext("Query Tool")
def get_own_menuitems(self):
return {'tools': [
MenuItem(name='mnu_query_tool',
label=gettext('Query tool'),
priority=100,
callback='show_query_tool',
icon='fa fa-question',
url=url_for('help.static', filename='index.html'))
]}
def get_exposed_url_endpoints(self):
"""
Returns:
list: URL endpoints for sqleditor module
"""
return [
'sqleditor.initialize_viewdata',
'sqleditor.initialize_sqleditor',
'sqleditor.initialize_sqleditor_with_did',
'sqleditor.filter_validate',
'sqleditor.panel',
'sqleditor.close',
'sqleditor.update_sqleditor_connection',
'sqleditor.view_data_start',
'sqleditor.query_tool_start',
'sqleditor.poll',
'sqleditor.fetch_window',
'sqleditor.fetch_all_from_start',
'sqleditor.save',
'sqleditor.inclusive_filter',
'sqleditor.exclusive_filter',
'sqleditor.remove_filter',
'sqleditor.set_limit',
'sqleditor.cancel_transaction',
'sqleditor.get_object_name',
'sqleditor.auto_commit',
'sqleditor.auto_rollback',
'sqleditor.autocomplete',
'sqleditor.query_tool_download',
'sqleditor.connection_status',
'sqleditor.get_filter_data',
'sqleditor.set_filter_data',
'sqleditor.get_query_history',
'sqleditor.add_query_history',
'sqleditor.clear_query_history',
'sqleditor.get_macro',
'sqleditor.get_macros',
'sqleditor.get_user_macros',
'sqleditor.set_macros',
'sqleditor.get_new_connection_data',
'sqleditor.get_new_connection_servers',
'sqleditor.get_new_connection_database',
'sqleditor.get_new_connection_user',
'sqleditor._check_server_connection_status',
'sqleditor.get_new_connection_role',
'sqleditor.connect_server',
'sqleditor.server_cursor',
'sqleditor.nlq_chat_stream',
'sqleditor.explain_analyze_stream',
'sqleditor.download_binary_data',
]
def on_logout(self):
"""
This is a callback function when user logout from pgAdmin
:param user:
:return:
"""
with sqleditor_close_session_lock:
if 'gridData' in session:
for trans_id in session['gridData']:
close_sqleditor_session(trans_id)
# Delete all grid data from session variable
del session['gridData']
def register_preferences(self):
register_query_tool_preferences(self)
blueprint = SqlEditorModule(MODULE_NAME, __name__, static_url_path='/static')
@blueprint.route('/')
@pga_login_required
def index():
return bad_request(
errormsg=gettext('This URL cannot be requested directly.')
)
@blueprint.route(
'/initialize/viewdata/<int:trans_id>/<int:cmd_type>/<obj_type>/'
'<int:sgid>/<int:sid>/<int:did>/<int:obj_id>',
methods=["PUT", "POST"],
endpoint="initialize_viewdata"
)
@pga_login_required
def initialize_viewdata(trans_id, cmd_type, obj_type, sgid, sid, did, obj_id):
"""
This method is responsible for creating an asynchronous connection.
After creating the connection it will instantiate and initialize
the object as per the object type. It will also create a unique
transaction id and store the information into session variable.
Args:
cmd_type: Contains value for which menu item is clicked.
obj_type: Contains type of selected object for which data grid to
be render
sgid: Server group Id
sid: Server Id
did: Database Id
obj_id: Id of currently selected object
"""
if request.data:
_data = json.loads(request.data)
else:
_data = request.args or request.form
filter_sql = _data['sql_filter'] if 'sql_filter' in _data else None
server_cursor = _data['server_cursor'] if\
'server_cursor' in _data and (
_data['server_cursor'] == 'true' or _data['server_cursor'] is True
) else False
dbname = _data['dbname'] if 'dbname' in _data else None
kwargs = {
'user': _data['user'] if 'user' in _data else None,
'role': _data['role'] if 'role' in _data else None,
'password': _data['password'] if 'password' in _data else None
}
server = Server.query.filter_by(id=sid).first()
if kwargs.get('password', None) is None:
kwargs['encpass'] = server.password
else:
kwargs['encpass'] = None
# Create asynchronous connection using random connection id.
conn_id = str(secrets.choice(range(1, 9999999)))
try:
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
# default_conn is same connection which is created when user connect to
# database from tree
conn = manager.connection(conn_id=conn_id,
auto_reconnect=False,
use_binary_placeholder=True,
array_to_string=True,
**({"database": dbname} if dbname is not None
else {"did": did}
))
status, msg, is_ask_password, user, _, _ = _connect(
conn,**kwargs)
if not status:
current_app.logger.error(msg)
if is_ask_password:
return make_json_response(
success=0,
status=428,
result={
"server_label": server.name,
"username": user or server.username,
"errmsg": msg,
"prompt_password": True,
"allow_save_password": True
if ALLOW_SAVE_PASSWORD and
session.get('allow_save_password', None)
else False,
}
)
else:
return internal_server_error(
errormsg=str(msg))
default_conn = manager.connection(did=did)
except (ConnectionLost, SSHTunnelConnectionLost):
raise
except Exception as e:
current_app.logger.error(e)
return internal_server_error(errormsg=str(e))
status, msg = default_conn.connect()
if not status:
current_app.logger.error(msg)
return internal_server_error(errormsg=str(msg))
status, msg = conn.connect()
if not status:
current_app.logger.error(msg)
return internal_server_error(errormsg=str(msg))
try:
# if object type is partition then it is nothing but a table.
if obj_type == 'partition':
obj_type = 'table'
# Get the object as per the object type
command_obj = ObjectRegistry.get_object(
obj_type, conn_id=conn_id, sgid=sgid, sid=sid,
did=did, obj_id=obj_id, cmd_type=cmd_type,
sql_filter=filter_sql, server_cursor=server_cursor
)
except ObjectGone:
raise
except Exception as e:
current_app.logger.error(e)
return internal_server_error(errormsg=str(e))
if 'gridData' not in session:
sql_grid_data = dict()
else:
sql_grid_data = session['gridData']
# if server disconnected and server password not saved, once re-connected
# it will check for the old transaction object and restore the filter_sql
# and data_sorting keys of the filter dialog into the
# newly created command object.
if str(trans_id) in sql_grid_data:
old_trans_obj = pickle.loads(
sql_grid_data[str(trans_id)]['command_obj'])
if old_trans_obj.did == did and old_trans_obj.obj_id == obj_id:
command_obj.set_filter(old_trans_obj._row_filter)
command_obj.set_data_sorting(
dict(data_sorting=old_trans_obj._data_sorting), True)
# Set the value of database name, that will be used later
command_obj.dbname = conn.db if conn.db else None
# Use pickle to store the command object which will be used later by the
# sql grid module.
sql_grid_data[str(trans_id)] = {
# -1 specify the highest protocol version available
'command_obj': pickle.dumps(command_obj, -1)
}
# Store the grid dictionary into the session variable
session['gridData'] = sql_grid_data
return make_json_response(
data={
'conn_id': conn_id
}
)
@blueprint.route(
'/panel/<int:trans_id>',
methods=["POST"],
endpoint='panel'
)
@pga_login_required
def panel(trans_id):
"""
This method calls index.html to render the data grid.
Args:
trans_id: unique transaction id
"""
params = None
if request.args:
params = {k: v for k, v in request.args.items()}
if request.form:
for key, val in request.form.items():
params[key] = val
params['trans_id'] = trans_id
# We need client OS information to render correct Keyboard shortcuts
params['client_platform'] = UserAgent(request.headers.get('User-Agent'))\
.platform
params['is_linux'] = False
from sys import platform as _platform
if "linux" in _platform:
params['is_linux'] = True
# Fetch the server details
params['bgcolor'] = None
params['fgcolor'] = None
s = Server.query.filter_by(id=int(params['sid'])).first()
if s:
if s.shared and s.user_id != current_user.id:
# Import here to avoid circular dependency
from pgadmin.browser.server_groups.servers import ServerModule
shared_server = ServerModule.get_shared_server(s, params['sgid'])
s = ServerModule.get_shared_server_properties(s, shared_server)
if s and s.bgcolor:
# If background is set to white means we do not have to change
# the title background else change it as per user specified
# background
if s.bgcolor != '#ffffff':
params['bgcolor'] = s.bgcolor
params['fgcolor'] = s.fgcolor or 'black'
params['server_name'] = underscore_escape(s.name)
if 'user' not in params:
params['user'] = underscore_escape(s.username)
if 'role' not in params and s.role:
params['role'] = underscore_escape(s.role)
params['layout'] = get_setting('SQLEditor/Layout')
params['macros'] = get_user_macros()
params['is_desktop_mode'] = current_app.PGADMIN_RUNTIME
params['title'] = underscore_escape(params['title'])
params['selectedNodeInfo'] = (
underscore_escape(params['selectedNodeInfo']))
if 'database_name' in params:
params['database_name'] = (
underscore_escape(params['database_name']))
params['server_cursor'] = params[
'server_cursor'] if 'server_cursor' in params else False
return render_template(
"sqleditor/index.html",
title=underscore_escape(params['title']),
params=json.dumps(params),
)
else:
params['error'] = 'The server was not found.'
return render_template(
"sqleditor/index.html",
title=None,
params=json.dumps(params))
@blueprint.route(
'/initialize/sqleditor/<int:trans_id>/<int:sgid>/<int:sid>/'
'<did>',
methods=["POST"], endpoint='initialize_sqleditor_with_did'
)
@blueprint.route(
'/initialize/sqleditor/<int:trans_id>/<int:sgid>/<int:sid>/'
'<int:did>',
methods=["POST"], endpoint='initialize_sqleditor_with_did'
)
@blueprint.route(
'/initialize/sqleditor/<int:trans_id>/<int:sgid>/<int:sid>',
methods=["POST"], endpoint='initialize_sqleditor'
)
@permissions_required(AllPermissionTypes.tools_query_tool)
@pga_login_required
def initialize_sqleditor(trans_id, sgid, sid, did=None):
"""
This method is responsible for instantiating and initializing
the query tool object. It will also create a unique
transaction id and store the information into session variable.
Args:
sgid: Server group Id
sid: Server Id
did: Database Id
"""
connect = True
# Read the data if present. Skipping read may cause connection
# reset error if data is sent from the client
data = {}
if request.data:
data = json.loads(request.data)
req_args = request.args
if ('recreate' in req_args and
req_args['recreate'] == '1'):
connect = False
kwargs = {
'user': data['user'] if 'user' in data else None,
'role': data['role'] if 'role' in data else None,
'password': data['password'] if 'password' in data else None
}
is_error, errmsg, conn_id, version = _init_sqleditor(
trans_id, connect, sgid, sid, did, data['dbname'], **kwargs)
if is_error:
return errmsg
return make_json_response(
data={
'connId': str(conn_id),
'serverVersion': version,
}
)
def _connect(conn, **kwargs):
"""
Connect the database.
:param conn: Connection instance.
:param kwargs: user, role and password data from user.
:return:
"""
user = None
role = None
password = None
is_ask_password = False
if 'user' in kwargs and 'role' in kwargs:
user = kwargs['user']
role = kwargs['role'] if kwargs['role'] else None
password = kwargs['password'] if kwargs['password'] else None
encpass = kwargs['encpass'] if kwargs['encpass'] else None
is_ask_password = True
if user:
status, msg = conn.connect(user=user, role=role,
password=password, encpass=encpass)
else:
status, msg = conn.connect(**kwargs)
return status, msg, is_ask_password, user, role, password
def _init_sqleditor(trans_id, connect, sgid, sid, did, dbname=None, **kwargs):
# Create asynchronous connection using random connection id.
conn_id = kwargs['conn_id'] if 'conn_id' in kwargs else str(
secrets.choice(range(1, 9999999)))
if 'conn_id' in kwargs:
kwargs.pop('conn_id')
conn_id_ac = str(secrets.choice(range(1, 9999999)))
server = Server.query.filter_by(id=sid).first()
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
if kwargs.get('password', None) is None:
kwargs['encpass'] = server.password
else:
kwargs['encpass'] = None
if did is None:
did = manager.did
try:
command_obj = ObjectRegistry.get_object(
'query_tool', conn_id=conn_id, sgid=sgid, sid=sid, did=did,
conn_id_ac=conn_id_ac, **kwargs
)
except Exception as e:
current_app.logger.error(e)
return True, internal_server_error(errormsg=str(e)), '', ''
pref = Preferences.module('sqleditor')
if kwargs.get('auto_commit', None) is None:
kwargs['auto_commit'] = pref.preference('auto_commit').get()
if kwargs.get('auto_rollback', None) is None:
kwargs['auto_rollback'] = pref.preference('auto_rollback').get()
if kwargs.get('server_cursor', None) is None:
kwargs['server_cursor'] = pref.preference('server_cursor').get()
try:
conn = manager.connection(conn_id=conn_id,
auto_reconnect=False,
use_binary_placeholder=True,
array_to_string=True,
**({"database": dbname} if dbname is not None
else {"did": did}))
if connect:
status, msg, is_ask_password, user, _, _ = _connect(
conn, **kwargs)
if not status:
current_app.logger.error(msg)
if is_ask_password:
return True, make_json_response(
success=0,
status=428,
result={
"server_label": server.name,
"username": user or server.username,
"errmsg": msg,
"prompt_password": True,
"allow_save_password": True
if ALLOW_SAVE_PASSWORD and
session.get('allow_save_password', None)
else False,
}
), '', ''
else:
return True, internal_server_error(
errormsg=str(msg)), '', ''
if pref.preference('autocomplete_on_key_press').get():
conn_ac = manager.connection(conn_id=conn_id_ac,
auto_reconnect=False,
use_binary_placeholder=True,
array_to_string=True,
**({"database": dbname}
if dbname is not None
else {"did": did}))
status, msg, is_ask_password, user, _, _ = _connect(
conn_ac, **kwargs)
except (ConnectionLost, SSHTunnelConnectionLost) as e:
current_app.logger.error(e)
raise
except Exception as e:
current_app.logger.error(e)
return True, internal_server_error(errormsg=str(e)), '', ''
if 'gridData' not in session:
sql_grid_data = dict()
else:
sql_grid_data = session['gridData']
# Set the value of auto commit and auto rollback specified in Preferences
command_obj.set_auto_commit(kwargs['auto_commit'])
command_obj.set_auto_rollback(kwargs['auto_rollback'])
command_obj.set_server_cursor(kwargs['server_cursor'])
# Set the value of database name, that will be used later
command_obj.dbname = dbname if dbname else None
# Use pickle to store the command object which will be used
# later by the sql grid module.
sql_grid_data[str(trans_id)] = {
# -1 specify the highest protocol version available
'command_obj': pickle.dumps(command_obj, -1)
}
# Store the grid dictionary into the session variable
session['gridData'] = sql_grid_data
return False, '', conn_id, manager.version
@blueprint.route(
'/initialize/sqleditor/update_connection/<int:trans_id>/'
'<int:sgid>/<int:sid>/<int:did>',
methods=["POST"], endpoint='update_sqleditor_connection'
)
def update_sqleditor_connection(trans_id, sgid, sid, did):
# Remove transaction Id.
with sqleditor_close_session_lock:
data = json.loads(request.data)
if 'gridData' not in session:
return make_json_response(data={'status': True})
grid_data = session['gridData']
# Return from the function if transaction id not found
if str(trans_id) not in grid_data:
return make_json_response(data={'status': True})
connect = True
req_args = request.args
if ('recreate' in req_args and
req_args['recreate'] == '1'):
connect = False
# Old transaction
_, _, _, trans_obj, session_obj = \
check_transaction_status(trans_id)
new_trans_id = str(secrets.choice(range(1, 9999999)))
kwargs = {
'user': data['user'],
'role': data['role'] if 'role' in data else None,
'password': data['password'] if 'password' in data else None,
'auto_commit': getattr(trans_obj, 'auto_commit', None),
'auto_rollback': getattr(trans_obj, 'auto_rollback', None),
}
is_error, errmsg, conn_id, version = _init_sqleditor(
new_trans_id, connect, sgid, sid, did, data['database_name'],
**kwargs)
if is_error:
return errmsg
else:
try:
_, _, _, _, new_session_obj = \
check_transaction_status(new_trans_id)
new_session_obj['primary_keys'] = session_obj[
'primary_keys'] if 'primary_keys' in session_obj else None
new_session_obj['columns_info'] = session_obj[
'columns_info'] if 'columns_info' in session_obj else None
new_session_obj['client_primary_key'] = session_obj[
'client_primary_key'] if 'client_primary_key'\
in session_obj else None
close_sqleditor_session(trans_id)
# Remove the information of unique transaction id from the
# session variable.
grid_data.pop(str(trans_id), None)
session['gridData'] = grid_data
except Exception as e:
current_app.logger.error(e)
return make_json_response(
data={
'connId': str(conn_id),
'serverVersion': version,
'trans_id': new_trans_id
}
)
@blueprint.route('/close/<int:trans_id>', methods=["DELETE"], endpoint='close')
def close(trans_id):
"""
This method is used to close the asynchronous connection
and remove the information of unique transaction id from
the session variable.
Args:
trans_id: unique transaction id
"""
with sqleditor_close_session_lock:
# delete the SQLAutoComplete object
if trans_id in auto_complete_objects:
del auto_complete_objects[trans_id]
if 'gridData' not in session:
return make_json_response(data={'status': True})
grid_data = session['gridData']
# Return from the function if transaction id not found
if str(trans_id) not in grid_data:
return make_json_response(data={'status': True})
try:
close_sqleditor_session(trans_id)
# Remove the information of unique transaction id from the
# session variable.
grid_data.pop(str(trans_id), None)
session['gridData'] = grid_data
except Exception as e:
current_app.logger.error(e)
return internal_server_error(errormsg=str(e))
return make_json_response(data={'status': True})
@blueprint.route(
'/filter/validate/<int:sid>/<int:did>/<int:obj_id>',
methods=["PUT", "POST"], endpoint='filter_validate'
)
@pga_login_required
def validate_filter(sid, did, obj_id):
"""
This method is used to validate the sql filter.
Args:
sid: Server Id
did: Database Id
obj_id: Id of currently selected object
"""
if request.data:
filter_data = json.loads(request.data)
else:
filter_data = request.args or request.form
try:
# Create object of SQLFilter class
sql_filter_obj = SQLFilter(sid=sid, did=did, obj_id=obj_id)
# Call validate_filter method to validate the SQL.
status, res = sql_filter_obj.validate_filter(filter_data['filter_sql'])
if not status:
return internal_server_error(errormsg=str(res))
except ObjectGone:
raise
except Exception as e:
current_app.logger.error(e)
return internal_server_error(errormsg=str(e))
return make_json_response(data={'status': status, 'result': res})
def close_sqleditor_session(trans_id):
"""
This function is used to cancel the transaction and release the connection.
:param trans_id: Transaction id
:return:
"""
if 'gridData' in session and str(trans_id) in session['gridData']:
cmd_obj_str = session['gridData'][str(trans_id)]['command_obj']
# Use pickle.loads function to get the command object
cmd_obj = pickle.loads(cmd_obj_str)
# if connection id is None then no need to release the connection
if cmd_obj.conn_id is not None:
manager = get_driver(
PG_DEFAULT_DRIVER).connection_manager(cmd_obj.sid)
if manager is not None:
conn = manager.connection(
did=cmd_obj.did, conn_id=cmd_obj.conn_id)
# Release the connection
if conn.connected():
conn.cancel_transaction(cmd_obj.conn_id, cmd_obj.did)
manager.release(did=cmd_obj.did, conn_id=cmd_obj.conn_id)
# Check if all the connections of the adhoc server is
# closed then delete the server from the pgadmin database.
check_and_delete_adhoc_server(cmd_obj.sid)
# Close the auto complete connection
if hasattr(cmd_obj, 'conn_id_ac') and cmd_obj.conn_id_ac is not None:
manager = get_driver(
PG_DEFAULT_DRIVER).connection_manager(cmd_obj.sid)
if manager is not None:
conn = manager.connection(
did=cmd_obj.did, conn_id=cmd_obj.conn_id_ac)
# Release the connection
if conn.connected():
conn.cancel_transaction(cmd_obj.conn_id_ac, cmd_obj.did)
manager.release(did=cmd_obj.did,
conn_id=cmd_obj.conn_id_ac)
def check_transaction_status(trans_id, auto_comp=False):
"""
This function is used to check the transaction id
is available in the session object and connection
status.
Args:
trans_id: Transaction Id
auto_comp: Auto complete flag
Returns: status and connection object
"""
if 'gridData' not in session:
return False, ERROR_MSG_TRANS_ID_NOT_FOUND, None, None, None
grid_data = session['gridData']
# Return from the function if transaction id not found
if str(trans_id) not in grid_data:
return False, ERROR_MSG_TRANS_ID_NOT_FOUND, None, None, None
# Fetch the object for the specified transaction id.
# Use pickle.loads function to get the command object
session_obj = grid_data[str(trans_id)]
trans_obj = pickle.loads(session_obj['command_obj'])
if auto_comp:
conn_id = trans_obj.conn_id_ac
connect = True
else:
conn_id = trans_obj.conn_id
connect = True if 'connect' in request.args and \
request.args['connect'] == '1' else False
try:
manager = get_driver(
PG_DEFAULT_DRIVER).connection_manager(trans_obj.sid)
conn = manager.connection(
did=trans_obj.did,
conn_id=conn_id,
auto_reconnect=False,
use_binary_placeholder=True,
array_to_string=True,
**({"database": trans_obj.dbname} if hasattr(
trans_obj, 'dbname') else {})
)
except (ConnectionLost, SSHTunnelConnectionLost, CryptKeyMissing):
raise
except Exception as e:
current_app.logger.error(e)
return False, internal_server_error(errormsg=str(e)), None, None, None
if connect and conn and not conn.connected():
conn.connect()
return True, None, conn, trans_obj, session_obj
@blueprint.route(
'/view_data/start/<int:trans_id>',
methods=["GET"], endpoint='view_data_start'
)
@pga_login_required
def start_view_data(trans_id):
"""
This method is used to execute query using asynchronous connection.
Args:
trans_id: unique transaction id
"""
limit = -1
# Check the transaction and connection status
status, error_msg, conn, trans_obj, session_obj = \
check_transaction_status(trans_id)
if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
return make_json_response(success=0, errormsg=error_msg,
info='DATAGRID_TRANSACTION_REQUIRED',
status=404)
if not status and error_msg and type(error_msg) is Response:
return error_msg
# Check if connect is passed in the request.
connect = 'connect' in request.args and request.args['connect'] == '1'
# get the default connection as current connection which is attached to
# trans id holds the cursor which has query result so we cannot use that
# connection to execute another query otherwise we'll lose query result.
try:
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
trans_obj.sid)
default_conn = manager.connection(did=trans_obj.did,
** ({"database": trans_obj.dbname}
if hasattr(trans_obj, 'dbname')
else {}))
except (ConnectionLost, SSHTunnelConnectionLost) as e:
raise
except Exception as e:
current_app.logger.error(e)
return internal_server_error(errormsg=str(e))
# Connect to the Server if not connected.
if not conn.connected() or not default_conn.connected():
if connect:
# This will check if view/edit data tool connection is lost or not,
# if lost then it will reconnect
status, error_msg, conn, trans_obj, session_obj, response = \
query_tool_connection_check(trans_id)
# This is required for asking user to enter password
# when password is not saved for the server
if response is not None:
return response
status, _ = default_conn.connect()
if not status:
return service_unavailable(
gettext("Connection to the server has been lost."),
info="CONNECTION_LOST"
)
if status and conn is not None and \
trans_obj is not None and session_obj is not None:
# set fetched row count to 0 as we are executing query again.
trans_obj.update_fetched_row_cnt(0)
# Fetch the sql and primary_keys from the object
sql = trans_obj.get_sql(default_conn)
_, primary_keys = trans_obj.get_primary_keys(default_conn)
session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
has_oids = False
if trans_obj.object_type == 'table':
# Fetch OIDs status
has_oids = trans_obj.has_oids(default_conn)
# Fetch the applied filter.
filter_applied = trans_obj.is_filter_applied()
# Fetch the limit for the SQL query
limit = trans_obj.get_limit()
can_edit = trans_obj.can_edit()
can_filter = trans_obj.can_filter()
# Store the primary keys to the session object
session_obj['primary_keys'] = primary_keys
# Store the OIDs status into session object
session_obj['has_oids'] = has_oids
update_session_grid_transaction(trans_id, session_obj)
if trans_obj.server_cursor:
conn.release_async_cursor()
conn.execute_void("BEGIN;")
# Execute sql asynchronously
status, result = conn.execute_async(
sql,
server_cursor=trans_obj.server_cursor)
else:
status = False
result = error_msg
filter_applied = False
can_edit = False
can_filter = False
sql = None
return make_json_response(
data={
'status': status, 'result': result,
'filter_applied': filter_applied,
'limit': limit, 'can_edit': can_edit,
'can_filter': can_filter, 'sql': sql,
}
)
@blueprint.route(
'/query_tool/start/<int:trans_id>',
methods=["PUT", "POST"], endpoint='query_tool_start'
)
@pga_login_required
def start_query_tool(trans_id):
"""