forked from pgadmin-org/pgadmin4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
1380 lines (1168 loc) · 44.2 KB
/
__init__.py
File metadata and controls
1380 lines (1168 loc) · 44.2 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 - 2025, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
"""Implements the Database Node"""
import re
from functools import wraps
import json
from flask import render_template, current_app, request, jsonify, Response
from flask_babel import gettext as _
from flask_security import current_user
from pgadmin.browser.server_groups import servers
from config import PG_DEFAULT_DRIVER
from pgadmin.browser.collection import CollectionNodeModule
from pgadmin.browser.server_groups.servers.databases.utils import \
parse_sec_labels_from_db, parse_variables_from_db, \
get_attributes_from_db_info
from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
parse_priv_to_db, get_db_disp_restriction
from pgadmin.browser.utils import PGChildNodeView
from pgadmin.utils.ajax import gone
from pgadmin.utils.ajax import make_json_response, \
make_response as ajax_response, internal_server_error, unauthorized
from pgadmin.utils.driver import get_driver
from pgadmin.tools.sqleditor.utils.query_history import QueryHistory
from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
from pgadmin.model import db, Server, Database
from pgadmin.browser.utils import underscore_escape
from pgadmin.utils.constants import TWO_PARAM_STRING
class DatabaseModule(CollectionNodeModule):
_NODE_TYPE = 'database'
_COLLECTION_LABEL = _("Databases")
_DATABASE_CSS_PATH = 'databases/css'
_DATABASE_CSS = "/".join([_DATABASE_CSS_PATH, 'database.css'])
def __init__(self, *args, **kwargs):
self.min_ver = None
self.max_ver = None
super().__init__(*args, **kwargs)
def get_nodes(self, gid, sid):
"""
Generate the collection node
"""
if self.show_node:
yield self.generate_browser_collection_node(sid)
@property
def script_load(self):
"""
Load the module script for server, when any of the server-group node is
initialized.
"""
return servers.ServerModule.node_type
@property
def csssnippets(self):
"""
Returns a snippet of css to include in the page
"""
snippets = [
render_template(
self._COLLECTION_CSS,
node_type=self.node_type,
_=_
),
render_template(
self._DATABASE_CSS,
node_type=self.node_type,
_=_
)
]
for submodule in self.submodules:
snippets.extend(submodule.csssnippets)
return snippets
@property
def module_use_template_javascript(self):
"""
Returns whether Jinja2 template is used for generating the javascript
module.
"""
return False
def register(self, app, options):
"""
Override the default register function to automagically register
sub-modules at once.
"""
from .casts import blueprint as module
self.submodules.append(module)
from .event_triggers import blueprint as module
self.submodules.append(module)
from .extensions import blueprint as module
self.submodules.append(module)
from .foreign_data_wrappers import blueprint as module
self.submodules.append(module)
from .languages import blueprint as module
self.submodules.append(module)
from .publications import blueprint as module
self.submodules.append(module)
from .schemas import schema_blueprint as module
self.submodules.append(module)
from .schemas import catalog_blueprint as module
self.submodules.append(module)
from .subscriptions import blueprint as module
self.submodules.append(module)
from .dbms_job_scheduler import blueprint as module
self.submodules.append(module)
super().register(app, options)
blueprint = DatabaseModule(__name__)
class DatabaseView(PGChildNodeView):
node_type = blueprint.node_type
node_label = "Database"
parent_ids = [
{'type': 'int', 'id': 'gid'},
{'type': 'int', 'id': 'sid'}
]
ids = [
{'type': 'int', 'id': 'did'}
]
operations = dict({
'obj': [
{'get': 'properties', 'delete': 'delete', 'put': 'update'},
{'get': 'list', 'post': 'create', 'delete': 'delete'}
],
'nodes': [
{'get': 'node'},
{'get': 'nodes'}
],
'get_databases': [
{'get': 'get_databases'},
{'get': 'get_databases'}
],
'sql': [
{'get': 'sql'}
],
'msql': [
{'get': 'msql'},
{'get': 'msql'}
],
'stats': [
{'get': 'statistics'},
{'get': 'statistics'}
],
'dependency': [
{'get': 'dependencies'}
],
'dependent': [
{'get': 'dependents'}
],
'children': [
{'get': 'children'}
],
'connect': [
{
'get': 'connect_status',
'post': 'connect',
'delete': 'disconnect'
}
],
'get_encodings': [
{'get': 'get_encodings'},
{'get': 'get_encodings'}
],
'get_ctypes': [
{'get': 'get_ctypes'},
{'get': 'get_ctypes'}
],
'get_icu_locale': [
{'get': 'get_icu_locale'},
{'get': 'get_icu_locale'}
],
'get_builtin_locale': [
{'get': 'get_builtin_locale'},
{'get': 'get_builtin_locale'}
],
'vopts': [
{}, {'get': 'variable_options'}
],
'delete': [{'delete': 'delete'},
{'delete': 'delete'}]
})
def check_precondition(action=None):
"""
This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to self
"""
def wrap(f):
@wraps(f)
def wrapped(self, *args, **kwargs):
self.manager = get_driver(
PG_DEFAULT_DRIVER
).connection_manager(
kwargs['sid']
)
if self.manager is None:
return gone(errormsg=_("Could not find the server."))
self.datistemplate = False
if action and action in ["drop"]:
self.conn = self.manager.connection()
elif 'did' in kwargs:
self.conn = self.manager.connection(did=kwargs['did'])
self.db_allow_connection = True
# If connection to database is not allowed then
# provide generic connection
if kwargs['did'] in self.manager.db_info:
self._db = self.manager.db_info[kwargs['did']]
self.datistemplate, datallowconn = \
get_attributes_from_db_info(self.manager, kwargs)
if datallowconn is False:
self.conn = self.manager.connection()
self.db_allow_connection = False
else:
self.conn = self.manager.connection()
# set template path for sql scripts
self.template_path = 'databases/sql/#{0}#'.format(
self.manager.version
)
return f(self, *args, **kwargs)
return wrapped
return wrap
@check_precondition(action="list")
def list(self, gid, sid):
last_system_oid = self.retrieve_last_system_oid()
db_disp_res, params = get_db_disp_restriction(self.manager)
SQL = render_template(
"/".join([self.template_path, self._PROPERTIES_SQL]),
conn=self.conn,
last_system_oid=last_system_oid,
db_restrictions=db_disp_res,
)
status, res = self.conn.execute_dict(SQL, params)
if not status:
return internal_server_error(errormsg=res)
result_set = []
for row in res['rows']:
row['is_sys_obj'] = (
row['did'] <= self._DATABASE_LAST_SYSTEM_OID or
self.datistemplate)
if self.skip_db(row):
continue
if self.manager.db == row['name']:
row['canDrop'] = False
else:
row['canDrop'] = True
result_set.append(row)
return ajax_response(
response=result_set,
status=200
)
def retrieve_last_system_oid(self):
last_system_oid = 0
if not self.blueprint.show_system_objects:
last_system_oid = self._DATABASE_LAST_SYSTEM_OID
return last_system_oid
def get_icon(self, res, connected):
if not connected and not res['is_template']:
icon = "icon-database-not-connected"
elif not connected and res['is_template']:
icon = 'icon-database-template-not-connected'
elif connected and res['is_template']:
icon = 'icon-database-template-connected'
else:
icon = "pg-icon-database"
return icon
def skip_db(self, row):
if not self.blueprint.show_system_objects \
and row['is_sys_obj'] \
and row['name'] not in ('postgres', 'edb') \
or not self.blueprint.show_database_template \
and row['is_sys_obj'] \
and row['name'] not in ('postgres', 'edb'):
return True
if not self.blueprint.show_database_template \
and row['is_template'] and \
not row['is_sys_obj'] and \
row['name'] not in ('postgres', 'edb'):
return True
return False
def get_nodes(self, gid, sid, is_schema_diff=False):
res = []
last_system_oid = self.retrieve_last_system_oid()
# if is_schema_diff then no need to show system templates.
if is_schema_diff and self.manager.db_info is not None and \
self.manager.did in self.manager.db_info:
last_system_oid = self._DATABASE_LAST_SYSTEM_OID
db_disp_res, params = get_db_disp_restriction(self.manager)
SQL = render_template(
"/".join([self.template_path, self._NODES_SQL]),
last_system_oid=last_system_oid,
db_restrictions=db_disp_res,
)
status, rset = self.conn.execute_dict(SQL, params)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
dbname = row['name']
row['is_sys_obj'] = (
row['did'] <= self._DATABASE_LAST_SYSTEM_OID or
self.datistemplate)
if self.skip_db(row):
continue
if self.manager.db == dbname:
connected = True
can_drop = can_dis_conn = False
else:
conn = self.manager.connection(database=dbname, did=row['did'])
connected = conn.connected()
can_drop = can_dis_conn = True
icon = self.get_icon(row, connected)
res.append(
self.blueprint.generate_browser_node(
row['did'],
sid,
row['name'],
icon=icon,
connected=connected,
tablespace=row['spcname'],
allowConn=row['datallowconn'],
canCreate=row['cancreate'],
canDisconn=can_dis_conn,
canDrop=can_drop,
isTemplate=row['is_template'],
inode=True if row['datallowconn'] else False,
description=row['description']
)
)
return res
@check_precondition(action="nodes")
def nodes(self, gid, sid, is_schema_diff=False):
res = self.get_nodes(gid, sid, is_schema_diff)
if isinstance(res, Response):
return res
return make_json_response(
data=res,
status=200
)
@check_precondition(action="get_databases")
def get_databases(self, gid, sid):
"""
This function is used to get all the databases irrespective of
show_system_object flag for templates in create database dialog.
:param gid:
:param sid:
:return:
"""
res = []
SQL = render_template(
"/".join([self.template_path, self._NODES_SQL]),
last_system_oid=0,
show_system_objects=True,
)
status, rset = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
res.append(row['name'])
return make_json_response(
data=res,
status=200
)
@check_precondition(action="node")
def node(self, gid, sid, did):
SQL = render_template(
"/".join([self.template_path, self._NODES_SQL]),
did=did, conn=self.conn, last_system_oid=0,
show_system_objects=self.blueprint.show_system_objects,
)
status, rset = self.conn.execute_2darray(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
db = row['name']
if self.manager.db == db:
connected = True
else:
conn = self.manager.connection(database=row['name'])
connected = conn.connected()
icon_css_class = "pg-icon-database"
if not connected:
icon_css_class = "icon-database-not-connected"
return make_json_response(
data=self.blueprint.generate_browser_node(
row['did'],
sid,
row['name'],
icon=icon_css_class,
connected=connected,
spcname=row['spcname'],
allowConn=row['datallowconn'],
canCreate=row['cancreate']
),
status=200
)
return gone(errormsg=self.not_found_error_msg())
@check_precondition(action="properties")
def properties(self, gid, sid, did):
SQL = render_template(
"/".join([self.template_path, self._PROPERTIES_SQL]),
did=did, conn=self.conn, last_system_oid=0,
show_system_objects=self.blueprint.show_system_objects
)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(
self.not_found_error_msg()
)
SQL = render_template(
"/".join([self.template_path, self._ACL_SQL]),
did=did, conn=self.conn
)
status, dataclres = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
res = self.formatdbacl(res, dataclres['rows'])
SQL = render_template(
"/".join([self.template_path, 'defacl.sql']),
did=did, conn=self.conn, grant_reovke_sql=False
)
status, defaclres = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
res = self.formatdbacl(res, defaclres['rows'])
result = res['rows'][0]
result['is_sys_obj'] = (
result['oid'] <= self._DATABASE_LAST_SYSTEM_OID)
# Fetching variable for database
SQL = render_template(
"/".join([self.template_path, 'get_variables.sql']),
did=did, conn=self.conn
)
status, res1 = self.conn.execute_dict(SQL)
database = Database.query.filter_by(id=did, server=sid).first()
if database:
result['schema_res'] = database.schema_res.split(
',') if database.schema_res else []
if not status:
return internal_server_error(errormsg=res1)
# Get Formatted Security Labels
if 'seclabels' in result:
# Security Labels is not available for PostgreSQL <= 9.1
frmtd_sec_labels = parse_sec_labels_from_db(result['seclabels'])
result.update(frmtd_sec_labels)
# Get Formatted Variables
frmtd_variables = parse_variables_from_db(res1['rows'])
result.update(frmtd_variables)
return ajax_response(
response=result,
status=200
)
@staticmethod
def formatdbacl(res, dbacl):
for row in dbacl:
priv = parse_priv_from_db(row)
res['rows'][0].setdefault(row['deftype'], []).append(priv)
return res
def connect(self, gid, sid, did):
"""Connect the Database."""
from pgadmin.utils.driver import get_driver
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
conn = manager.connection(did=did, auto_reconnect=True)
already_connected = conn.connected()
if not already_connected:
status, errmsg = conn.connect()
if not status:
current_app.logger.error(
"Could not connected to database(#{0}).\nError: {1}"
.format(
did, errmsg
)
)
return internal_server_error(errmsg)
else:
current_app.logger.info(
'Connection Established for Database Id: \
%s' % (did)
)
return make_json_response(
success=1,
info=_("Database connected."),
data={
'icon': 'pg-icon-database',
'already_connected': already_connected,
'connected': True,
'info_prefix': TWO_PARAM_STRING.
format(Server.query.filter_by(id=sid)[0].name, conn.db)
}
)
def disconnect(self, gid, sid, did):
"""Disconnect the database."""
# Release Connection
from pgadmin.utils.driver import get_driver
manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
conn = manager.connection(did=did, auto_reconnect=True)
status = manager.release(did=did)
if not status:
return unauthorized(_("Database could not be disconnected."))
else:
return make_json_response(
success=1,
info=_("Database disconnected."),
data={
'icon': 'icon-database-not-connected',
'connected': False,
'info_prefix': TWO_PARAM_STRING.
format(Server.query.filter_by(id=sid)[0].name, conn.db)
}
)
@check_precondition(action="get_encodings")
def get_encodings(self, gid, sid, did=None):
"""
This function to return list of avialable encodings
"""
res = []
SQL = render_template(
"/".join([self.template_path, 'get_encodings.sql'])
)
status, rset = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
res.append(
{'label': row['encoding'], 'value': row['encoding']}
)
return make_json_response(
data=res,
status=200
)
@check_precondition(action="get_ctypes")
def get_ctypes(self, gid, sid, did=None):
"""
This function to return list of available collation/character types
"""
res = []
default_list = ['C', 'POSIX']
for val in default_list:
res.append(
{'label': val, 'value': val}
)
SQL = render_template(
"/".join([self.template_path, 'get_ctypes.sql'])
)
status, rset = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
if row['cname'] not in default_list:
res.append({'label': row['cname'], 'value': row['cname']})
return make_json_response(
data=res,
status=200
)
@check_precondition(action="get_icu_locale")
def get_icu_locale(self, gid, sid, did=None):
"""
This function is used to get the list of icu locale
"""
res = []
SQL = render_template(
"/".join([self.template_path, 'get_icu_locale.sql'])
)
status, rset = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
res.append(
{'label': row['colliculocale'], 'value': row['colliculocale']})
return make_json_response(
data=res,
status=200
)
@check_precondition(action="get_builtin_locale")
def get_builtin_locale(self, gid, sid, did=None):
"""
This function is used to get the list of builtin locale
"""
res = []
SQL = render_template(
"/".join([self.template_path, 'get_builtin_locale.sql'])
)
status, rset = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=rset)
for row in rset['rows']:
res.append(
{'label': row['collbuiltinlocale'],
'value': row['collbuiltinlocale']})
return make_json_response(
data=res,
status=200
)
@check_precondition(action="create")
def create(self, gid, sid):
"""Create the database."""
required_args = [
'name'
]
data = request.form if request.form else json.loads(
request.data
)
for arg in required_args:
if arg not in data:
return make_json_response(
status=410,
success=0,
errormsg=_(
"Could not find the required parameter ({})."
).format(arg)
)
# The below SQL will execute CREATE DDL only
SQL = render_template(
"/".join([self.template_path, self._CREATE_SQL]),
data=data, conn=self.conn
)
status, msg = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=msg)
if 'datacl' in data:
data['datacl'] = parse_priv_to_db(data['datacl'], 'DATABASE')
# The below SQL will execute rest DMLs because we cannot execute
# CREATE with any other
SQL = render_template(
"/".join([self.template_path, self._GRANT_SQL]),
data=data, conn=self.conn
)
SQL = SQL.strip('\n').strip(' ')
if SQL and SQL != "":
status, msg = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=msg)
# We need oid of newly created database
SQL = render_template(
"/".join([self.template_path, self._PROPERTIES_SQL]),
name=data['name'], conn=self.conn, last_system_oid=0,
show_system_objects=self.blueprint.show_system_objects,
)
SQL = SQL.strip('\n').strip(' ')
if SQL and SQL != "":
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
response = res['rows'][0]
# Add database entry into database table with schema_restrictions.
database = Database(id=response['did'], server=sid,
schema_res=','.join(data['schema_res']))
db.session.add(database)
db.session.commit()
return jsonify(
node=self.blueprint.generate_browser_node(
response['did'],
sid,
response['name'],
icon="icon-database-not-connected",
connected=False,
tablespace=response['default_tablespace'],
allowConn=True,
canCreate=response['cancreate'],
canDisconn=True,
canDrop=True,
isTemplate=response['is_template']
)
)
@staticmethod
def _update_db_schema_res(data, did, sid):
database = Database.query.filter_by(id=did, server=sid).first()
if 'schema_res' in data:
if database:
data['schema_res'] = ','.join(data['schema_res'])
setattr(database, 'schema_res', data['schema_res'])
else:
database_obj = Database(id=did, server=sid,
schema_res=','.join(
data['schema_res']))
db.session.add(database_obj)
def _check_rename_db_or_change_table_space(self, data, conn, all_ids):
for action in ["rename_database", "tablespace"]:
sql = self.get_offline_sql(all_ids['gid'], all_ids['sid'], data,
all_ids['did'], action)
sql = sql.strip('\n').strip(' ')
if sql and sql != "":
status, msg = conn.execute_scalar(sql)
if not status:
# In case of error from server while rename it,
# reconnect to the database with old name again.
self.conn = self.manager.connection(
database=data['old_name'], auto_reconnect=True
)
status, errmsg = self.conn.connect()
if not status:
current_app.logger.error(
'Could not reconnected to database(#{0}).\n'
'Error: {1}'.format(all_ids['did'], errmsg)
)
return True, msg
QueryHistory.update_history_dbname(
current_user.id, all_ids['sid'], data['old_name'],
data['name'])
return False, ''
def _fetch_db_details(self, data, did):
if did is not None:
# Fetch the name of database for comparison
status, rset = self.conn.execute_dict(
render_template(
"/".join([self.template_path, self._NODES_SQL]),
did=did, conn=self.conn, last_system_oid=0,
show_system_objects=self.blueprint.show_system_objects,
)
)
if not status:
return True, rset
if len(rset['rows']) == 0:
return gone(
_('Could not find the database on the server.')
)
data['old_name'] = (rset['rows'][0])['name']
if 'name' not in data:
data['name'] = data['old_name']
return False, ''
def _reconnect_connect_db(self, data, did):
if self._db['datallowconn']:
self.conn = self.manager.connection(
database=data['name'], auto_reconnect=True
)
status, errmsg = self.conn.connect()
if not status:
current_app.logger.error(
'Could not connected to database(#{0}).\n'
'Error: {1}'.format(did, errmsg)
)
return True, errmsg
return False, ''
def _commit_db_changes(self, res, can_drop):
if self.manager.db == res['name']:
can_drop = False
try:
db.session.commit()
except Exception as e:
current_app.logger.exception(e)
return True, e.message, False
return False, '', can_drop
def _get_data_from_request(self):
return request.form if request.form else json.loads(
request.data
)
@check_precondition(action='update')
def update(self, gid, sid, did):
"""Update the database."""
data = self._get_data_from_request()
# Update schema restriction in db object.
DatabaseView._update_db_schema_res(data, did, sid)
# Generic connection for offline updates
conn = self.manager.connection(conn_id='db_offline_update')
status, errmsg = conn.connect()
if not status:
current_app.logger.error(
"Could not create database connection for offline updates\n"
"Err: {0}".format(errmsg)
)
return internal_server_error(errmsg)
fetching_error, err_msg = self._fetch_db_details(data, did)
if fetching_error:
return internal_server_error(errormsg=err_msg)
# Release any existing connection from connection manager
# to perform offline operation
self.manager.release(did=did)
all_ids = {
'gid': gid,
'sid': sid,
'did': did
}
is_error, errmsg = self._check_rename_db_or_change_table_space(data,
conn,
all_ids)
if is_error:
return internal_server_error(errmsg)
# Make connection for database again
connection_error, errmsg = self._reconnect_connect_db(data, did)
if connection_error:
return internal_server_error(errmsg)
sql = self.get_online_sql(gid, sid, data, did)
sql = sql.strip('\n').strip(' ')
if sql and sql != "":
status, msg = self.conn.execute_scalar(sql)
if not status:
return internal_server_error(errormsg=msg)
# Release any existing connection from connection manager
# used for offline updates
self.manager.release(conn_id="db_offline_update")
# Fetch the new data again after update for proper node
# generation
status, rset = self.conn.execute_dict(
render_template(
"/".join([self.template_path, self._NODES_SQL]),
did=did, conn=self.conn, last_system_oid=0,
show_system_objects=self.blueprint.show_system_objects,
)
)
if not status:
return internal_server_error(errormsg=rset)
if len(rset['rows']) == 0:
return gone(
self.not_found_error_msg()
)
res = rset['rows'][0]
can_drop = True
error, errmsg, is_can_drop = self._commit_db_changes(res, can_drop)
if error:
return make_json_response(
success=0,
errormsg=errmsg
)
can_drop = can_dis_conn = is_can_drop
icon = self.get_icon(res,
self.conn.connected()
if self._db['datallowconn'] else False)
return jsonify(
node=self.blueprint.generate_browser_node(
did,
sid,
res['name'],
icon=icon,
connected=self.conn.connected() if
self._db['datallowconn'] else False,
tablespace=res['spcname'],
allowConn=res['datallowconn'],
canCreate=res['cancreate'],
canDisconn=can_dis_conn,
canDrop=can_drop,
inode=True if res['datallowconn'] else False,
isTemplate=res['is_template'],
)
)
def _release_conn_before_delete(self, sid, did):
"""
Check connection and release it before deleting database.
:param sid: Server Id.
:param did: Database Id.
:return: Return error if any.
"""
if self.conn.connected():
# Release the connection if it is connected
from pgadmin.utils.driver import get_driver
manager = \
get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
manager.connection(did=did, auto_reconnect=True)
status = manager.release(did=did)
if not status:
return True, unauthorized(
_("Database could not be deleted."))
return False, ''