codekingpro commited on
Commit
4b9cd65
·
verified ·
1 Parent(s): ae01f49

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/aggregates/__init__.py +371 -0
  2. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py +364 -0
  3. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/__init__.py +853 -0
  4. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/create.sql +59 -0
  5. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/properties.sql +10 -0
  6. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/15_plus/properties.sql +10 -0
  7. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/16_plus/properties.sql +10 -0
  8. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/backend_support.sql +18 -0
  9. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/count.sql +5 -0
  10. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/create.sql +47 -0
  11. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/delete.sql +1 -0
  12. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_collations.sql +7 -0
  13. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_name.sql +5 -0
  14. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/__init__.py +1030 -0
  15. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/__init__.py +770 -0
  16. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/coll-domain_constraints.svg +1 -0
  17. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints-bad.svg +1 -0
  18. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints.svg +1 -0
  19. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.js +79 -0
  20. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.ui.js +59 -0
  21. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/css/domain_constraints.css +26 -0
  22. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/create.sql +10 -0
  23. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/delete.sql +4 -0
  24. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_domain.sql +8 -0
  25. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_oid.sql +7 -0
  26. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_type_category.sql +5 -0
  27. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/properties.sql +22 -0
  28. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/update.sql +13 -0
  29. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/coll-domain.svg +1 -0
  30. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/domain.svg +1 -0
  31. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.js +100 -0
  32. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui.js +224 -0
  33. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/count.sql +9 -0
  34. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql +41 -0
  35. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/delete.sql +16 -0
  36. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/domain_schema_diff.sql +54 -0
  37. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_collations.sql +10 -0
  38. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_constraints.sql +15 -0
  39. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_oid.sql +18 -0
  40. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/node.sql +23 -0
  41. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/properties.sql +34 -0
  42. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/update.sql +100 -0
  43. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py +1942 -0
  44. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/children/__init__.py +14 -0
  45. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/__init__.py +97 -0
  46. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/coll-foreign_table_column.svg +1 -0
  47. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/foreign_table_column.svg +1 -0
  48. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/js/foreign_table_column.js +70 -0
  49. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/coll-foreign_table.svg +1 -0
  50. pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/foreign_table.svg +1 -0
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/aggregates/__init__.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """ Implements Aggregate Node """
11
+
12
+ from functools import wraps
13
+
14
+ from flask import render_template
15
+ from flask_babel import gettext
16
+
17
+ import pgadmin.browser.server_groups.servers.databases as database
18
+ from config import PG_DEFAULT_DRIVER
19
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
20
+ import SchemaChildModule
21
+ from pgadmin.browser.utils import PGChildNodeView
22
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
23
+ make_response as ajax_response, gone
24
+ from pgadmin.utils.compile_template_name import compile_template_path
25
+ from pgadmin.utils.driver import get_driver
26
+
27
+
28
+ class AggregateModule(SchemaChildModule):
29
+ """
30
+ class AggregateModule(SchemaChildModule)
31
+
32
+ A module class for Aggregate node derived from SchemaChildModule.
33
+
34
+ Methods:
35
+ -------
36
+ * __init__(*args, **kwargs)
37
+ - Method is used to initialize the Aggregate and it's base module.
38
+
39
+ * get_nodes(gid, sid, did, scid, agid)
40
+ - Method is used to generate the browser collection node.
41
+
42
+ * node_inode()
43
+ - Method is overridden from its base class to make the node as leaf node.
44
+
45
+ * script_load()
46
+ - Load the module script for schema, when any of the server node is
47
+ initialized.
48
+ """
49
+
50
+ _NODE_TYPE = 'aggregate'
51
+ _COLLECTION_LABEL = gettext("Aggregates")
52
+
53
+ def __init__(self, *args, **kwargs):
54
+ """
55
+ Method is used to initialize the AggregateModule and it's base module.
56
+
57
+ Args:
58
+ *args:
59
+ **kwargs:
60
+ """
61
+
62
+ super().__init__(*args, **kwargs)
63
+ self.min_ver = 90100
64
+ self.max_ver = None
65
+
66
+ def get_nodes(self, gid, sid, did, scid):
67
+ """
68
+ Generate the collection node
69
+ """
70
+ if self.has_nodes(sid, did, scid=scid,
71
+ base_template_path=AggregateView.BASE_TEMPLATE_PATH):
72
+ yield self.generate_browser_collection_node(scid)
73
+
74
+ @property
75
+ def script_load(self):
76
+ """
77
+ Load the module script for database, when any of the database node is
78
+ initialized.
79
+ """
80
+ return database.DatabaseModule.node_type
81
+
82
+ @property
83
+ def node_inode(self):
84
+ return False
85
+
86
+
87
+ blueprint = AggregateModule(__name__)
88
+
89
+
90
+ class AggregateView(PGChildNodeView):
91
+ """
92
+ This class is responsible for generating routes for Aggregate node
93
+
94
+ Methods:
95
+ -------
96
+ * __init__(**kwargs)
97
+ - Method is used to initialize the AggregateView and it's base view.
98
+
99
+ * check_precondition()
100
+ - This function will behave as a decorator which will checks
101
+ database connection before running view, it will also attaches
102
+ manager,conn & template_path properties to self
103
+
104
+ * list()
105
+ - This function is used to list all the Aggregate nodes within that
106
+ collection.
107
+
108
+ * nodes()
109
+ - This function will used to create all the child node within that
110
+ collection, Here it will create all the Aggregate node.
111
+
112
+ * properties(gid, sid, did, scid, agid)
113
+ - This function will show the properties of the selected Aggregate node
114
+
115
+
116
+ * sql(gid, sid, did, scid):
117
+ - This function will generate sql to show it in sql pane for the
118
+ selected Aggregate node.
119
+ """
120
+
121
+ node_type = blueprint.node_type
122
+ node_label = "Aggregate"
123
+ BASE_TEMPLATE_PATH = 'aggregates/sql/#{0}#'
124
+
125
+ parent_ids = [
126
+ {'type': 'int', 'id': 'gid'},
127
+ {'type': 'int', 'id': 'sid'},
128
+ {'type': 'int', 'id': 'did'},
129
+ {'type': 'int', 'id': 'scid'}
130
+ ]
131
+ ids = [
132
+ {'type': 'int', 'id': 'agid'}
133
+ ]
134
+
135
+ operations = dict({
136
+ 'obj': [
137
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
138
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
139
+ ],
140
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
141
+ 'children': [{'get': 'children'}],
142
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
143
+ 'sql': [{'get': 'sql'}]
144
+ })
145
+
146
+ def check_precondition(f):
147
+ """
148
+ This function will behave as a decorator which will checks
149
+ database connection before running view, it will also attaches
150
+ manager,conn & template_path properties to self
151
+ """
152
+
153
+ @wraps(f)
154
+ def wrap(*args, **kwargs):
155
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
156
+ self = args[0]
157
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
158
+ kwargs['sid']
159
+ )
160
+ self.conn = self.manager.connection(did=kwargs['did'])
161
+ self.datistemplate = False
162
+ if (
163
+ self.manager.db_info is not None and
164
+ kwargs['did'] in self.manager.db_info and
165
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
166
+ ):
167
+ self.datistemplate = self.manager.db_info[
168
+ kwargs['did']]['datistemplate']
169
+
170
+ # Set the template path for the SQL scripts
171
+ self.template_path = \
172
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
173
+
174
+ return f(*args, **kwargs)
175
+
176
+ return wrap
177
+
178
+ @check_precondition
179
+ def list(self, gid, sid, did, scid):
180
+ """
181
+ This function is used to list all the aggregate nodes within that
182
+ collection.
183
+
184
+ Args:
185
+ gid: Server group ID
186
+ sid: Server ID
187
+ did: Database ID
188
+ scid: Schema ID
189
+
190
+ Returns:
191
+ JSON of available aggregate nodes
192
+ """
193
+
194
+ SQL = render_template("/".join([self.template_path,
195
+ self._NODES_SQL]), scid=scid)
196
+ status, res = self.conn.execute_dict(SQL)
197
+
198
+ if not status:
199
+ return internal_server_error(errormsg=res)
200
+ return ajax_response(
201
+ response=res['rows'],
202
+ status=200
203
+ )
204
+
205
+ @check_precondition
206
+ def nodes(self, gid, sid, did, scid):
207
+ """
208
+ This function will used to create all the child node within that
209
+ collection.
210
+ Here it will create all the aggregate node.
211
+
212
+ Args:
213
+ gid: Server Group ID
214
+ sid: Server ID
215
+ did: Database ID
216
+ scid: Schema ID
217
+
218
+ Returns:
219
+ JSON of available aggregate child nodes
220
+ """
221
+
222
+ res = []
223
+ SQL = render_template("/".join([self.template_path,
224
+ self._NODES_SQL]), scid=scid)
225
+ status, rset = self.conn.execute_2darray(SQL)
226
+ if not status:
227
+ return internal_server_error(errormsg=rset)
228
+
229
+ for row in rset['rows']:
230
+ res.append(
231
+ self.blueprint.generate_browser_node(
232
+ row['oid'],
233
+ scid,
234
+ row['name'],
235
+ icon="icon-aggregate",
236
+ description=row['description']
237
+ ))
238
+
239
+ return make_json_response(
240
+ data=res,
241
+ status=200
242
+ )
243
+
244
+ @check_precondition
245
+ def node(self, gid, sid, did, scid, agid):
246
+ """
247
+ This function will fetch properties of the aggregate node.
248
+
249
+ Args:
250
+ gid: Server Group ID
251
+ sid: Server ID
252
+ did: Database ID
253
+ scid: Schema ID
254
+ agid: Aggregate ID
255
+
256
+ Returns:
257
+ JSON of given aggregate node
258
+ """
259
+
260
+ SQL = render_template("/".join([self.template_path,
261
+ self._NODES_SQL]), agid=agid)
262
+ status, rset = self.conn.execute_2darray(SQL)
263
+ if not status:
264
+ return internal_server_error(errormsg=rset)
265
+
266
+ for row in rset['rows']:
267
+ return make_json_response(
268
+ data=self.blueprint.generate_browser_node(
269
+ row['oid'],
270
+ scid,
271
+ row['name'],
272
+ icon="icon-aggregate"
273
+ ),
274
+ status=200
275
+ )
276
+
277
+ return gone(self.not_found_error_msg())
278
+
279
+ @check_precondition
280
+ def properties(self, gid, sid, did, scid, agid):
281
+ """
282
+ This function will show the properties of the selected aggregate node.
283
+
284
+ Args:
285
+ gid: Server Group ID
286
+ sid: Server ID
287
+ did: Database ID
288
+ scid: Schema ID
289
+ scid: Schema ID
290
+ agid: Aggregate ID
291
+
292
+ Returns:
293
+ JSON of selected aggregate node
294
+ """
295
+
296
+ status, res = self._fetch_properties(scid, agid)
297
+ if not status:
298
+ return res
299
+
300
+ return ajax_response(
301
+ response=res,
302
+ status=200
303
+ )
304
+
305
+ def _fetch_properties(self, scid, agid):
306
+ """
307
+ This function fetch the properties for the specified object.
308
+
309
+ :param scid: Schema ID
310
+ :param agid: Aggregate ID
311
+ """
312
+
313
+ SQL = render_template("/".join([self.template_path,
314
+ self._PROPERTIES_SQL]),
315
+ scid=scid, agid=agid,
316
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
317
+ status, res = self.conn.execute_dict(SQL)
318
+
319
+ if not status:
320
+ return False, internal_server_error(errormsg=res)
321
+
322
+ if len(res['rows']) == 0:
323
+ return False, gone(self.not_found_error_msg())
324
+
325
+ res['rows'][0]['is_sys_obj'] = (
326
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
327
+ self.datistemplate)
328
+
329
+ return True, res['rows'][0]
330
+
331
+ @check_precondition
332
+ def sql(self, gid, sid, did, scid, agid, **kwargs):
333
+ """
334
+ This function will generates reverse engineered sql for aggregate
335
+ object
336
+
337
+ Args:
338
+ gid: Server Group ID
339
+ sid: Server ID
340
+ did: Database ID
341
+ scid: Schema ID
342
+ agid: Aggregate ID
343
+ json_resp: True then return json response
344
+ """
345
+
346
+ SQL = render_template("/".join([self.template_path,
347
+ self._PROPERTIES_SQL]),
348
+ scid=scid, agid=agid)
349
+ status, res = self.conn.execute_dict(SQL)
350
+ if not status:
351
+ return internal_server_error(errormsg=res)
352
+ if len(res['rows']) == 0:
353
+ return gone(self.not_found_error_msg())
354
+
355
+ data = res['rows'][0]
356
+
357
+ SQL = render_template("/".join([self.template_path,
358
+ self._CREATE_SQL]),
359
+ data=data)
360
+
361
+ sql_header = "-- Aggregate: {0};\n\n-- ".format(data['name'])
362
+
363
+ sql_header += render_template("/".join([self.template_path,
364
+ self._DELETE_SQL]),
365
+ data=data)
366
+ SQL = sql_header + '\n' + SQL.strip('\n')
367
+
368
+ return ajax_response(response=SQL)
369
+
370
+
371
+ AggregateView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """ Implements Catalog objects Node."""
11
+
12
+ from functools import wraps
13
+
14
+ from flask import render_template
15
+ from flask_babel import gettext
16
+
17
+ import pgadmin.browser.server_groups.servers.databases as database
18
+ from config import PG_DEFAULT_DRIVER
19
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
20
+ import SchemaChildModule
21
+ from pgadmin.browser.utils import PGChildNodeView
22
+ from pgadmin.utils.ajax import gone
23
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
24
+ make_response as ajax_response
25
+ from pgadmin.utils.driver import get_driver
26
+
27
+
28
+ class CatalogObjectModule(SchemaChildModule):
29
+ """
30
+ class CatalogObjectModule(SchemaChildModule)
31
+
32
+ A module class for Catalog objects node derived from SchemaChildModule.
33
+
34
+ Methods:
35
+ -------
36
+ * __init__(*args, **kwargs)
37
+ - Method is used to initialize the Catalog objects and it's base module.
38
+
39
+ * get_nodes(gid, sid, did, scid, coid)
40
+ - Method is used to generate the browser collection node.
41
+
42
+ * script_load()
43
+ - Load the module script for Catalog objects, when any of the server node
44
+ is initialized.
45
+ """
46
+ _NODE_TYPE = 'catalog_object'
47
+ _COLLECTION_LABEL = gettext("Catalog Objects")
48
+
49
+ # Flag for not to show node under Schema/Catalog node
50
+ # By default its set to True to display node in schema/catalog
51
+ # We do not want to display 'Catalog Objects' under Schema/Catalog
52
+ # but only in information_schema/sys
53
+ CATALOG_DB_SUPPORTED = False
54
+ SUPPORTED_SCHEMAS = ['information_schema', 'sys']
55
+
56
+ def __init__(self, *args, **kwargs):
57
+ """
58
+ Method is used to initialize the CatalogObjectModule and it's base
59
+ module.
60
+
61
+ Args:
62
+ *args:
63
+ **kwargs:
64
+ """
65
+ super().__init__(*args, **kwargs)
66
+ self.min_ver = None
67
+ self.max_ver = None
68
+
69
+ def get_nodes(self, gid, sid, did, scid):
70
+ """
71
+ Generate the collection node
72
+ """
73
+ yield self.generate_browser_collection_node(scid)
74
+
75
+ @property
76
+ def script_load(self):
77
+ """
78
+ Load the module script for server, when any of the database node is
79
+ initialized.
80
+ """
81
+ return database.DatabaseModule.node_type
82
+
83
+ def register(self, app, options):
84
+ """
85
+ Override the default register function to automagically register
86
+ sub-modules at once.
87
+ """
88
+ super().register(app, options)
89
+
90
+ from .columns import blueprint as module
91
+ app.register_blueprint(module)
92
+
93
+
94
+ blueprint = CatalogObjectModule(__name__)
95
+
96
+
97
+ class CatalogObjectView(PGChildNodeView):
98
+ """
99
+ This class is responsible for generating routes for Catalog objects node.
100
+
101
+ Methods:
102
+ -------
103
+ * check_precondition()
104
+ - This function will behave as a decorator which will checks
105
+ database connection before running view, it will also attaches
106
+ manager,conn & template_path properties to self
107
+
108
+ * list()
109
+ - Lists all the Catalog objects nodes within that collection.
110
+
111
+ * nodes()
112
+ - Creates all the nodes of type Catalog objects.
113
+
114
+ * properties(gid, sid, did, scid, coid)
115
+ - Shows the properties of the selected Catalog objects node.
116
+
117
+ * dependency(gid, sid, did, scid):
118
+ - Returns the dependencies list for the given catalog object node.
119
+
120
+ * dependent(gid, sid, did, scid):
121
+ - Returns the dependents list for the given Catalog objects node.
122
+ """
123
+ node_type = blueprint.node_type
124
+
125
+ parent_ids = [
126
+ {'type': 'int', 'id': 'gid'},
127
+ {'type': 'int', 'id': 'sid'},
128
+ {'type': 'int', 'id': 'did'},
129
+ {'type': 'int', 'id': 'scid'}
130
+ ]
131
+ ids = [
132
+ {'type': 'int', 'id': 'coid'}
133
+ ]
134
+
135
+ operations = dict({
136
+ 'obj': [{'get': 'properties'}, {'get': 'list'}],
137
+ 'children': [{'get': 'children'}],
138
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
139
+ 'sql': [{'get': 'sql'}],
140
+ 'dependency': [{'get': 'dependencies'}],
141
+ 'dependent': [{'get': 'dependents'}]
142
+ })
143
+
144
+ def check_precondition(f):
145
+ """
146
+ This function will behave as a decorator which will checks
147
+ database connection before running view, it will also attaches
148
+ manager,conn & template_path properties to self
149
+ """
150
+
151
+ @wraps(f)
152
+ def wrap(*args, **kwargs):
153
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
154
+ self = args[0]
155
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
156
+ kwargs['sid']
157
+ )
158
+ self.conn = self.manager.connection(did=kwargs['did'])
159
+ self.datistemplate = False
160
+ if (
161
+ self.manager.db_info is not None and
162
+ kwargs['did'] in self.manager.db_info and
163
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
164
+ ):
165
+ self.datistemplate = self.manager.db_info[
166
+ kwargs['did']]['datistemplate']
167
+
168
+ self.template_path = 'catalog_object/sql/{0}/#{1}#'.format(
169
+ 'ppas' if self.manager.server_type == 'ppas' else 'pg',
170
+ self.manager.version
171
+ )
172
+
173
+ return f(*args, **kwargs)
174
+
175
+ return wrap
176
+
177
+ @check_precondition
178
+ def list(self, gid, sid, did, scid):
179
+ """
180
+ This function is used to list all the catalog objects
181
+ nodes within that collection.
182
+
183
+ Args:
184
+ gid: Server group ID
185
+ sid: Server ID
186
+ did: Database ID
187
+ scid: Schema ID
188
+
189
+ Returns:
190
+ JSON of available catalog objects nodes
191
+ """
192
+
193
+ SQL = render_template("/".join([
194
+ self.template_path, self._PROPERTIES_SQL
195
+ ]), scid=scid
196
+ )
197
+
198
+ status, res = self.conn.execute_dict(SQL)
199
+
200
+ if not status:
201
+ return internal_server_error(errormsg=res)
202
+ return ajax_response(
203
+ response=res['rows'],
204
+ status=200
205
+ )
206
+
207
+ @check_precondition
208
+ def nodes(self, gid, sid, did, scid):
209
+ """
210
+ This function will used to create all the child node within that
211
+ collection.
212
+ Here it will create all the catalog objects node.
213
+
214
+ Args:
215
+ gid: Server Group ID
216
+ sid: Server ID
217
+ did: Database ID
218
+ scid: Schema ID
219
+
220
+ Returns:
221
+ JSON of available catalog objects child nodes
222
+ """
223
+ res = []
224
+ SQL = render_template(
225
+ "/".join([self.template_path, self._NODES_SQL]), scid=scid
226
+ )
227
+
228
+ status, rset = self.conn.execute_2darray(SQL)
229
+ if not status:
230
+ return internal_server_error(errormsg=rset)
231
+
232
+ for row in rset['rows']:
233
+ res.append(
234
+ self.blueprint.generate_browser_node(
235
+ row['oid'],
236
+ scid,
237
+ row['name'],
238
+ icon="icon-catalog_object",
239
+ description=row['description']
240
+ ))
241
+
242
+ return make_json_response(
243
+ data=res,
244
+ status=200
245
+ )
246
+
247
+ @check_precondition
248
+ def node(self, gid, sid, did, scid, coid):
249
+ """
250
+ This function will fetch properties of catalog objects node.
251
+
252
+ Args:
253
+ gid: Server Group ID
254
+ sid: Server ID
255
+ did: Database ID
256
+ scid: Schema ID
257
+ coid: Catalog object ID
258
+
259
+ Returns:
260
+ JSON of given catalog objects child node
261
+ """
262
+ SQL = render_template(
263
+ "/".join([self.template_path, self._NODES_SQL]), coid=coid
264
+ )
265
+
266
+ status, rset = self.conn.execute_2darray(SQL)
267
+ if not status:
268
+ return internal_server_error(errormsg=rset)
269
+
270
+ for row in rset['rows']:
271
+ return make_json_response(
272
+ data=self.blueprint.generate_browser_node(
273
+ row['oid'],
274
+ scid,
275
+ row['name'],
276
+ icon="icon-catalog_object"
277
+ ),
278
+ status=200
279
+ )
280
+
281
+ return gone(
282
+ errormsg=gettext("Could not find the specified catalog object."))
283
+
284
+ @check_precondition
285
+ def properties(self, gid, sid, did, scid, coid):
286
+ """
287
+ This function will show the properties of the selected
288
+ catalog objects node.
289
+
290
+ Args:
291
+ gid: Server Group ID
292
+ sid: Server ID
293
+ did: Database ID
294
+ scid: Schema ID
295
+ scid: Schema ID
296
+ coid: Catalog object ID
297
+
298
+ Returns:
299
+ JSON of selected catalog objects node
300
+ """
301
+ SQL = render_template(
302
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
303
+ scid=scid, coid=coid
304
+ )
305
+ status, res = self.conn.execute_dict(SQL)
306
+
307
+ if not status:
308
+ return internal_server_error(errormsg=res)
309
+
310
+ if len(res['rows']) == 0:
311
+ return gone(
312
+ gettext("""Could not find the specified catalog object."""))
313
+
314
+ res['rows'][0]['is_sys_obj'] = (
315
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
316
+ self.datistemplate)
317
+
318
+ return ajax_response(
319
+ response=res['rows'][0],
320
+ status=200
321
+ )
322
+
323
+ @check_precondition
324
+ def dependents(self, gid, sid, did, scid, coid):
325
+ """
326
+ This function get the dependents and return ajax response
327
+ for the catalog objects node.
328
+
329
+ Args:
330
+ gid: Server Group ID
331
+ sid: Server ID
332
+ did: Database ID
333
+ scid: Schema ID
334
+ coid: catalog objects ID
335
+ """
336
+ dependents_result = self.get_dependents(self.conn, coid)
337
+
338
+ return ajax_response(
339
+ response=dependents_result,
340
+ status=200
341
+ )
342
+
343
+ @check_precondition
344
+ def dependencies(self, gid, sid, did, scid, coid):
345
+ """
346
+ This function get the dependencies and return ajax response
347
+ for the catalog objects node.
348
+
349
+ Args:
350
+ gid: Server Group ID
351
+ sid: Server ID
352
+ did: Database ID
353
+ scid: Schema ID
354
+ coid: catalog objects ID
355
+ """
356
+ dependencies_result = self.get_dependencies(self.conn, coid)
357
+
358
+ return ajax_response(
359
+ response=dependencies_result,
360
+ status=200
361
+ )
362
+
363
+
364
+ CatalogObjectView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/__init__.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """ Implements Collation Node """
11
+
12
+ from functools import wraps
13
+
14
+ import json
15
+ from flask import render_template, request, jsonify
16
+ from flask_babel import gettext
17
+
18
+ import pgadmin.browser.server_groups.servers.databases as database
19
+ from config import PG_DEFAULT_DRIVER
20
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
21
+ import SchemaChildModule
22
+ from pgadmin.browser.utils import PGChildNodeView
23
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
24
+ make_response as ajax_response, gone
25
+ from pgadmin.utils.compile_template_name import compile_template_path
26
+ from pgadmin.utils.driver import get_driver
27
+ from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
28
+ from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
29
+
30
+
31
+ class CollationModule(SchemaChildModule):
32
+ """
33
+ class CollationModule(CollectionNodeModule)
34
+
35
+ A module class for Collation node derived from CollectionNodeModule.
36
+
37
+ Methods:
38
+ -------
39
+ * __init__(*args, **kwargs)
40
+ - Method is used to initialize the Collation and it's base module.
41
+
42
+ * get_nodes(gid, sid, did, scid, coid)
43
+ - Method is used to generate the browser collection node.
44
+
45
+ * node_inode()
46
+ - Method is overridden from its base class to make the node as leaf node.
47
+
48
+ * script_load()
49
+ - Load the module script for schema, when any of the server node is
50
+ initialized.
51
+ """
52
+
53
+ _NODE_TYPE = 'collation'
54
+ _COLLECTION_LABEL = gettext("Collations")
55
+
56
+ def __init__(self, *args, **kwargs):
57
+ """
58
+ Method is used to initialize the CollationModule and it's base module.
59
+
60
+ Args:
61
+ *args:
62
+ **kwargs:
63
+ """
64
+
65
+ super().__init__(*args, **kwargs)
66
+ self.min_ver = 90100
67
+ self.max_ver = None
68
+
69
+ def get_nodes(self, gid, sid, did, scid):
70
+ """
71
+ Generate the collection node
72
+ """
73
+ if self.has_nodes(sid, did, scid=scid,
74
+ base_template_path=CollationView.BASE_TEMPLATE_PATH):
75
+ yield self.generate_browser_collection_node(scid)
76
+
77
+ @property
78
+ def script_load(self):
79
+ """
80
+ Load the module script for database, when any of the database node is
81
+ initialized.
82
+ """
83
+ return database.DatabaseModule.node_type
84
+
85
+ @property
86
+ def node_inode(self):
87
+ return False
88
+
89
+
90
+ blueprint = CollationModule(__name__)
91
+
92
+
93
+ class CollationView(PGChildNodeView, SchemaDiffObjectCompare):
94
+ """
95
+ This class is responsible for generating routes for Collation node
96
+
97
+ Methods:
98
+ -------
99
+ * __init__(**kwargs)
100
+ - Method is used to initialize the CollationView and it's base view.
101
+
102
+ * check_precondition()
103
+ - This function will behave as a decorator which will checks
104
+ database connection before running view, it will also attaches
105
+ manager,conn & template_path properties to self
106
+
107
+ * list()
108
+ - This function is used to list all the Collation nodes within that
109
+ collection.
110
+
111
+ * nodes()
112
+ - This function will used to create all the child node within that
113
+ collection, Here it will create all the Collation node.
114
+
115
+ * properties(gid, sid, did, scid, coid)
116
+ - This function will show the properties of the selected Collation node
117
+
118
+ * create(gid, sid, did, scid)
119
+ - This function will create the new Collation object
120
+
121
+ * update(gid, sid, did, scid, coid)
122
+ - This function will update the data for the selected Collation node
123
+
124
+ * delete(self, gid, sid, scid, coid):
125
+ - This function will drop the Collation object
126
+
127
+ * msql(gid, sid, did, scid, coid)
128
+ - This function is used to return modified SQL for the selected
129
+ Collation node
130
+
131
+ * get_sql(data, scid, coid)
132
+ - This function will generate sql from model data
133
+
134
+ * sql(gid, sid, did, scid):
135
+ - This function will generate sql to show it in sql pane for the
136
+ selected Collation node.
137
+
138
+ * dependency(gid, sid, did, scid):
139
+ - This function will generate dependency list show it in dependency
140
+ pane for the selected Collation node.
141
+
142
+ * dependent(gid, sid, did, scid):
143
+ - This function will generate dependent list to show it in dependent
144
+ pane for the selected Collation node.
145
+
146
+ * compare(**kwargs):
147
+ - This function will compare the collation nodes from two different
148
+ schemas.
149
+ """
150
+
151
+ node_type = blueprint.node_type
152
+ node_label = "Collation"
153
+ BASE_TEMPLATE_PATH = 'collations/sql/#{0}#'
154
+
155
+ parent_ids = [
156
+ {'type': 'int', 'id': 'gid'},
157
+ {'type': 'int', 'id': 'sid'},
158
+ {'type': 'int', 'id': 'did'},
159
+ {'type': 'int', 'id': 'scid'}
160
+ ]
161
+ ids = [
162
+ {'type': 'int', 'id': 'coid'}
163
+ ]
164
+
165
+ operations = dict({
166
+ 'obj': [
167
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
168
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
169
+ ],
170
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
171
+ 'children': [{'get': 'children'}],
172
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
173
+ 'sql': [{'get': 'sql'}],
174
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
175
+ 'stats': [{'get': 'statistics'}],
176
+ 'dependency': [{'get': 'dependencies'}],
177
+ 'dependent': [{'get': 'dependents'}],
178
+ 'get_collations': [{'get': 'get_collation'},
179
+ {'get': 'get_collation'}],
180
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
181
+ })
182
+
183
+ def check_precondition(f):
184
+ """
185
+ This function will behave as a decorator which will checks
186
+ database connection before running view, it will also attaches
187
+ manager,conn & template_path properties to self
188
+ """
189
+
190
+ @wraps(f)
191
+ def wrap(*args, **kwargs):
192
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
193
+ self = args[0]
194
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
195
+ kwargs['sid']
196
+ )
197
+ self.conn = self.manager.connection(did=kwargs['did'])
198
+ self.datistemplate = False
199
+ if (
200
+ self.manager.db_info is not None and
201
+ kwargs['did'] in self.manager.db_info and
202
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
203
+ ):
204
+ self.datistemplate = self.manager.db_info[
205
+ kwargs['did']]['datistemplate']
206
+
207
+ # Set the template path for the SQL scripts
208
+ self.template_path = \
209
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
210
+
211
+ return f(*args, **kwargs)
212
+
213
+ return wrap
214
+
215
+ @check_precondition
216
+ def list(self, gid, sid, did, scid):
217
+ """
218
+ This function is used to list all the collation nodes within that
219
+ collection.
220
+
221
+ Args:
222
+ gid: Server group ID
223
+ sid: Server ID
224
+ did: Database ID
225
+ scid: Schema ID
226
+
227
+ Returns:
228
+ JSON of available collation nodes
229
+ """
230
+
231
+ SQL = render_template("/".join([self.template_path,
232
+ self._PROPERTIES_SQL]), scid=scid)
233
+ status, res = self.conn.execute_dict(SQL)
234
+
235
+ if not status:
236
+ return internal_server_error(errormsg=res)
237
+ return ajax_response(
238
+ response=res['rows'],
239
+ status=200
240
+ )
241
+
242
+ @check_precondition
243
+ def nodes(self, gid, sid, did, scid):
244
+ """
245
+ This function will used to create all the child node within that
246
+ collection.
247
+ Here it will create all the collation node.
248
+
249
+ Args:
250
+ gid: Server Group ID
251
+ sid: Server ID
252
+ did: Database ID
253
+ scid: Schema ID
254
+
255
+ Returns:
256
+ JSON of available collation child nodes
257
+ """
258
+
259
+ res = []
260
+ SQL = render_template("/".join([self.template_path,
261
+ self._NODES_SQL]), scid=scid)
262
+ status, rset = self.conn.execute_2darray(SQL)
263
+ if not status:
264
+ return internal_server_error(errormsg=rset)
265
+
266
+ for row in rset['rows']:
267
+ res.append(
268
+ self.blueprint.generate_browser_node(
269
+ row['oid'],
270
+ scid,
271
+ row['name'],
272
+ icon="icon-collation",
273
+ description=row['description']
274
+ ))
275
+
276
+ return make_json_response(
277
+ data=res,
278
+ status=200
279
+ )
280
+
281
+ @check_precondition
282
+ def node(self, gid, sid, did, scid, coid):
283
+ """
284
+ This function will fetch properties of the collation node.
285
+
286
+ Args:
287
+ gid: Server Group ID
288
+ sid: Server ID
289
+ did: Database ID
290
+ scid: Schema ID
291
+ coid: Collation ID
292
+
293
+ Returns:
294
+ JSON of given collation node
295
+ """
296
+
297
+ SQL = render_template("/".join([self.template_path,
298
+ self._NODES_SQL]), coid=coid)
299
+ status, rset = self.conn.execute_2darray(SQL)
300
+ if not status:
301
+ return internal_server_error(errormsg=rset)
302
+
303
+ for row in rset['rows']:
304
+ return make_json_response(
305
+ data=self.blueprint.generate_browser_node(
306
+ row['oid'],
307
+ scid,
308
+ row['name'],
309
+ icon="icon-collation"
310
+ ),
311
+ status=200
312
+ )
313
+
314
+ return gone(self.not_found_error_msg())
315
+
316
+ @check_precondition
317
+ def properties(self, gid, sid, did, scid, coid):
318
+ """
319
+ This function will show the properties of the selected collation node.
320
+
321
+ Args:
322
+ gid: Server Group ID
323
+ sid: Server ID
324
+ did: Database ID
325
+ scid: Schema ID
326
+ scid: Schema ID
327
+ coid: Collation ID
328
+
329
+ Returns:
330
+ JSON of selected collation node
331
+ """
332
+
333
+ status, res = self._fetch_properties(scid, coid)
334
+ if not status:
335
+ return res
336
+
337
+ return ajax_response(
338
+ response=res,
339
+ status=200
340
+ )
341
+
342
+ def _fetch_properties(self, scid, coid):
343
+ """
344
+ This function fetch the properties for the specified object.
345
+
346
+ :param scid: Schema ID
347
+ :param coid: Collation ID
348
+ """
349
+
350
+ SQL = render_template("/".join([self.template_path,
351
+ self._PROPERTIES_SQL]),
352
+ scid=scid, coid=coid,
353
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
354
+ status, res = self.conn.execute_dict(SQL)
355
+
356
+ if not status:
357
+ return False, internal_server_error(errormsg=res)
358
+
359
+ if len(res['rows']) == 0:
360
+ return False, gone(self.not_found_error_msg())
361
+
362
+ res['rows'][0]['is_sys_obj'] = (
363
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
364
+ self.datistemplate)
365
+
366
+ return True, res['rows'][0]
367
+
368
+ @check_precondition
369
+ def get_collation(self, gid, sid, did, scid, coid=None):
370
+ """
371
+ This function will return list of collation available
372
+ as AJAX response.
373
+ """
374
+
375
+ res = []
376
+ try:
377
+ SQL = render_template("/".join([self.template_path,
378
+ 'get_collations.sql']))
379
+ status, rset = self.conn.execute_2darray(SQL)
380
+ if not status:
381
+ return internal_server_error(errormsg=res)
382
+
383
+ for row in rset['rows']:
384
+ res.append(
385
+ {'label': row['copy_collation'],
386
+ 'value': row['copy_collation']}
387
+ )
388
+ return make_json_response(
389
+ data=res,
390
+ status=200
391
+ )
392
+
393
+ except Exception as e:
394
+ return internal_server_error(errormsg=str(e))
395
+
396
+ def _check_definition(self, data):
397
+ """
398
+ Args:
399
+ data: request data received from client
400
+
401
+ Returns:
402
+ True if defination is missing, False otherwise
403
+ """
404
+ definition_args = [
405
+ 'locale',
406
+ 'copy_collation',
407
+ 'lc_collate',
408
+ 'lc_type'
409
+ ]
410
+
411
+ # Additional server side validation to check if
412
+ # definition is sent properly from client side
413
+ missing_definition_flag = False
414
+
415
+ for arg in definition_args:
416
+ if (
417
+ arg == 'locale' and
418
+ (arg not in data or data[arg] == '') and
419
+ 'copy_collation' not in data and
420
+ 'lc_collate' not in data and 'lc_type' not in data
421
+ ):
422
+ missing_definition_flag = True
423
+
424
+ if (
425
+ arg == 'copy_collation' and
426
+ (arg not in data or data[arg] == '') and
427
+ 'locale' not in data and
428
+ 'lc_collate' not in data and 'lc_type' not in data
429
+ ):
430
+ missing_definition_flag = True
431
+
432
+ if (
433
+ (arg == 'lc_collate' or arg == 'lc_type') and
434
+ (arg not in data or data[arg] == '') and
435
+ 'copy_collation' not in data and 'locale' not in data
436
+ ):
437
+ missing_definition_flag = True
438
+
439
+ return missing_definition_flag
440
+
441
+ @check_precondition
442
+ def create(self, gid, sid, did, scid):
443
+ """
444
+ This function will creates new the collation object
445
+
446
+ Args:
447
+ gid: Server Group ID
448
+ sid: Server ID
449
+ did: Database ID
450
+ scid: Schema ID
451
+ """
452
+
453
+ data = request.form if request.form else json.loads(
454
+ request.data
455
+ )
456
+
457
+ required_args = [
458
+ 'schema',
459
+ 'name'
460
+ ]
461
+
462
+ for arg in required_args:
463
+ if arg not in data:
464
+ return make_json_response(
465
+ status=410,
466
+ success=0,
467
+ errormsg=gettext(
468
+ "Could not find the required parameter ({})."
469
+ ).format(arg)
470
+ )
471
+ if self._check_definition(data):
472
+ return make_json_response(
473
+ status=410,
474
+ success=0,
475
+ errormsg=gettext(
476
+ "Definition incomplete. Please provide Locale OR Copy "
477
+ "Collation OR LC_TYPE/LC_COLLATE."
478
+ )
479
+ )
480
+
481
+ SQL = render_template(
482
+ "/".join([self.template_path, self._CREATE_SQL]),
483
+ data=data, conn=self.conn
484
+ )
485
+ status, res = self.conn.execute_scalar(SQL)
486
+ if not status:
487
+ return internal_server_error(errormsg=res)
488
+
489
+ # We need oid to add object in tree at browser
490
+ SQL = render_template(
491
+ "/".join([self.template_path, self._OID_SQL]), data=data,
492
+ conn=self.conn
493
+ )
494
+ status, coid = self.conn.execute_scalar(SQL)
495
+ if not status:
496
+ return internal_server_error(errormsg=coid)
497
+
498
+ # Get updated schema oid
499
+ SQL = render_template(
500
+ "/".join([self.template_path, self._OID_SQL]), coid=coid,
501
+ conn=self.conn
502
+ )
503
+
504
+ status, new_scid = self.conn.execute_scalar(SQL)
505
+ if not status:
506
+ return internal_server_error(errormsg=coid)
507
+
508
+ return jsonify(
509
+ node=self.blueprint.generate_browser_node(
510
+ coid,
511
+ new_scid,
512
+ data['name'],
513
+ icon="icon-collation"
514
+ )
515
+ )
516
+
517
+ @check_precondition
518
+ def delete(self, gid, sid, did, scid, coid=None, only_sql=False):
519
+ """
520
+ This function will delete the existing collation object
521
+
522
+ Args:
523
+ gid: Server Group ID
524
+ sid: Server ID
525
+ did: Database ID
526
+ scid: Schema ID
527
+ coid: Collation ID
528
+ only_sql: Return only sql if True
529
+ """
530
+ data = json.loads(request.data) if coid is None \
531
+ else {'ids': [coid]}
532
+
533
+ # Below will decide if it's simple drop or drop with cascade call
534
+
535
+ cascade = self._check_cascade_operation()
536
+
537
+ try:
538
+ for coid in data['ids']:
539
+ SQL = render_template("/".join([self.template_path,
540
+ 'get_name.sql']),
541
+ scid=scid, coid=coid)
542
+ status, res = self.conn.execute_dict(SQL)
543
+ if not status:
544
+ return internal_server_error(errormsg=res)
545
+
546
+ if len(res['rows']) == 0:
547
+ return gone(self.not_found_error_msg())
548
+
549
+ data = res['rows'][0]
550
+
551
+ SQL = render_template("/".join([self.template_path,
552
+ self._DELETE_SQL]),
553
+ name=data['name'],
554
+ nspname=data['schema'],
555
+ cascade=cascade,
556
+ conn=self.conn)
557
+
558
+ # Used for schema diff tool
559
+ if only_sql:
560
+ return SQL
561
+
562
+ status, res = self.conn.execute_scalar(SQL)
563
+ if not status:
564
+ return internal_server_error(errormsg=res)
565
+
566
+ return make_json_response(
567
+ success=1,
568
+ info=gettext("Collation dropped")
569
+ )
570
+
571
+ except Exception as e:
572
+ return internal_server_error(errormsg=str(e))
573
+
574
+ @check_precondition
575
+ def update(self, gid, sid, did, scid, coid):
576
+ """
577
+ This function will updates the existing collation object
578
+
579
+ Args:
580
+ gid: Server Group ID
581
+ sid: Server ID
582
+ did: Database ID
583
+ scid: Schema ID
584
+ coid: Collation ID
585
+ """
586
+ data = request.form if request.form else json.loads(
587
+ request.data
588
+ )
589
+ SQL, name = self.get_sql(gid, sid, data, scid, coid)
590
+ # Most probably this is due to error
591
+ if not isinstance(SQL, str):
592
+ return SQL
593
+ SQL = SQL.strip('\n').strip(' ')
594
+ status, res = self.conn.execute_scalar(SQL)
595
+
596
+ if not status:
597
+ return internal_server_error(errormsg=res)
598
+
599
+ # We need oid to add object in tree at browser
600
+ SQL = render_template("/".join([self.template_path,
601
+ self._OID_SQL]), coid=coid)
602
+
603
+ status, res = self.conn.execute_2darray(SQL)
604
+ if not status:
605
+ return internal_server_error(errormsg=res)
606
+
607
+ scid = res['rows'][0]['scid']
608
+
609
+ other_node_info = {}
610
+ if 'description' in data:
611
+ other_node_info['description'] = data['description']
612
+
613
+ return jsonify(
614
+ node=self.blueprint.generate_browser_node(
615
+ coid,
616
+ scid,
617
+ name,
618
+ icon="icon-%s" % self.node_type,
619
+ **other_node_info
620
+ )
621
+ )
622
+
623
+ @check_precondition
624
+ def msql(self, gid, sid, did, scid, coid=None):
625
+ """
626
+ This function will generates modified sql for collation object
627
+
628
+ Args:
629
+ gid: Server Group ID
630
+ sid: Server ID
631
+ did: Database ID
632
+ scid: Schema ID
633
+ coid: Collation ID
634
+ """
635
+ data = dict()
636
+ for k, v in request.args.items():
637
+ try:
638
+ # comments should be taken as is because if user enters a
639
+ # json comment it is parsed by loads which should not happen
640
+ if k in ('description',):
641
+ data[k] = v
642
+ else:
643
+ data[k] = json.loads(v)
644
+ except ValueError:
645
+ data[k] = v
646
+
647
+ try:
648
+ SQL, _ = self.get_sql(gid, sid, data, scid, coid)
649
+ # Most probably this is due to error
650
+ if not isinstance(SQL, str):
651
+ return SQL
652
+ if SQL == '':
653
+ SQL = "--modified SQL"
654
+
655
+ return make_json_response(
656
+ data=SQL,
657
+ status=200
658
+ )
659
+ except Exception as e:
660
+ return internal_server_error(errormsg=str(e))
661
+
662
+ def get_sql(self, gid, sid, data, scid, coid=None):
663
+ """
664
+ This function will genrate sql from model data
665
+ """
666
+ if coid is not None:
667
+ SQL = render_template("/".join([self.template_path,
668
+ self._PROPERTIES_SQL]),
669
+ scid=scid, coid=coid)
670
+ status, res = self.conn.execute_dict(SQL)
671
+ if not status:
672
+ return internal_server_error(errormsg=res)
673
+ if len(res['rows']) == 0:
674
+ return gone(self.not_found_error_msg())
675
+
676
+ old_data = res['rows'][0]
677
+ SQL = render_template(
678
+ "/".join([self.template_path, self._UPDATE_SQL]),
679
+ data=data, o_data=old_data, conn=self.conn
680
+ )
681
+ return SQL.strip('\n'), data['name'] if 'name' in data else \
682
+ old_data['name']
683
+ else:
684
+ required_args = [
685
+ 'name'
686
+ ]
687
+
688
+ for arg in required_args:
689
+ if arg not in data:
690
+ return gettext("-- missing definition")
691
+
692
+ if self._check_definition(data):
693
+ return gettext("-- missing definition")
694
+
695
+ SQL = render_template("/".join([self.template_path,
696
+ self._CREATE_SQL]),
697
+ data=data, conn=self.conn)
698
+ return SQL.strip('\n'), data['name']
699
+
700
+ @check_precondition
701
+ def sql(self, gid, sid, did, scid, coid, **kwargs):
702
+ """
703
+ This function will generates reverse engineered sql for collation
704
+ object
705
+
706
+ Args:
707
+ gid: Server Group ID
708
+ sid: Server ID
709
+ did: Database ID
710
+ scid: Schema ID
711
+ coid: Collation ID
712
+ json_resp: True then return json response
713
+ """
714
+ json_resp = kwargs.get('json_resp', True)
715
+ target_schema = kwargs.get('target_schema', None)
716
+
717
+ SQL = render_template("/".join([self.template_path,
718
+ self._PROPERTIES_SQL]),
719
+ scid=scid, coid=coid)
720
+ status, res = self.conn.execute_dict(SQL)
721
+ if not status:
722
+ return internal_server_error(errormsg=res)
723
+ if len(res['rows']) == 0:
724
+ return gone(self.not_found_error_msg())
725
+
726
+ data = res['rows'][0]
727
+ if target_schema:
728
+ data['schema'] = target_schema
729
+
730
+ SQL = render_template("/".join([self.template_path,
731
+ self._CREATE_SQL]),
732
+ data=data, conn=self.conn,
733
+ add_not_exists_clause=True
734
+ )
735
+
736
+ sql_header = "-- Collation: {0};\n\n-- ".format(data['name'])
737
+
738
+ sql_header += render_template("/".join([self.template_path,
739
+ self._DELETE_SQL]),
740
+ name=data['name'],
741
+ nspname=data['schema'])
742
+ SQL = sql_header + '\n\n' + SQL.strip('\n')
743
+
744
+ if not json_resp:
745
+ return SQL
746
+
747
+ return ajax_response(response=SQL)
748
+
749
+ @check_precondition
750
+ def dependents(self, gid, sid, did, scid, coid):
751
+ """
752
+ This function get the dependents and return ajax response
753
+ for the Collation node.
754
+
755
+ Args:
756
+ gid: Server Group ID
757
+ sid: Server ID
758
+ did: Database ID
759
+ scid: Schema ID
760
+ coid: Collation ID
761
+ """
762
+ dependents_result = self.get_dependents(
763
+ self.conn, coid
764
+ )
765
+
766
+ return ajax_response(
767
+ response=dependents_result,
768
+ status=200
769
+ )
770
+
771
+ @check_precondition
772
+ def dependencies(self, gid, sid, did, scid, coid):
773
+ """
774
+ This function get the dependencies and return ajax response
775
+ for the Collation node.
776
+
777
+ Args:
778
+ gid: Server Group ID
779
+ sid: Server ID
780
+ did: Database ID
781
+ scid: Schema ID
782
+ coid: Collation ID
783
+ """
784
+ dependencies_result = self.get_dependencies(
785
+ self.conn, coid
786
+ )
787
+
788
+ return ajax_response(
789
+ response=dependencies_result,
790
+ status=200
791
+ )
792
+
793
+ @check_precondition
794
+ def fetch_objects_to_compare(self, sid, did, scid):
795
+ """
796
+ This function will fetch the list of all the collations for
797
+ specified schema id.
798
+
799
+ :param sid: Server Id
800
+ :param did: Database Id
801
+ :param scid: Schema Id
802
+ :return:
803
+ """
804
+ res = dict()
805
+ SQL = render_template("/".join([self.template_path,
806
+ self._NODES_SQL]), scid=scid,
807
+ schema_diff=True)
808
+ status, rset = self.conn.execute_2darray(SQL)
809
+ if not status:
810
+ return internal_server_error(errormsg=res)
811
+
812
+ for row in rset['rows']:
813
+ status, data = self._fetch_properties(scid, row['oid'])
814
+ if status:
815
+ res[row['name']] = data
816
+
817
+ return res
818
+
819
+ def get_sql_from_diff(self, **kwargs):
820
+ """
821
+ This function is used to get the DDL/DML statements.
822
+ :param kwargs
823
+ :return:
824
+ """
825
+ gid = kwargs.get('gid')
826
+ sid = kwargs.get('sid')
827
+ did = kwargs.get('did')
828
+ scid = kwargs.get('scid')
829
+ oid = kwargs.get('oid')
830
+ data = kwargs.get('data', None)
831
+ drop_sql = kwargs.get('drop_sql', False)
832
+ target_schema = kwargs.get('target_schema', None)
833
+
834
+ if data:
835
+ if target_schema:
836
+ data['schema'] = target_schema
837
+ sql, _ = self.get_sql(gid=gid, sid=sid, data=data, scid=scid,
838
+ coid=oid)
839
+ else:
840
+ if drop_sql:
841
+ sql = self.delete(gid=gid, sid=sid, did=did,
842
+ scid=scid, coid=oid, only_sql=True)
843
+ elif target_schema:
844
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, coid=oid,
845
+ target_schema=target_schema, json_resp=False)
846
+ else:
847
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, coid=oid,
848
+ json_resp=False)
849
+ return sql
850
+
851
+
852
+ SchemaDiffRegistry(blueprint.node_type, CollationView)
853
+ CollationView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/create.sql ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% if data %}
2
+ CREATE COLLATION{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
3
+ {% if not data.copy_collation %}
4
+ {% set options = [] %}
5
+ {# if user has provided lc_collate & lc_type #}
6
+ {% if data.lc_collate and data.lc_type %}
7
+ {% if data.lc_collate and data.lc_type %}
8
+ {% set options = options + ['LC_COLLATE = ' ~ data.lc_collate|qtLiteral(conn), 'LC_CTYPE = ' ~ data.lc_type|qtLiteral(conn)] %}
9
+ {% endif %}
10
+ {% if data.provider %}
11
+ {% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
12
+ {% endif %}
13
+ {% if data.is_deterministic is defined %}
14
+ {% set options = options + ['DETERMINISTIC = ' ~ data.is_deterministic|qtLiteral(conn)] %}
15
+ {% endif %}
16
+ {% if data.rules %}
17
+ {% set options = options + ['RULES = ' ~ data.rules|qtLiteral(conn)] %}
18
+ {% endif %}
19
+ {% if data.version %}
20
+ {% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
21
+ {% endif %}
22
+ {% endif %}
23
+ {# if user has provided locale only #}
24
+ {% if data.locale %}
25
+ {% if data.locale %}
26
+ {% set options = options + ['LOCALE = ' ~ data.locale|qtLiteral(conn)] %}
27
+ {% endif %}
28
+ {% if data.provider %}
29
+ {% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
30
+ {% endif %}
31
+ {% if data.is_deterministic is defined %}
32
+ {% set options = options + ['DETERMINISTIC = ' ~ data.is_deterministic|qtLiteral(conn)] %}
33
+ {% endif %}
34
+ {% if data.rules %}
35
+ {% set options = options + ['RULES = ' ~ data.rules|qtLiteral(conn)] %}
36
+ {% endif %}
37
+ {% if data.version %}
38
+ {% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
39
+ {% endif %}
40
+ {% endif %}
41
+ {% if options %}
42
+ ({{ options|join(', ') }});
43
+ {% endif %}
44
+ {% endif %}
45
+ {# if user has choosed to copy from existing collation #}
46
+ {% if data.copy_collation %}
47
+ FROM {{ data.copy_collation }};
48
+ {% endif %}
49
+ {% if data.owner %}
50
+
51
+ ALTER COLLATION {{ conn|qtIdent(data.schema, data.name) }}
52
+ OWNER TO {{ conn|qtIdent(data.owner) }};
53
+ {% endif %}
54
+ {% if data.description %}
55
+
56
+ COMMENT ON COLLATION {{ conn|qtIdent(data.schema, data.name) }}
57
+ IS {{ data.description|qtLiteral(conn) }};
58
+ {% endif %}
59
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/properties.sql ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT c.oid, c.collname AS name, c.collcollate AS lc_collate, c.collctype AS lc_type,
2
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, c.collisdeterministic AS is_deterministic, c.collversion AS version,
3
+ c.collprovider AS provider, des.description, n.nspname AS schema
4
+
5
+ FROM pg_catalog.pg_collation c
6
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
7
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
8
+ WHERE c.collnamespace = {{scid}}::oid
9
+ {% if coid %} AND c.oid = {{coid}}::oid {% endif %}
10
+ ORDER BY c.collname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/15_plus/properties.sql ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT c.oid, c.collname AS name, COALESCE(c.collcollate, c.colliculocale) AS lc_collate,
2
+ COALESCE(c.collctype, c.colliculocale) AS lc_type, c.collisdeterministic AS is_deterministic, c.collversion AS version,
3
+ c.collprovider AS provider,
4
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, description, n.nspname AS schema
5
+ FROM pg_catalog.pg_collation c
6
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
7
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
8
+ WHERE c.collnamespace = {{scid}}::oid
9
+ {% if coid %} AND c.oid = {{coid}}::oid {% endif %}
10
+ ORDER BY c.collname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/16_plus/properties.sql ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT c.oid, c.collname AS name, COALESCE(c.collcollate, c.colliculocale) AS lc_collate,
2
+ COALESCE(c.collctype, c.colliculocale) AS lc_type, c.collisdeterministic AS is_deterministic, c.collversion AS version,
3
+ c.collprovider AS provider, c.collicurules AS rules,
4
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, description, n.nspname AS schema
5
+ FROM pg_catalog.pg_collation c
6
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
7
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
8
+ WHERE c.collnamespace = {{scid}}::oid
9
+ {% if coid %} AND c.oid = {{coid}}::oid {% endif %}
10
+ ORDER BY c.collname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/backend_support.sql ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ CASE WHEN nsp.nspname IN ('sys', 'information_schema') THEN true ELSE false END AS dbSupport
3
+ FROM pg_catalog.pg_namespace nsp
4
+ WHERE nsp.oid={{scid}}::oid
5
+ AND (
6
+ (nspname = 'pg_catalog' AND EXISTS
7
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1))
8
+ OR (nspname = 'pgagent' AND EXISTS
9
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1))
10
+ OR (nspname = 'information_schema' AND EXISTS
11
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1))
12
+ OR (nspname LIKE '_%' AND EXISTS
13
+ (SELECT 1 FROM pg_catalog.pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1))
14
+ )
15
+ AND
16
+ nspname NOT LIKE E'pg\\temp\\%'
17
+ AND
18
+ nspname NOT LIKE E'pg\\toast_temp\\%'
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/count.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ SELECT COUNT(*)
2
+ FROM pg_catalog.pg_collation c
3
+ {% if scid %}
4
+ WHERE c.collnamespace = {{scid}}::oid
5
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/create.sql ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% if data %}
2
+ CREATE COLLATION{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
3
+ {% if not data.copy_collation %}
4
+ {% set options = [] %}
5
+ {# if user has provided lc_collate & lc_type #}
6
+ {% if data.lc_collate and data.lc_type %}
7
+ {% if data.lc_collate and data.lc_type %}
8
+ {% set options = options + ['LC_COLLATE = ' ~ data.lc_collate|qtLiteral(conn), 'LC_CTYPE = ' ~ data.lc_type|qtLiteral(conn)] %}
9
+ {% endif %}
10
+ {% if data.provider %}
11
+ {% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
12
+ {% endif %}
13
+ {% if data.version %}
14
+ {% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
15
+ {% endif %}
16
+ {% endif %}
17
+ {# if user has provided locale only #}
18
+ {% if data.locale %}
19
+ {% if data.locale %}
20
+ {% set options = options + ['LOCALE = ' ~ data.locale|qtLiteral(conn)] %}
21
+ {% endif %}
22
+ {% if data.provider %}
23
+ {% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
24
+ {% endif %}
25
+ {% if data.version %}
26
+ {% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
27
+ {% endif %}
28
+ {% endif %}
29
+ {% if options %}
30
+ ({{ options|join(', ') }});
31
+ {% endif %}
32
+ {% endif %}
33
+ {# if user has choosed to copy from existing collation #}
34
+ {% if data.copy_collation %}
35
+ FROM {{ data.copy_collation }};
36
+ {% endif %}
37
+ {% if data.owner %}
38
+
39
+ ALTER COLLATION {{ conn|qtIdent(data.schema, data.name) }}
40
+ OWNER TO {{ conn|qtIdent(data.owner) }};
41
+ {% endif %}
42
+ {% if data.description %}
43
+
44
+ COMMENT ON COLLATION {{ conn|qtIdent(data.schema, data.name) }}
45
+ IS {{ data.description|qtLiteral(conn) }};
46
+ {% endif %}
47
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/delete.sql ADDED
@@ -0,0 +1 @@
 
 
1
+ DROP COLLATION IF EXISTS {{ conn|qtIdent(nspname, name) }}{% if cascade%} CASCADE{% endif %};
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_collations.sql ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ SELECT --nspname, collname,
2
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
3
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
4
+ ELSE '' END AS copy_collation
5
+ FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
6
+ WHERE c.collnamespace=n.oid
7
+ ORDER BY nspname, collname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_name.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ SELECT nspname AS schema, collname AS name
2
+ FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
3
+ WHERE c.collnamespace = n.oid AND
4
+ n.oid = {{ scid }}::oid AND
5
+ c.oid = {{ coid }}::oid;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/__init__.py ADDED
@@ -0,0 +1,1030 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """Implements the Domain Node."""
11
+
12
+ from functools import wraps
13
+
14
+ import json
15
+ from flask import render_template, make_response, request, jsonify
16
+ from flask_babel import gettext
17
+
18
+ from pgadmin.browser.server_groups.servers import databases
19
+ from config import PG_DEFAULT_DRIVER
20
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
21
+ SchemaChildModule, DataTypeReader
22
+ from pgadmin.browser.server_groups.servers.databases.utils import \
23
+ parse_sec_labels_from_db
24
+ from pgadmin.browser.utils import PGChildNodeView
25
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
26
+ make_response as ajax_response, gone
27
+ from pgadmin.utils.compile_template_name import compile_template_path
28
+ from pgadmin.utils.driver import get_driver
29
+ from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
30
+ from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
31
+
32
+
33
+ class DomainModule(SchemaChildModule):
34
+ """
35
+ class DomainModule(SchemaChildModule):
36
+
37
+ This class represents The Domain Module.
38
+
39
+ Methods:
40
+ -------
41
+ * __init__(*args, **kwargs)
42
+ - Initialize the Domain Module.
43
+
44
+ * get_nodes(gid, sid, did, scid)
45
+ - Generate the domain collection node.
46
+
47
+ * script_load()
48
+ - Load the module script for domain, when schema node is
49
+ initialized.
50
+ """
51
+
52
+ _NODE_TYPE = 'domain'
53
+ _COLLECTION_LABEL = gettext("Domains")
54
+
55
+ def __init__(self, *args, **kwargs):
56
+ super().__init__(*args, **kwargs)
57
+ self.min_ver = None
58
+ self.max_ver = None
59
+
60
+ def get_nodes(self, gid, sid, did, scid):
61
+ """
62
+ Generate the domain collection node.
63
+ """
64
+ if self.has_nodes(sid, did, scid=scid,
65
+ base_template_path=DomainView.BASE_TEMPLATE_PATH):
66
+ yield self.generate_browser_collection_node(scid)
67
+
68
+ @property
69
+ def script_load(self):
70
+ """
71
+ Load the module script for domain, when schema node is
72
+ initialized.
73
+ """
74
+ return databases.DatabaseModule.node_type
75
+
76
+ def register(self, app, options):
77
+ """
78
+ Override the default register function to automagically register
79
+ sub-modules at once.
80
+ """
81
+ from .domain_constraints import blueprint as module
82
+ self.submodules.append(module)
83
+ super().register(app, options)
84
+
85
+
86
+ blueprint = DomainModule(__name__)
87
+
88
+
89
+ class DomainView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
90
+ """
91
+ class DomainView
92
+
93
+ This class inherits PGChildNodeView to get the different routes for
94
+ the module. Also, inherits DataTypeReader to get data types.
95
+
96
+ The class is responsible to Create, Read, Update and Delete operations for
97
+ the Domain.
98
+
99
+ Methods:
100
+ -------
101
+ * validate_request(f):
102
+ - Works as a decorator.
103
+ Validating request on the request of create, update and modified SQL.
104
+
105
+ * check_precondition(f):
106
+ - Works as a decorator.
107
+ - Checks database connection status.
108
+ - Attach connection object and template path.
109
+
110
+ * list(gid, sid, did, scid, doid):
111
+ - List the Domains.
112
+
113
+ * nodes(gid, sid, did, scid):
114
+ - Returns all the Domains to generate Nodes in the browser.
115
+
116
+ * properties(gid, sid, did, scid, doid):
117
+ - Returns the Domain properties.
118
+
119
+ * get_collations(gid, sid, did, scid, doid=None):
120
+ - Returns Collations.
121
+
122
+ * create(gid, sid, did, scid):
123
+ - Creates a new Domain object.
124
+
125
+ * update(gid, sid, did, scid, doid):
126
+ - Updates the Domain object.
127
+
128
+ * delete(gid, sid, did, scid, doid):
129
+ - Drops the Domain object.
130
+
131
+ * sql(gid, sid, did, scid, doid=None):
132
+ - Returns the SQL for the Domain object.
133
+
134
+ * msql(gid, sid, did, scid, doid=None):
135
+ - Returns the modified SQL.
136
+
137
+ * get_sql(gid, sid, data, scid, doid=None):
138
+ - Generates the SQL statements to create/update the Domain object.
139
+
140
+ * dependents(gid, sid, did, scid, doid):
141
+ - Returns the dependents for the Domain object.
142
+
143
+ * dependencies(gid, sid, did, scid, doid):
144
+ - Returns the dependencies for the Domain object.
145
+
146
+ * types(gid, sid, did, scid, fnid=None):
147
+ - Returns Data Types.
148
+
149
+ * compare(**kwargs):
150
+ - This function will compare the domain nodes from two different
151
+ schemas.
152
+ """
153
+
154
+ node_type = blueprint.node_type
155
+ node_label = "Domain"
156
+ BASE_TEMPLATE_PATH = 'domains/sql/#{0}#'
157
+
158
+ parent_ids = [
159
+ {'type': 'int', 'id': 'gid'},
160
+ {'type': 'int', 'id': 'sid'},
161
+ {'type': 'int', 'id': 'did'},
162
+ {'type': 'int', 'id': 'scid'}
163
+ ]
164
+ ids = [
165
+ {'type': 'int', 'id': 'doid'}
166
+ ]
167
+
168
+ operations = dict({
169
+ 'obj': [
170
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
171
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
172
+ ],
173
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
174
+ 'children': [{'get': 'children'}],
175
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
176
+ 'sql': [{'get': 'sql'}],
177
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
178
+ 'stats': [{'get': 'statistics'}],
179
+ 'dependency': [{'get': 'dependencies'}],
180
+ 'dependent': [{'get': 'dependents'}],
181
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
182
+ 'get_collations': [
183
+ {'get': 'get_collations'},
184
+ {'get': 'get_collations'}
185
+ ],
186
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
187
+ })
188
+
189
+ keys_to_ignore = ['oid', 'basensp', 'conoid', 'nspname', 'oid-2']
190
+
191
+ @staticmethod
192
+ def _get_req_data(kwargs):
193
+ """
194
+ Get req data from request.
195
+ :param kwargs: kwargs.
196
+ :return: if any error return error, else return req.
197
+ """
198
+ if request.data:
199
+ req = json.loads(request.data)
200
+ else:
201
+ req = request.args or request.form
202
+
203
+ if 'doid' not in kwargs:
204
+ required_args = [
205
+ 'name',
206
+ 'basetype'
207
+ ]
208
+
209
+ for arg in required_args:
210
+ if arg not in req or req[arg] == '':
211
+ return req, True, make_json_response(
212
+ status=410,
213
+ success=0,
214
+ errormsg=gettext(
215
+ "Could not find the required parameter ({})."
216
+ ).format(arg),
217
+ )
218
+ return req, False, ''
219
+
220
+ @staticmethod
221
+ def _get_data(req):
222
+ """
223
+ Get data from request and update required values.
224
+ :param req: request object.
225
+ :return: data.
226
+ """
227
+ data = {}
228
+ list_params = []
229
+ if request.method == 'GET':
230
+ list_params = ['constraints', 'seclabels']
231
+
232
+ for key in req:
233
+ if (
234
+ key in list_params and req[key] != '' and
235
+ req[key] is not None
236
+ ):
237
+ # Coverts string into python list as expected.
238
+ data[key] = json.loads(req[key])
239
+ elif key == 'typnotnull':
240
+ if req[key] == 'true' or req[key] is True:
241
+ data[key] = True
242
+ elif req[key] == 'false' or req[key] is False:
243
+ data[key] = False
244
+ else:
245
+ data[key] = ''
246
+ else:
247
+ data[key] = req[key]
248
+ return data
249
+
250
+ def validate_request(f):
251
+ """
252
+ Works as a decorator.
253
+ Validating request on the request of create, update and modified SQL.
254
+
255
+ Required Args:
256
+ name: Name of the Domain
257
+ owner: Domain Owner
258
+ basensp: Schema Name
259
+ basetype: Data Type of the Domain
260
+
261
+ Above both the arguments will not be validated in the update action.
262
+ """
263
+
264
+ @wraps(f)
265
+ def wrap(self, **kwargs):
266
+
267
+ req, is_error, errmsg = DomainView._get_req_data(kwargs)
268
+ if is_error:
269
+ return errmsg
270
+
271
+ try:
272
+ data = DomainView._get_data(req)
273
+
274
+ except Exception as e:
275
+ return internal_server_error(errormsg=str(e))
276
+
277
+ self.request = data
278
+ return f(self, **kwargs)
279
+
280
+ return wrap
281
+
282
+ def check_precondition(f):
283
+ """
284
+ Works as a decorator.
285
+ Checks database connection status.
286
+ Attach connection object and template path.
287
+ """
288
+
289
+ @wraps(f)
290
+ def wrap(*args, **kwargs):
291
+ self = args[0]
292
+ driver = get_driver(PG_DEFAULT_DRIVER)
293
+ self.manager = driver.connection_manager(kwargs['sid'])
294
+ # Get database connection
295
+ self.conn = self.manager.connection(did=kwargs['did'])
296
+ self.qtIdent = driver.qtIdent
297
+ self.datistemplate = False
298
+ if (
299
+ self.manager.db_info is not None and
300
+ kwargs['did'] in self.manager.db_info and
301
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
302
+ ):
303
+ self.datistemplate = self.manager.db_info[
304
+ kwargs['did']]['datistemplate']
305
+
306
+ # we will set template path for sql scripts
307
+ self.template_path = \
308
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
309
+
310
+ return f(*args, **kwargs)
311
+
312
+ return wrap
313
+
314
+ @check_precondition
315
+ def list(self, gid, sid, did, scid):
316
+ """
317
+ List the Domains.
318
+
319
+ Args:
320
+ gid: Server Group Id
321
+ sid: Server Id
322
+ did: Database Id
323
+ scid: Schema Id
324
+ """
325
+
326
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
327
+ scid=scid)
328
+ status, res = self.conn.execute_dict(SQL)
329
+
330
+ if not status:
331
+ return internal_server_error(errormsg=res)
332
+ return ajax_response(
333
+ response=res['rows'],
334
+ status=200
335
+ )
336
+
337
+ @check_precondition
338
+ def nodes(self, gid, sid, did, scid):
339
+ """
340
+ Returns all the Domains to generate Nodes in the browser.
341
+
342
+ Args:
343
+ gid: Server Group Id
344
+ sid: Server Id
345
+ did: Database Id
346
+ scid: Schema Id
347
+ """
348
+
349
+ res = []
350
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
351
+ scid=scid)
352
+ status, rset = self.conn.execute_2darray(SQL)
353
+ if not status:
354
+ return internal_server_error(errormsg=rset)
355
+
356
+ for row in rset['rows']:
357
+ res.append(
358
+ self.blueprint.generate_browser_node(
359
+ row['oid'],
360
+ scid,
361
+ row['name'],
362
+ icon="icon-domain",
363
+ description=row['description']
364
+ ))
365
+
366
+ return make_json_response(
367
+ data=res,
368
+ status=200
369
+ )
370
+
371
+ @check_precondition
372
+ def node(self, gid, sid, did, scid, doid):
373
+ """
374
+ This function will fetch the properties of the domain node.
375
+
376
+ Args:
377
+ gid: Server Group Id
378
+ sid: Server Id
379
+ did: Database Id
380
+ scid: Schema Id
381
+ doid: Domain Id
382
+ """
383
+
384
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
385
+ doid=doid)
386
+ status, rset = self.conn.execute_2darray(SQL)
387
+ if not status:
388
+ return internal_server_error(errormsg=rset)
389
+
390
+ for row in rset['rows']:
391
+ return make_json_response(
392
+ data=self.blueprint.generate_browser_node(
393
+ row['oid'],
394
+ scid,
395
+ row['name'],
396
+ icon="icon-domain"
397
+ ),
398
+ status=200
399
+ )
400
+
401
+ return gone(self.not_found_error_msg())
402
+
403
+ @check_precondition
404
+ def properties(self, gid, sid, did, scid, doid):
405
+ """
406
+ Returns the Domain properties.
407
+
408
+ Args:
409
+ gid: Server Group Id
410
+ sid: Server Id
411
+ did: Database Id
412
+ scid: Schema Id
413
+ doid: Domain Id
414
+ """
415
+ status, res = self._fetch_properties(did, scid, doid)
416
+ if not status:
417
+ return res
418
+
419
+ return ajax_response(
420
+ response=res,
421
+ status=200
422
+ )
423
+
424
+ def _fetch_properties(self, did, scid, doid):
425
+ """
426
+ This function is used to fecth the properties of specified object.
427
+ :param did:
428
+ :param scid:
429
+ :param doid:
430
+ :return:
431
+ """
432
+ SQL = render_template("/".join([self.template_path,
433
+ self._PROPERTIES_SQL]),
434
+ scid=scid, doid=doid)
435
+ status, res = self.conn.execute_dict(SQL)
436
+ if not status:
437
+ return False, internal_server_error(errormsg=res)
438
+
439
+ if len(res['rows']) == 0:
440
+ return False, gone(gettext("""
441
+ Could not find the domain in the database.
442
+ It may have been removed by another user or moved to another schema.
443
+ """))
444
+
445
+ data = res['rows'][0]
446
+
447
+ # Get Type Length and Precision
448
+ data.update(self._parse_type(data['fulltype']))
449
+
450
+ # Get Domain Constraints
451
+ SQL = render_template("/".join([self.template_path,
452
+ self._GET_CONSTRAINTS_SQL]),
453
+ doid=doid)
454
+ status, res = self.conn.execute_dict(SQL)
455
+ if not status:
456
+ return False, internal_server_error(errormsg=res)
457
+
458
+ data['constraints'] = res['rows']
459
+
460
+ # Get formatted Security Labels
461
+ if 'seclabels' in data:
462
+ data.update(parse_sec_labels_from_db(data['seclabels']))
463
+
464
+ # Set System Domain Status
465
+ data['sysdomain'] = False
466
+ if doid <= self._DATABASE_LAST_SYSTEM_OID or \
467
+ self.datistemplate:
468
+ data['sysdomain'] = True
469
+
470
+ return True, data
471
+
472
+ def _parse_type(self, basetype):
473
+ """
474
+ Returns Type and Data Type from the basetype.
475
+ """
476
+ typ_len = ''
477
+ typ_precision = ''
478
+
479
+ # The Length and the precision of the Datatype should be separate.
480
+ # The Format we getting from database is: numeric(1,1)
481
+ # So, we need to separate Length: 1, Precision: 1
482
+
483
+ if basetype != '' and basetype.find("(") > 0:
484
+ substr = basetype[basetype.find("(") + 1:len(
485
+ basetype) - 1]
486
+ typlen = substr.split(",")
487
+ typ_len = typlen[0]
488
+ if len(typlen) > 1:
489
+ typ_precision = typlen[1]
490
+ else:
491
+ typ_precision = ''
492
+
493
+ return {'typlen': typ_len, 'precision': typ_precision}
494
+
495
+ @check_precondition
496
+ def get_collations(self, gid, sid, did, scid, doid=None):
497
+ """
498
+ Returns Collations.
499
+
500
+ Args:
501
+ gid: Server Group Id
502
+ sid: Server Id
503
+ did: Database Id
504
+ scid: Schema Id
505
+ doid: Domain Id
506
+ """
507
+
508
+ res = [{'label': '', 'value': ''}]
509
+ try:
510
+ SQL = render_template("/".join([self.template_path,
511
+ 'get_collations.sql']))
512
+ status, rset = self.conn.execute_2darray(SQL)
513
+ if not status:
514
+ return internal_server_error(errormsg=rset)
515
+
516
+ for row in rset['rows']:
517
+ res.append({'label': row['copy_collation'],
518
+ 'value': row['copy_collation']}
519
+ )
520
+
521
+ return make_json_response(
522
+ data=res,
523
+ status=200
524
+ )
525
+
526
+ except Exception as e:
527
+ return internal_server_error(errormsg=str(e))
528
+
529
+ @check_precondition
530
+ def types(self, gid, sid, did, scid, doid=None):
531
+ """
532
+ Returns the Data Types.
533
+
534
+ Args:
535
+ gid: Server Group Id
536
+ sid: Server Id
537
+ did: Database Id
538
+ scid: Schema Id
539
+ fnid: Function Id
540
+ """
541
+
542
+ condition = """typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r')
543
+ AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class
544
+ WHERE relnamespace=typnamespace AND relname = typname AND relkind != 'c') AND
545
+ (typname NOT LIKE '_%' OR NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class WHERE
546
+ relnamespace=typnamespace AND relname = substring(typname FROM 2)::name
547
+ AND relkind != 'c'))"""
548
+
549
+ # To show hidden objects
550
+ if not self.blueprint.show_system_objects:
551
+ condition += " AND nsp.nspname != 'information_schema'"
552
+
553
+ # Get Types
554
+ status, types = self.get_types(self.conn, condition)
555
+
556
+ if not status:
557
+ return internal_server_error(errormsg=types)
558
+
559
+ return make_json_response(
560
+ data=types,
561
+ status=200
562
+ )
563
+
564
+ @check_precondition
565
+ @validate_request
566
+ def create(self, gid, sid, did, scid):
567
+ """
568
+ Creates a new Domain object.
569
+
570
+ Args:
571
+ gid: Server Group Id
572
+ sid: Server Id
573
+ did: Database Id
574
+ scid: Schema Id
575
+ doid: Domain Id
576
+
577
+ Required Args:
578
+ name: Domain Name
579
+ owner: Owner Name
580
+ basensp: Schema Name
581
+ basetype: Domain Base Type
582
+
583
+ Returns:
584
+ Domain object in json format.
585
+ """
586
+
587
+ data = self.request
588
+ SQL, _ = self.get_sql(gid, sid, data, scid)
589
+ # Most probably this is due to error
590
+ if not isinstance(SQL, str):
591
+ return SQL
592
+
593
+ status, res = self.conn.execute_scalar(SQL)
594
+ if not status:
595
+ return internal_server_error(errormsg=res)
596
+
597
+ # We need oid to add object in tree at browser, below sql will
598
+ # gives the same
599
+ SQL = render_template("/".join([self.template_path,
600
+ self._OID_SQL]),
601
+ basensp=data['basensp'],
602
+ name=data['name'],
603
+ conn=self.conn)
604
+ status, doid = self.conn.execute_scalar(SQL)
605
+ if not status:
606
+ return internal_server_error(errormsg=doid)
607
+
608
+ # Get updated schema oid
609
+ SQL = render_template("/".join([self.template_path,
610
+ self._OID_SQL]),
611
+ doid=doid,
612
+ conn=self.conn)
613
+ status, scid = self.conn.execute_scalar(SQL)
614
+ if not status:
615
+ return internal_server_error(errormsg=scid)
616
+
617
+ return jsonify(
618
+ node=self.blueprint.generate_browser_node(
619
+ doid,
620
+ scid,
621
+ data['name'],
622
+ icon="icon-domain"
623
+ )
624
+ )
625
+
626
+ @check_precondition
627
+ def delete(self, gid, sid, did, scid, doid=None, only_sql=False):
628
+ """
629
+ Drops the Domain object.
630
+
631
+ Args:
632
+ gid: Server Group Id
633
+ sid: Server Id
634
+ did: Database Id
635
+ scid: Schema Id
636
+ doid: Domain Id
637
+ only_sql: Return only sql if True
638
+ """
639
+ if doid is None:
640
+ data = request.form if request.form else json.loads(
641
+ request.data
642
+ )
643
+ else:
644
+ data = {'ids': [doid]}
645
+
646
+ cascade = self._check_cascade_operation(only_sql)
647
+
648
+ for doid in data['ids']:
649
+ SQL = render_template("/".join([self.template_path,
650
+ self._DELETE_SQL]),
651
+ scid=scid, doid=doid)
652
+ status, res = self.conn.execute_2darray(SQL)
653
+ if not status:
654
+ return internal_server_error(errormsg=res)
655
+
656
+ if not res['rows']:
657
+ return make_json_response(
658
+ status=410,
659
+ success=0,
660
+ errormsg=gettext(
661
+ 'Error: Object not found.'
662
+ ),
663
+ info=self.not_found_error_msg()
664
+ )
665
+
666
+ name = res['rows'][0]['name']
667
+ basensp = res['rows'][0]['basensp']
668
+
669
+ SQL = render_template("/".join([self.template_path,
670
+ self._DELETE_SQL]),
671
+ name=name, basensp=basensp, cascade=cascade)
672
+
673
+ # Used for schema diff tool
674
+ if only_sql:
675
+ return SQL
676
+
677
+ status, res = self.conn.execute_scalar(SQL)
678
+ if not status:
679
+ return internal_server_error(errormsg=res)
680
+
681
+ return make_json_response(
682
+ success=1,
683
+ info=gettext("Domain dropped")
684
+ )
685
+
686
+ @check_precondition
687
+ @validate_request
688
+ def update(self, gid, sid, did, scid, doid):
689
+ """
690
+ Updates the Domain object.
691
+
692
+ Args:
693
+ gid: Server Group Id
694
+ sid: Server Id
695
+ did: Database Id
696
+ scid: Schema Id
697
+ doid: Domain Id
698
+ """
699
+
700
+ SQL, name = self.get_sql(gid, sid, self.request, scid, doid)
701
+ # Most probably this is due to error
702
+ if not isinstance(SQL, str):
703
+ return SQL
704
+
705
+ status, res = self.conn.execute_scalar(SQL)
706
+ if not status:
707
+ return internal_server_error(errormsg=res)
708
+
709
+ # Get Schema Id
710
+ SQL = render_template("/".join([self.template_path,
711
+ self._OID_SQL]),
712
+ doid=doid,
713
+ conn=self.conn)
714
+ status, scid = self.conn.execute_scalar(SQL)
715
+ if not status:
716
+ return internal_server_error(errormsg=scid)
717
+
718
+ other_node_info = {}
719
+ if 'description' in self.request:
720
+ other_node_info['description'] = self.request['description']
721
+
722
+ return jsonify(
723
+ node=self.blueprint.generate_browser_node(
724
+ doid,
725
+ scid,
726
+ name,
727
+ icon="icon-%s" % self.node_type,
728
+ **other_node_info
729
+ )
730
+ )
731
+
732
+ @check_precondition
733
+ def sql(self, gid, sid, did, scid, doid=None, **kwargs):
734
+ """
735
+ Returns the SQL for the Domain object.
736
+
737
+ Args:
738
+ gid: Server Group Id
739
+ sid: Server Id
740
+ did: Database Id
741
+ scid: Schema Id
742
+ doid: Domain Id
743
+ json_resp: True then return json response
744
+ """
745
+ json_resp = kwargs.get('json_resp', True)
746
+ target_schema = kwargs.get('target_schema', None)
747
+
748
+ SQL = render_template("/".join([self.template_path,
749
+ self._PROPERTIES_SQL]),
750
+ scid=scid, doid=doid)
751
+ status, res = self.conn.execute_dict(SQL)
752
+ if not status:
753
+ return internal_server_error(errormsg=res)
754
+ if len(res['rows']) == 0:
755
+ return gone(self.not_found_error_msg())
756
+
757
+ data = res['rows'][0]
758
+ if target_schema:
759
+ data['basensp'] = target_schema
760
+
761
+ # Get Type Length and Precision
762
+ data.update(self._parse_type(data['fulltype']))
763
+
764
+ # Get Domain Constraints
765
+ SQL = render_template("/".join([self.template_path,
766
+ self._GET_CONSTRAINTS_SQL]),
767
+ doid=doid)
768
+ status, res = self.conn.execute_dict(SQL)
769
+ if not status:
770
+ return internal_server_error(errormsg=res)
771
+
772
+ data['constraints'] = res['rows']
773
+
774
+ # Get formatted Security Labels
775
+ if 'seclabels' in data:
776
+ data.update(parse_sec_labels_from_db(data['seclabels']))
777
+
778
+ SQL = render_template("/".join([self.template_path,
779
+ self._CREATE_SQL]), data=data)
780
+
781
+ sql_header = """-- DOMAIN: {0}.{1}\n\n""".format(
782
+ data['basensp'], data['name'])
783
+
784
+ sql_header += """-- DROP DOMAIN IF EXISTS {0};\n
785
+ """.format(self.qtIdent(self.conn, data['basensp'], data['name']))
786
+ SQL = sql_header + SQL
787
+
788
+ if not json_resp:
789
+ return SQL.strip('\n')
790
+
791
+ return ajax_response(response=SQL.strip('\n'))
792
+
793
+ @check_precondition
794
+ @validate_request
795
+ def msql(self, gid, sid, did, scid, doid=None):
796
+ """
797
+ Returns the modified SQL.
798
+
799
+ Args:
800
+ gid: Server Group Id
801
+ sid: Server Id
802
+ did: Database Id
803
+ scid: Schema Id
804
+ doid: Domain Id
805
+
806
+ Required Args:
807
+ name: Domain Name
808
+ owner: Owner Name
809
+ basensp: Schema Name
810
+ basetype: Domain Base Type
811
+
812
+ Returns:
813
+ SQL statements to create/update the Domain.
814
+ """
815
+
816
+ try:
817
+ SQL, _ = self.get_sql(gid, sid, self.request, scid, doid)
818
+ # Most probably this is due to error
819
+ if not isinstance(SQL, str):
820
+ return SQL
821
+ if SQL == '':
822
+ SQL = "--modified SQL"
823
+
824
+ return make_json_response(
825
+ data=SQL,
826
+ status=200
827
+ )
828
+ except Exception as e:
829
+ return internal_server_error(errormsg=str(e))
830
+
831
+ def check_domain_type(self, data, old_data, is_schema_diff):
832
+ """
833
+ Check domain type
834
+ :return:
835
+ """
836
+ # If fulltype or basetype or collname is changed while comparing
837
+ # two schemas then we need to drop domain and recreate it
838
+ if 'fulltype' in data or 'basetype' in data or 'collname' in data:
839
+ SQL = render_template(
840
+ "/".join([self.template_path, 'domain_schema_diff.sql']),
841
+ data=data, o_data=old_data)
842
+ else:
843
+ if is_schema_diff:
844
+ data['is_schema_diff'] = True
845
+
846
+ SQL = render_template(
847
+ "/".join([self.template_path, self._UPDATE_SQL]),
848
+ data=data, o_data=old_data, conn=self.conn)
849
+ return SQL, data
850
+
851
+ def get_sql(self, gid, sid, data, scid, doid=None, is_schema_diff=False):
852
+ """
853
+ Generates the SQL statements to create/update the Domain.
854
+
855
+ Args:
856
+ gid: Server Group Id
857
+ sid: Server Id
858
+ did: Database Id
859
+ scid: Schema Id
860
+ doid: Domain Id
861
+ is_schema_diff: True is function gets called from schema diff
862
+ """
863
+
864
+ if doid is not None:
865
+ SQL = render_template("/".join([self.template_path,
866
+ self._PROPERTIES_SQL]),
867
+ scid=scid, doid=doid)
868
+ status, res = self.conn.execute_dict(SQL)
869
+
870
+ if not status:
871
+ return False, internal_server_error(errormsg=res)
872
+ if len(res['rows']) == 0:
873
+ return gone(self.not_found_error_msg())
874
+
875
+ old_data = res['rows'][0]
876
+
877
+ # Get Domain Constraints
878
+ SQL = render_template("/".join([self.template_path,
879
+ self._GET_CONSTRAINTS_SQL]),
880
+ doid=doid)
881
+ status, res = self.conn.execute_dict(SQL)
882
+ if not status:
883
+ return internal_server_error(errormsg=res)
884
+
885
+ con_data = {}
886
+ for c in res['rows']:
887
+ con_data[c['conoid']] = c
888
+
889
+ old_data['constraints'] = con_data
890
+
891
+ SQL, data = self.check_domain_type(data, old_data, is_schema_diff)
892
+ return SQL.strip('\n'), data['name'] if 'name' in data else \
893
+ old_data['name']
894
+ else:
895
+ SQL = render_template("/".join([self.template_path,
896
+ self._CREATE_SQL]),
897
+ data=data)
898
+ return SQL.strip('\n'), data['name']
899
+
900
+ @check_precondition
901
+ def dependents(self, gid, sid, did, scid, doid):
902
+ """
903
+ This function get the dependents and return ajax response
904
+ for the Domain node.
905
+
906
+ Args:
907
+ gid: Server Group Id
908
+ sid: Server Id
909
+ did: Database Id
910
+ scid: Schema Id
911
+ doid: Domain Id
912
+ """
913
+ dependents_result = self.get_dependents(self.conn, doid)
914
+ return ajax_response(
915
+ response=dependents_result,
916
+ status=200
917
+ )
918
+
919
+ @check_precondition
920
+ def dependencies(self, gid, sid, did, scid, doid):
921
+ """
922
+ This function get the dependencies and return ajax response
923
+ for the Domain node.
924
+
925
+ Args:
926
+ gid: Server Group Id
927
+ sid: Server Id
928
+ did: Database Id
929
+ scid: Schema Id
930
+ doid: Domain Id
931
+ """
932
+ dependencies_result = self.get_dependencies(self.conn, doid)
933
+ return ajax_response(
934
+ response=dependencies_result,
935
+ status=200
936
+ )
937
+
938
+ @check_precondition
939
+ def fetch_objects_to_compare(self, sid, did, scid):
940
+ """
941
+ This function will fetch the list of all the domains for
942
+ specified schema id.
943
+
944
+ :param sid: Server Id
945
+ :param did: Database Id
946
+ :param scid: Schema Id
947
+ :return:
948
+ """
949
+ res = dict()
950
+ SQL = render_template("/".join([self.template_path,
951
+ self._NODE_SQL]), scid=scid,
952
+ schema_diff=True)
953
+ status, rset = self.conn.execute_2darray(SQL)
954
+ if not status:
955
+ return internal_server_error(errormsg=rset)
956
+
957
+ for row in rset['rows']:
958
+ status, data = self._fetch_properties(did, scid, row['oid'])
959
+
960
+ if status:
961
+ res[row['name']] = data
962
+
963
+ return res
964
+
965
+ def get_sql_from_diff(self, **kwargs):
966
+ """
967
+ This function is used to get the DDL/DML statements.
968
+ :param kwargs
969
+ :return:
970
+ """
971
+ gid = kwargs.get('gid')
972
+ sid = kwargs.get('sid')
973
+ did = kwargs.get('did')
974
+ scid = kwargs.get('scid')
975
+ oid = kwargs.get('oid')
976
+ data = kwargs.get('data', None)
977
+ drop_sql = kwargs.get('drop_sql', False)
978
+ target_schema = kwargs.get('target_schema', None)
979
+
980
+ if data:
981
+ if target_schema:
982
+ data['schema'] = target_schema
983
+ sql, _ = self.get_sql(gid=gid, sid=sid, scid=scid,
984
+ data=data, doid=oid, is_schema_diff=True)
985
+ else:
986
+ if drop_sql:
987
+ sql = self.delete(gid=gid, sid=sid, did=did,
988
+ scid=scid, doid=oid, only_sql=True)
989
+ elif target_schema:
990
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, doid=oid,
991
+ target_schema=target_schema, json_resp=False)
992
+ else:
993
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, doid=oid,
994
+ json_resp=False)
995
+ return sql
996
+
997
+ def get_dependencies(self, conn, object_id, where=None,
998
+ show_system_objects=None, is_schema_diff=False):
999
+ """
1000
+ This function is used to get dependencies of domain and it's
1001
+ domain constraints.
1002
+ """
1003
+ domain_dependencies = []
1004
+ domain_deps = super().get_dependencies(
1005
+ conn, object_id, where=None, show_system_objects=None,
1006
+ is_schema_diff=True)
1007
+ if len(domain_deps) > 0:
1008
+ domain_dependencies.extend(domain_deps)
1009
+
1010
+ # Get Domain Constraints
1011
+ SQL = render_template("/".join([self.template_path,
1012
+ self._GET_CONSTRAINTS_SQL]),
1013
+ doid=object_id)
1014
+ status, res = self.conn.execute_dict(SQL)
1015
+ if not status:
1016
+ return False, internal_server_error(errormsg=res)
1017
+
1018
+ # Get the domain constraints dependencies.
1019
+ for row in res['rows']:
1020
+ constraint_deps = super().get_dependencies(
1021
+ conn, row['conoid'], where=None, show_system_objects=None,
1022
+ is_schema_diff=True)
1023
+ if len(constraint_deps) > 0:
1024
+ domain_dependencies.extend(constraint_deps)
1025
+
1026
+ return domain_dependencies
1027
+
1028
+
1029
+ SchemaDiffRegistry(blueprint.node_type, DomainView)
1030
+ DomainView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/__init__.py ADDED
@@ -0,0 +1,770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ##########################################################################
3
+ #
4
+ # pgAdmin 4 - PostgreSQL Tools
5
+ #
6
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
7
+ # This software is released under the PostgreSQL Licence
8
+ #
9
+ ##########################################################################
10
+
11
+ """Implements the Domain Constraint Module."""
12
+
13
+ from functools import wraps
14
+
15
+ import json
16
+ from flask import render_template, request, jsonify
17
+ from flask_babel import gettext
18
+
19
+ from pgadmin.browser.server_groups.servers.databases.schemas import domains
20
+ from config import PG_DEFAULT_DRIVER
21
+ from pgadmin.browser.collection import CollectionNodeModule
22
+ from pgadmin.browser.utils import PGChildNodeView
23
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
24
+ make_response as ajax_response, gone
25
+ from pgadmin.utils.driver import get_driver
26
+ from pgadmin.utils.exception import ObjectGone
27
+
28
+
29
+ class DomainConstraintModule(CollectionNodeModule):
30
+ """
31
+ class DomainConstraintModule(CollectionNodeModule):
32
+
33
+ This class represents The Domain Constraint Module.
34
+
35
+ Methods:
36
+ -------
37
+ * __init__(*args, **kwargs)
38
+ - Initialize the Domain Constraint Module.
39
+
40
+ * get_nodes(gid, sid, did, scid)
41
+ - Generate the Domain Constraint collection node.
42
+
43
+ * node_inode(gid, sid, did, scid)
44
+ - Returns Domain Constraint node as leaf node.
45
+
46
+ * script_load()
47
+ - Load the module script for the Domain Constraint, when any of the
48
+ Domain node is initialized.
49
+ """
50
+ _NODE_TYPE = 'domain_constraints'
51
+ _COLLECTION_LABEL = gettext("Domain Constraints")
52
+
53
+ def __init__(self, *args, **kwargs):
54
+ super().__init__(*args, **kwargs)
55
+ self.min_ver = None
56
+ self.max_ver = None
57
+
58
+ def get_nodes(self, gid, sid, did, scid, doid):
59
+ """
60
+ Generate the Domain Constraint collection node.
61
+ """
62
+ yield self.generate_browser_collection_node(doid)
63
+
64
+ @property
65
+ def node_inode(self):
66
+ """
67
+ Returns Domain Constraint node as leaf node.
68
+ """
69
+ return False
70
+
71
+ @property
72
+ def script_load(self):
73
+ """
74
+ Load the module script for the Domain Constraint, when any of the
75
+ Domain node is initialized.
76
+ """
77
+ return domains.DomainModule.node_type
78
+
79
+ @property
80
+ def csssnippets(self):
81
+ """
82
+ Returns a snippet of css to include in the page
83
+ """
84
+ return [
85
+ render_template(
86
+ "domain_constraints/css/domain_constraints.css",
87
+ node_type=self.node_type
88
+ )
89
+ ]
90
+
91
+ @property
92
+ def module_use_template_javascript(self):
93
+ """
94
+ Returns whether Jinja2 template is used for generating the javascript
95
+ module.
96
+ """
97
+ return False
98
+
99
+
100
+ blueprint = DomainConstraintModule(__name__)
101
+
102
+
103
+ class DomainConstraintView(PGChildNodeView):
104
+ """
105
+ class DomainConstraintView(PGChildNodeView):
106
+
107
+ This class inherits PGChildNodeView to get the different routes for
108
+ the module.
109
+
110
+ The class is responsible to Create, Read, Update and Delete operations for
111
+ the Domain Constraint.
112
+
113
+ Methods:
114
+ -------
115
+
116
+ * check_precondition(f):
117
+ - Works as a decorator.
118
+ - Checks database connection status.
119
+ - Attach connection object and template path.
120
+
121
+ * list(gid, sid, did, scid, doid):
122
+ - List the Domain Constraints.
123
+
124
+ * nodes(gid, sid, did, scid):
125
+ - Returns all the Domain Constraints to generate Nodes in the browser.
126
+
127
+ * properties(gid, sid, did, scid, doid):
128
+ - Returns the Domain Constraint properties.
129
+
130
+ * create(gid, sid, did, scid):
131
+ - Creates a new Domain Constraint object.
132
+
133
+ * update(gid, sid, did, scid, doid):
134
+ - Updates the Domain Constraint object.
135
+
136
+ * delete(gid, sid, did, scid, doid):
137
+ - Drops the Domain Constraint object.
138
+
139
+ * sql(gid, sid, did, scid, doid=None):
140
+ - Returns the SQL for the Domain Constraint object.
141
+
142
+ * msql(gid, sid, did, scid, doid=None):
143
+ - Returns the modified SQL.
144
+
145
+ * get_sql(gid, sid, data, scid, doid=None):
146
+ - Generates the SQL statements to create/update the Domain Constraint.
147
+ object.
148
+
149
+ * dependents(gid, sid, did, scid, doid, coid):
150
+ - Returns the dependents for the Domain Constraint object.
151
+
152
+ * dependencies(gid, sid, did, scid, doid, coid):
153
+ - Returns the dependencies for the Domain Constraint object.
154
+ """
155
+ node_type = blueprint.node_type
156
+ node_label = "Domain Constraint"
157
+
158
+ parent_ids = [
159
+ {'type': 'int', 'id': 'gid'},
160
+ {'type': 'int', 'id': 'sid'},
161
+ {'type': 'int', 'id': 'did'},
162
+ {'type': 'int', 'id': 'scid'},
163
+ {'type': 'int', 'id': 'doid'}
164
+ ]
165
+ ids = [
166
+ {'type': 'int', 'id': 'coid'}
167
+ ]
168
+
169
+ operations = dict({
170
+ 'obj': [
171
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
172
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
173
+ ],
174
+ 'children': [{'get': 'children'}],
175
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
176
+ 'sql': [{'get': 'sql'}],
177
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
178
+ 'stats': [{'get': 'statistics'}],
179
+ 'dependency': [{'get': 'dependencies'}],
180
+ 'dependent': [{'get': 'dependents'}]
181
+ })
182
+
183
+ @staticmethod
184
+ def _get_req_data(kwargs):
185
+ """
186
+ Get data from request.
187
+ :param kwargs: kwargs for request.
188
+ :return: if any error return error with error msg else return req data
189
+ """
190
+ if request.data:
191
+ req = json.loads(request.data)
192
+ else:
193
+ req = request.args or request.form
194
+
195
+ if 'coid' not in kwargs:
196
+ required_args = [
197
+ 'name',
198
+ 'consrc'
199
+ ]
200
+
201
+ for arg in required_args:
202
+ if arg not in req or req[arg] == '':
203
+ return True, make_json_response(
204
+ status=410,
205
+ success=0,
206
+ errormsg=gettext(
207
+ "Could not find the required parameter ({})."
208
+ ).format(arg)
209
+ ), req
210
+ return False, '', req
211
+
212
+ def validate_request(f):
213
+ """
214
+ Works as a decorator.
215
+ Validating request on the request of create, update and modified SQL.
216
+
217
+ Required Args:
218
+ name: Name of the Domain Constraint
219
+ consrc: Check Constraint Definition
220
+
221
+ Above both the arguments will not be validated in the update action.
222
+ """
223
+
224
+ @wraps(f)
225
+ def wrap(self, **kwargs):
226
+
227
+ data = {}
228
+ is_error, errmsg, req = DomainConstraintView._get_req_data(kwargs)
229
+ if is_error:
230
+ return errmsg
231
+
232
+ try:
233
+ for key in req:
234
+ if key == 'convalidated':
235
+ data[key] = True if (req[key] == 'true' or req[key] is
236
+ True) else False
237
+ else:
238
+ data[key] = req[key]
239
+
240
+ except Exception as e:
241
+ return internal_server_error(errormsg=str(e))
242
+
243
+ self.request = data
244
+ return f(self, **kwargs)
245
+
246
+ return wrap
247
+
248
+ def check_precondition(f):
249
+ """
250
+ Works as a decorator.
251
+ Checks database connection status.
252
+ Attach connection object and template path.
253
+ """
254
+
255
+ @wraps(f)
256
+ def wrap(*args, **kwargs):
257
+ self = args[0]
258
+ driver = get_driver(PG_DEFAULT_DRIVER)
259
+ self.manager = driver.connection_manager(kwargs['sid'])
260
+ self.conn = self.manager.connection(did=kwargs['did'])
261
+ self.qtIdent = driver.qtIdent
262
+ self.datistemplate = False
263
+ if (
264
+ self.manager.db_info is not None and
265
+ kwargs['did'] in self.manager.db_info and
266
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
267
+ ):
268
+ self.datistemplate = self.manager.db_info[
269
+ kwargs['did']]['datistemplate']
270
+
271
+ # Set the template path for the SQL scripts
272
+ self.template_path = 'domain_constraints/sql/#{0}#'.format(
273
+ self.manager.version)
274
+
275
+ return f(*args, **kwargs)
276
+
277
+ return wrap
278
+
279
+ @check_precondition
280
+ def list(self, gid, sid, did, scid, doid):
281
+ """
282
+ List the Domain Constraints.
283
+
284
+ Args:
285
+ gid: Server Group Id
286
+ sid: Server Id
287
+ did: Database Id
288
+ scid: Schema Id
289
+ doid: Domain Id
290
+ """
291
+ SQL = render_template("/".join([self.template_path,
292
+ self._PROPERTIES_SQL]),
293
+ doid=doid)
294
+ status, res = self.conn.execute_dict(SQL)
295
+
296
+ if not status:
297
+ return internal_server_error(errormsg=res)
298
+ return ajax_response(
299
+ response=res['rows'],
300
+ status=200
301
+ )
302
+
303
+ @check_precondition
304
+ def nodes(self, gid, sid, did, scid, doid):
305
+ """
306
+ Returns all the Domain Constraints.
307
+
308
+ Args:
309
+ gid: Server Group Id
310
+ sid: Server Id
311
+ did: Database Id
312
+ scid: Schema Id
313
+ doid: Domain Id
314
+ """
315
+ res = []
316
+ SQL = render_template("/".join([self.template_path,
317
+ self._PROPERTIES_SQL]),
318
+ doid=doid)
319
+ status, rset = self.conn.execute_2darray(SQL)
320
+
321
+ if not status:
322
+ return internal_server_error(errormsg=rset)
323
+
324
+ for row in rset['rows']:
325
+ if 'convalidated' not in row:
326
+ icon = 'icon-domain_constraints'
327
+ elif row['convalidated']:
328
+ icon = 'icon-domain_constraints'
329
+ else:
330
+ icon = 'icon-domain_constraints-bad'
331
+ res.append(
332
+ self.blueprint.generate_browser_node(
333
+ row['oid'],
334
+ doid,
335
+ row['name'],
336
+ icon=icon,
337
+ description=row['description']
338
+ ))
339
+
340
+ return make_json_response(
341
+ data=res,
342
+ status=200
343
+ )
344
+
345
+ @check_precondition
346
+ def node(self, gid, sid, did, scid, doid, coid):
347
+ """
348
+ Returns all the Domain Constraints.
349
+
350
+ Args:
351
+ gid: Server Group Id
352
+ sid: Server Id
353
+ did: Database Id
354
+ scid: Schema Id
355
+ doid: Domain Id
356
+ coid: Domain Constraint Id
357
+ """
358
+ SQL = render_template("/".join([self.template_path,
359
+ self._PROPERTIES_SQL]),
360
+ coid=coid)
361
+ status, rset = self.conn.execute_2darray(SQL)
362
+
363
+ if not status:
364
+ return internal_server_error(errormsg=rset)
365
+
366
+ for row in rset['rows']:
367
+ if 'convalidated' not in row:
368
+ icon = 'icon-domain_constraints'
369
+ elif row['convalidated']:
370
+ icon = 'icon-domain_constraints'
371
+ else:
372
+ icon = 'icon-domain_constraints-bad'
373
+ return make_json_response(
374
+ data=self.blueprint.generate_browser_node(
375
+ row['oid'],
376
+ doid,
377
+ row['name'],
378
+ icon=icon
379
+ ),
380
+ status=200
381
+ )
382
+
383
+ return gone(self.not_found_error_msg())
384
+
385
+ @check_precondition
386
+ def properties(self, gid, sid, did, scid, doid, coid):
387
+ """
388
+ Returns the Domain Constraints property.
389
+
390
+ Args:
391
+ gid: Server Group Id
392
+ sid: Server Id
393
+ did: Database Id
394
+ scid: Schema Id
395
+ doid: Domain Id
396
+ coid: Domain Constraint Id
397
+ """
398
+
399
+ SQL = render_template("/".join([self.template_path,
400
+ self._PROPERTIES_SQL]),
401
+ doid=doid, coid=coid)
402
+ status, res = self.conn.execute_dict(SQL)
403
+ if not status:
404
+ return internal_server_error(errormsg=res)
405
+
406
+ if len(res['rows']) == 0:
407
+ return gone(self.not_found_error_msg())
408
+
409
+ data = res['rows'][0]
410
+ data['is_sys_obj'] = (
411
+ data['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
412
+ self.datistemplate)
413
+ return ajax_response(
414
+ response=data,
415
+ status=200
416
+ )
417
+
418
+ @check_precondition
419
+ @validate_request
420
+ def create(self, gid, sid, did, scid, doid):
421
+ """
422
+ Creates a new Domain Constraint object.
423
+
424
+ Args:
425
+ gid: Server Group Id
426
+ sid: Server Id
427
+ did: Database Id
428
+ scid: Schema Id
429
+ doid: Domain Id
430
+
431
+ Returns:
432
+ Domain Constraint object in json format.
433
+ """
434
+ data = self.request
435
+ try:
436
+ status, SQL, _ = self.get_sql(gid, sid, data, scid, doid)
437
+ if not status:
438
+ return SQL
439
+
440
+ status, res = self.conn.execute_scalar(SQL)
441
+
442
+ if not status:
443
+ return internal_server_error(errormsg=res)
444
+
445
+ # Get the recently added constraints oid
446
+ SQL = render_template("/".join([self.template_path,
447
+ self._OID_SQL]),
448
+ doid=doid, name=data['name'],
449
+ conn=self.conn)
450
+ status, coid = self.conn.execute_scalar(SQL)
451
+ if not status:
452
+ return internal_server_error(errormsg=coid)
453
+
454
+ if 'convalidated' not in data:
455
+ icon = 'icon-domain_constraints'
456
+ elif 'convalidated' in data and data['convalidated']:
457
+ icon = 'icon-domain_constraints'
458
+ else:
459
+ icon = 'icon-domain_constraints-bad'
460
+
461
+ return jsonify(
462
+ node=self.blueprint.generate_browser_node(
463
+ coid,
464
+ doid,
465
+ data['name'],
466
+ icon=icon
467
+ )
468
+ )
469
+ except ObjectGone:
470
+ raise
471
+ except Exception as e:
472
+ return internal_server_error(errormsg=str(e))
473
+
474
+ @check_precondition
475
+ def delete(self, gid, sid, did, scid, doid, coid=None):
476
+ """
477
+ Drops the Domain Constraint object.
478
+
479
+ Args:
480
+ gid: Server Group Id
481
+ sid: Server Id
482
+ did: Database Id
483
+ scid: Schema Id
484
+ doid: Domain Id
485
+ coid: Domain Constraint Id
486
+ """
487
+ if coid is None:
488
+ data = request.form if request.form else json.loads(
489
+ request.data
490
+ )
491
+ else:
492
+ data = {'ids': [coid]}
493
+
494
+ try:
495
+ for coid in data['ids']:
496
+ SQL = render_template("/".join([self.template_path,
497
+ self._PROPERTIES_SQL]),
498
+ doid=doid, coid=coid)
499
+ status, res = self.conn.execute_dict(SQL)
500
+
501
+ if not status:
502
+ return internal_server_error(errormsg=res)
503
+
504
+ if not res['rows']:
505
+ return make_json_response(
506
+ status=410,
507
+ success=0,
508
+ errormsg=gettext(
509
+ 'Error: Object not found.'
510
+ ),
511
+ info=self.not_found_error_msg()
512
+ )
513
+
514
+ data = res['rows'][0]
515
+
516
+ SQL = render_template("/".join([self.template_path,
517
+ self._DELETE_SQL]),
518
+ data=data)
519
+ status, res = self.conn.execute_scalar(SQL)
520
+ if not status:
521
+ return internal_server_error(errormsg=res)
522
+
523
+ return make_json_response(
524
+ success=1,
525
+ info=gettext("Domain Constraint dropped")
526
+ )
527
+
528
+ except Exception as e:
529
+ return internal_server_error(errormsg=str(e))
530
+
531
+ @check_precondition
532
+ @validate_request
533
+ def update(self, gid, sid, did, scid, doid, coid):
534
+ """
535
+ Updates the Domain Constraint object.
536
+
537
+ Args:
538
+ gid: Server Group Id
539
+ sid: Server Id
540
+ did: Database Id
541
+ scid: Schema Id
542
+ doid: Domain Id
543
+ coid: Domain Constraint Id
544
+ """
545
+ data = self.request
546
+ status, SQL, name = self.get_sql(gid, sid, data, scid, doid, coid)
547
+ if not status:
548
+ return SQL
549
+
550
+ try:
551
+ if SQL and status:
552
+ status, res = self.conn.execute_scalar(SQL)
553
+ if not status:
554
+ return internal_server_error(errormsg=res)
555
+
556
+ if 'convalidated' in data and data['convalidated']:
557
+ icon = 'icon-domain_constraints'
558
+ elif 'convalidated' in data and not data['convalidated']:
559
+ icon = 'icon-domain_constraints-bad'
560
+ else:
561
+ icon = ''
562
+
563
+ other_node_info = {}
564
+ if 'description' in data:
565
+ other_node_info['description'] = data['description']
566
+
567
+ return jsonify(
568
+ node=self.blueprint.generate_browser_node(
569
+ coid,
570
+ doid,
571
+ name,
572
+ icon=icon,
573
+ **other_node_info
574
+ )
575
+ )
576
+ else:
577
+ return make_json_response(
578
+ success=1,
579
+ info="Nothing to update",
580
+ data={
581
+ 'id': coid,
582
+ 'doid': doid,
583
+ 'scid': scid,
584
+ 'sid': sid,
585
+ 'gid': gid,
586
+ 'did': did
587
+ }
588
+ )
589
+
590
+ except Exception as e:
591
+ return internal_server_error(errormsg=str(e))
592
+
593
+ @check_precondition
594
+ def sql(self, gid, sid, did, scid, doid, coid=None):
595
+ """
596
+ Returns the SQL for the Domain Constraint object.
597
+
598
+ Args:
599
+ gid: Server Group Id
600
+ sid: Server Id
601
+ did: Database Id
602
+ scid: Schema Id
603
+ doid: Domain Id
604
+ coid: Domain Constraint Id
605
+ """
606
+
607
+ # Get Schema and Domain.
608
+ schema, domain = self._get_domain(doid)
609
+
610
+ SQL = render_template("/".join([self.template_path,
611
+ self._PROPERTIES_SQL]),
612
+ doid=doid, coid=coid)
613
+ status, res = self.conn.execute_dict(SQL)
614
+ if not status:
615
+ return internal_server_error(errormsg=res)
616
+ if len(res['rows']) == 0:
617
+ return gone(self.not_found_error_msg())
618
+
619
+ data = res['rows'][0]
620
+
621
+ SQL = render_template("/".join([self.template_path,
622
+ self._CREATE_SQL]),
623
+ data=data, domain=domain, schema=schema)
624
+
625
+ sql_header = """-- CHECK: {1}.{0}
626
+
627
+ -- ALTER DOMAIN {1} DROP CONSTRAINT {0};
628
+
629
+ """.format(self.qtIdent(self.conn, data['name']),
630
+ self.qtIdent(self.conn, schema, domain))
631
+
632
+ SQL = sql_header + SQL
633
+
634
+ return ajax_response(response=SQL)
635
+
636
+ @check_precondition
637
+ @validate_request
638
+ def msql(self, gid, sid, did, scid, doid, coid=None):
639
+ """
640
+ Returns the modified SQL.
641
+
642
+ Args:
643
+ gid: Server Group Id
644
+ sid: Server Id
645
+ did: Database Id
646
+ scid: Schema Id
647
+ doid: Domain Id
648
+ coid: Domain Constraint Id
649
+
650
+ Returns:
651
+ Domain Constraint object in json format.
652
+ """
653
+ data = self.request
654
+
655
+ status, SQL, _ = self.get_sql(gid, sid, data, scid, doid, coid)
656
+ if status and SQL:
657
+ return make_json_response(
658
+ data=SQL,
659
+ status=200
660
+ )
661
+ else:
662
+ return SQL
663
+
664
+ def get_sql(self, gid, sid, data, scid, doid, coid=None):
665
+ """
666
+ Generates the SQL statements to create/update the Domain Constraint.
667
+
668
+ Args:
669
+ gid: Server Group Id
670
+ sid: Server Id
671
+ did: Database Id
672
+ scid: Schema Id
673
+ doid: Domain Id
674
+ coid: Domain Constraint Id
675
+ """
676
+ try:
677
+ if coid is not None:
678
+ SQL = render_template("/".join([self.template_path,
679
+ self._PROPERTIES_SQL]),
680
+ doid=doid, coid=coid)
681
+ status, res = self.conn.execute_dict(SQL)
682
+
683
+ if not status:
684
+ return False, internal_server_error(errormsg=res)
685
+ if len(res['rows']) == 0:
686
+ return False, gone(self.not_found_error_msg())
687
+
688
+ old_data = res['rows'][0]
689
+
690
+ SQL = render_template(
691
+ "/".join([self.template_path, self._UPDATE_SQL]),
692
+ data=data, o_data=old_data, conn=self.conn
693
+ )
694
+ else:
695
+ schema, domain = self._get_domain(doid)
696
+
697
+ SQL = render_template("/".join([self.template_path,
698
+ self._CREATE_SQL]),
699
+ data=data, domain=domain, schema=schema)
700
+ if 'name' in data:
701
+ return True, SQL.strip('\n'), data['name']
702
+ else:
703
+ return True, SQL.strip('\n'), old_data['name']
704
+ except ObjectGone:
705
+ raise
706
+ except Exception as e:
707
+ return False, internal_server_error(errormsg=str(e)), None
708
+
709
+ def _get_domain(self, doid):
710
+ """
711
+ Returns Domain and Schema name.
712
+
713
+ Args:
714
+ doid: Domain Id
715
+
716
+ """
717
+ SQL = render_template("/".join([self.template_path,
718
+ 'get_domain.sql']),
719
+ doid=doid)
720
+ status, res = self.conn.execute_2darray(SQL)
721
+
722
+ if not status:
723
+ return False, internal_server_error(errormsg=res)
724
+ if len(res['rows']) == 0:
725
+ raise ObjectGone(self.not_found_error_msg('Domain'))
726
+
727
+ return res['rows'][0]['schema'], res['rows'][0]['domain']
728
+
729
+ @check_precondition
730
+ def dependents(self, gid, sid, did, scid, doid, coid):
731
+ """
732
+ This function get the dependents and return ajax response
733
+ for the Domain Constraint node.
734
+
735
+ Args:
736
+ gid: Server Group Id
737
+ sid: Server Id
738
+ did: Database Id
739
+ scid: Schema Id
740
+ doid: Domain Id
741
+ coid: Domain Constraint Id
742
+ """
743
+ dependents_result = self.get_dependents(self.conn, coid)
744
+ return ajax_response(
745
+ response=dependents_result,
746
+ status=200
747
+ )
748
+
749
+ @check_precondition
750
+ def dependencies(self, gid, sid, did, scid, doid, coid):
751
+ """
752
+ This function get the dependencies and return ajax response
753
+ for the Domain Constraint node.
754
+
755
+ Args:
756
+ gid: Server Group Id
757
+ sid: Server Id
758
+ did: Database Id
759
+ scid: Schema Id
760
+ doid: Domain Id
761
+ coid: Domain Constraint Id
762
+ """
763
+ dependencies_result = self.get_dependencies(self.conn, coid)
764
+ return ajax_response(
765
+ response=dependencies_result,
766
+ status=200
767
+ )
768
+
769
+
770
+ DomainConstraintView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/coll-domain_constraints.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints-bad.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.js ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////
2
+ //
3
+ // pgAdmin 4 - PostgreSQL Tools
4
+ //
5
+ // Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ // This software is released under the PostgreSQL Licence
7
+ //
8
+ //////////////////////////////////////////////////////////////
9
+
10
+ import DomainConstraintSchema from './domain_constraints.ui';
11
+
12
+ // Domain Constraint Module: Collection and Node
13
+ define('pgadmin.node.domain_constraints', [
14
+ 'sources/gettext', 'sources/url_for',
15
+ 'sources/pgadmin', 'pgadmin.browser',
16
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
17
+ ], function(gettext, url_for, pgAdmin, pgBrowser, schemaChildTreeNode) {
18
+
19
+ // Define Domain Constraint Collection Node
20
+ if (!pgBrowser.Nodes['coll-domain_constraints']) {
21
+ pgAdmin.Browser.Nodes['coll-domain_constraints'] =
22
+ pgAdmin.Browser.Collection.extend({
23
+ node: 'domain_constraints',
24
+ label: gettext('Domain Constraints'),
25
+ type: 'coll-domain_constraints',
26
+ columns: ['name', 'description'],
27
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
28
+ canDropCascade: false,
29
+ });
30
+ }
31
+
32
+ // Domain Constraint Node
33
+ if (!pgBrowser.Nodes['domain_constraints']) {
34
+ pgAdmin.Browser.Nodes['domain_constraints'] = pgBrowser.Node.extend({
35
+ type: 'domain_constraints',
36
+ sqlAlterHelp: 'sql-alterdomain.html',
37
+ sqlCreateHelp: 'sql-alterdomain.html',
38
+ dialogHelp: url_for('help.static', {'filename': 'domain_constraint_dialog.html'}),
39
+ label: gettext('Domain Constraints'),
40
+ collection_type: 'coll-domain_constraints',
41
+ hasSQL: true,
42
+ hasDepends: true,
43
+ parent_type: ['domain'],
44
+ Init: function() {
45
+ // Avoid mulitple registration of menus
46
+ if (this.initialized)
47
+ return;
48
+
49
+ this.initialized = true;
50
+
51
+ pgBrowser.add_menus([{
52
+ name: 'create_domain_on_coll', node: 'coll-domain_constraints', module: this,
53
+ applies: ['object', 'context'], callback: 'show_obj_properties',
54
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
55
+ data: {action: 'create', check: true}, enable: 'canCreate',
56
+ },{
57
+ name: 'create_domain_constraints', node: 'domain_constraints', module: this,
58
+ applies: ['object', 'context'], callback: 'show_obj_properties',
59
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
60
+ data: {action: 'create', check: true}, enable: 'canCreate',
61
+ },{
62
+ name: 'create_domain_constraints', node: 'domain', module: this,
63
+ applies: ['object', 'context'], callback: 'show_obj_properties',
64
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
65
+ data: {action: 'create', check: false}, enable: 'canCreate',
66
+ },
67
+ ]);
68
+
69
+ },
70
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
71
+
72
+ getSchema: function() {
73
+ return new DomainConstraintSchema();
74
+ },
75
+ });
76
+ }
77
+
78
+ return pgBrowser.Nodes['domain'];
79
+ });
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.ui.js ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////
2
+ //
3
+ // pgAdmin 4 - PostgreSQL Tools
4
+ //
5
+ // Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ // This software is released under the PostgreSQL Licence
7
+ //
8
+ //////////////////////////////////////////////////////////////
9
+
10
+ import gettext from 'sources/gettext';
11
+ import BaseUISchema from 'sources/SchemaView/base_schema.ui';
12
+
13
+ export default class DomainConstraintSchema extends BaseUISchema {
14
+ constructor(initValues) {
15
+ super({
16
+ name: undefined,
17
+ oid: undefined,
18
+ description: undefined,
19
+ consrc: undefined,
20
+ convalidated: true,
21
+ ...initValues,
22
+ });
23
+ }
24
+
25
+ get idAttribute() {
26
+ return 'oid';
27
+ }
28
+
29
+ get baseFields() {
30
+ let obj = this;
31
+ return [
32
+ {
33
+ id: 'name', label: gettext('Name'), type:'text', cell:'text',
34
+ noEmpty: true,
35
+ }, {
36
+ id: 'oid', label: gettext('OID'), cell: 'text',
37
+ type: 'text' , mode: ['properties'],
38
+ }, {
39
+ id: 'is_sys_obj', label: gettext('System domain constraint?'),
40
+ cell:'boolean', type: 'switch', mode: ['properties'],
41
+ }, {
42
+ id: 'description', label: gettext('Comment'), type: 'multiline', cell:
43
+ 'text', mode: ['properties', 'create', 'edit'], min_version: 90500,
44
+ }, {
45
+ id: 'consrc', label: gettext('Check'), type: 'multiline',
46
+ group: gettext('Definition'), mode: ['properties', 'create', 'edit'],
47
+ readonly: function(state) {return !obj.isNew(state); },
48
+ noEmpty: true,
49
+ }, {
50
+ id: 'convalidated', label: gettext('Validate?'), type: 'switch',
51
+ cell:'boolean', group: gettext('Definition'), min_version: 90200,
52
+ mode: ['properties', 'create', 'edit'],
53
+ readonly: function(state) {
54
+ return !obj.isNew(state) && obj._origData.convalidated;
55
+ }
56
+ }
57
+ ];
58
+ }
59
+ }
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/css/domain_constraints.css ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .icon-coll-domain_constraints {
2
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/coll-domain_constraints.svg' )}}') !important;
3
+ background-repeat: no-repeat;
4
+ background-size: 20px !important;
5
+ align-content: center;
6
+ vertical-align: middle;
7
+ height: 1.3em;
8
+ }
9
+
10
+ .icon-check-bad, .icon-domain_constraints-bad {
11
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/domain_constraints-bad.svg' )}}') !important;
12
+ background-repeat: no-repeat;
13
+ background-size: 20px !important;
14
+ align-content: center;
15
+ vertical-align: middle;
16
+ height: 1.3em;
17
+ }
18
+
19
+ .icon-check, .icon-domain_constraints {
20
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/domain_constraints.svg' )}}') !important;
21
+ background-repeat: no-repeat;
22
+ background-size: 20px !important;
23
+ align-content: center;
24
+ vertical-align: middle;
25
+ height: 1.3em;
26
+ }
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/create.sql ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {% if data and schema and domain %}
2
+ ALTER DOMAIN {{ conn|qtIdent(schema, domain) }}
3
+ ADD CONSTRAINT {{ conn|qtIdent(data.name) }} CHECK ({{ data.consrc }}){% if not data.convalidated %}
4
+
5
+ NOT VALID{% endif %};{% if data.description %}
6
+
7
+
8
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON DOMAIN {{ conn|qtIdent(schema, domain) }}
9
+ IS '{{ data.description }}';{% endif %}
10
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/delete.sql ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {% if data %}
2
+ ALTER DOMAIN {{ conn|qtIdent(data.nspname, data.relname) }}
3
+ DROP CONSTRAINT {{ conn|qtIdent(data.name) }};
4
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_domain.sql ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ d.typname as domain, bn.nspname as schema
3
+ FROM
4
+ pg_catalog.pg_type d
5
+ JOIN
6
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
7
+ WHERE
8
+ d.oid = {{doid}};
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_oid.sql ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ oid, conname as name
3
+ FROM
4
+ pg_catalog.pg_constraint
5
+ WHERE
6
+ contypid = {{doid}}::oid
7
+ AND conname={{ name|qtLiteral(conn) }};
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_type_category.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ SELECT
2
+ typcategory
3
+ FROM
4
+ pg_catalog.pg_type
5
+ WHERE typname = {{datatype}};
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/properties.sql ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ c.oid, conname AS name, typname AS relname, nspname, description,
3
+ pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') AS consrc,
4
+ connoinherit, convalidated, convalidated AS convalidated_p
5
+ FROM
6
+ pg_catalog.pg_constraint c
7
+ JOIN
8
+ pg_catalog.pg_type t ON t.oid=contypid
9
+ JOIN
10
+ pg_catalog.pg_namespace nl ON nl.oid=typnamespace
11
+ LEFT OUTER JOIN
12
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
13
+ {% if doid %}
14
+ WHERE
15
+ contype = 'c' AND contypid = {{doid}}::oid
16
+ {% if coid %}
17
+ AND c.oid = {{ coid }}
18
+ {% endif %}
19
+ {% elif coid %}
20
+ WHERE
21
+ c.oid = {{ coid }}
22
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/update.sql ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% set name = o_data.name %}
2
+ {% if data.name %}
3
+ {% set name = data.name %}
4
+ ALTER DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
5
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};{% endif -%}{% if data.convalidated %}
6
+
7
+
8
+ ALTER DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
9
+ VALIDATE CONSTRAINT {{ conn|qtIdent(name) }};{% endif -%}{% if data.description is defined %}
10
+
11
+
12
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(name) }} ON DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
13
+ IS {{ data.description|qtLiteral(conn) }};{% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/coll-domain.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/domain.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.js ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////
2
+ //
3
+ // pgAdmin 4 - PostgreSQL Tools
4
+ //
5
+ // Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ // This software is released under the PostgreSQL Licence
7
+ //
8
+ //////////////////////////////////////////////////////////////
9
+
10
+ import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../static/js/node_ajax';
11
+ import DomainSchema from './domain.ui';
12
+
13
+ // Domain Module: Collection and Node.
14
+ define('pgadmin.node.domain', [
15
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
16
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
17
+ 'pgadmin.browser.collection',
18
+ ], function(
19
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
20
+ ) {
21
+
22
+ // Define Domain Collection Node
23
+ if (!pgBrowser.Nodes['coll-domain']) {
24
+ pgBrowser.Nodes['coll-domain'] =
25
+ pgBrowser.Collection.extend({
26
+ node: 'domain',
27
+ label: gettext('Domains'),
28
+ type: 'coll-domain',
29
+ columns: ['name', 'owner', 'description'],
30
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
31
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
32
+ });
33
+ }
34
+
35
+ // Domain Node
36
+ if (!pgBrowser.Nodes['domain']) {
37
+ pgBrowser.Nodes['domain'] = schemaChild.SchemaChildNode.extend({
38
+ type: 'domain',
39
+ sqlAlterHelp: 'sql-alterdomain.html',
40
+ sqlCreateHelp: 'sql-createdomain.html',
41
+ dialogHelp: url_for('help.static', {'filename': 'domain_dialog.html'}),
42
+ label: gettext('Domain'),
43
+ collection_type: 'coll-domain',
44
+ hasSQL: true,
45
+ hasDepends: true,
46
+ Init: function() {
47
+ // Avoid mulitple registration of menus
48
+ if (this.initialized)
49
+ return;
50
+
51
+ this.initialized = true;
52
+
53
+ pgBrowser.add_menus([{
54
+ name: 'create_domain_on_coll', node: 'coll-domain', module: this,
55
+ applies: ['object', 'context'], callback: 'show_obj_properties',
56
+ category: 'create', priority: 4, label: gettext('Domain...'),
57
+ data: {action: 'create', check: true}, enable: 'canCreate',
58
+ },{
59
+ name: 'create_domain', node: 'domain', module: this,
60
+ applies: ['object', 'context'], callback: 'show_obj_properties',
61
+ category: 'create', priority: 4, label: gettext('Domain...'),
62
+ data: {action: 'create', check: true}, enable: 'canCreate',
63
+ },{
64
+ name: 'create_domain', node: 'schema', module: this,
65
+ applies: ['object', 'context'], callback: 'show_obj_properties',
66
+ category: 'create', priority: 4, label: gettext('Domain...'),
67
+ data: {action: 'create', check: false}, enable: 'canCreate',
68
+ },
69
+ ]);
70
+
71
+ },
72
+
73
+ getSchema: function(treeNodeInfo, itemNodeData) {
74
+ return new DomainSchema(
75
+ {
76
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
77
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {
78
+ cacheLevel: 'database'
79
+ }),
80
+ basetype: ()=>getNodeAjaxOptions('get_types', this, treeNodeInfo, itemNodeData, {
81
+ cacheNode: 'type'
82
+ }),
83
+ collation: ()=>getNodeAjaxOptions('get_collations', this, treeNodeInfo, itemNodeData, {
84
+ cacheLevel: 'database',
85
+ cacheNode: 'schema'
86
+ }),
87
+ },
88
+ {
89
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
90
+ schema: itemNodeData.label,
91
+ basensp: itemNodeData.label,
92
+ }
93
+ );
94
+ },
95
+ });
96
+
97
+ }
98
+
99
+ return pgBrowser.Nodes['domain'];
100
+ });
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui.js ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////
2
+ //
3
+ // pgAdmin 4 - PostgreSQL Tools
4
+ //
5
+ // Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ // This software is released under the PostgreSQL Licence
7
+ //
8
+ //////////////////////////////////////////////////////////////
9
+
10
+ import gettext from 'sources/gettext';
11
+ import BaseUISchema from 'sources/SchemaView/base_schema.ui';
12
+ import SecLabelSchema from '../../../../../static/js/sec_label.ui';
13
+ import { isEmptyString } from 'sources/validators';
14
+ import _ from 'lodash';
15
+
16
+ export class DomainConstSchema extends BaseUISchema {
17
+ constructor() {
18
+ super({
19
+ conoid: undefined,
20
+ conname: undefined,
21
+ consrc: undefined,
22
+ convalidated: true,
23
+ });
24
+ }
25
+
26
+ get idAttribute() {
27
+ return 'conoid';
28
+ }
29
+
30
+ get baseFields() {
31
+ let obj = this;
32
+ return [
33
+ {
34
+ id: 'conname', label: gettext('Name'), cell: 'text', type: 'text',
35
+ }, {
36
+ id: 'consrc', label: gettext('Check'), cell: 'text', type: 'text',
37
+ editable: function(state) {return obj.isNew(state);},
38
+ }, {
39
+ id: 'convalidated', label: gettext('Validate?'), cell: 'checkbox',
40
+ type: 'checkbox',
41
+ readonly: function(state) {
42
+ let currCon = _.find(obj.top.origData.constraints, (con)=>con.conoid == state.conoid);
43
+ return !obj.isNew(state) && currCon.convalidated;
44
+ },
45
+ }
46
+ ];
47
+ }
48
+
49
+ validate(state, setError) {
50
+ if (isEmptyString(state.conname)) {
51
+ setError('conname', 'Constraint Name cannot be empty.');
52
+ return true;
53
+ } else {
54
+ setError('conname', null);
55
+ }
56
+
57
+ if (isEmptyString(state.consrc)) {
58
+ setError('consrc', 'Constraint Check cannot be empty.');
59
+ return true;
60
+ } else {
61
+ setError('consrc', null);
62
+ }
63
+ }
64
+ }
65
+
66
+ export default class DomainSchema extends BaseUISchema {
67
+ constructor(fieldOptions={}, initValues={}) {
68
+ super({
69
+ name: undefined,
70
+ oid: undefined,
71
+ owner: undefined,
72
+ basensp: undefined,
73
+ description: undefined,
74
+ basetype: undefined,
75
+ typlen: undefined,
76
+ precision: undefined,
77
+ typdefault: undefined,
78
+ typnotnull: undefined,
79
+ sysdomain: undefined,
80
+ collname: undefined,
81
+ constraints: [],
82
+ seclabels: [],
83
+ ...initValues,
84
+ });
85
+ this.fieldOptions = {
86
+ role: [],
87
+ schema: [],
88
+ basetype: [],
89
+ collation: [],
90
+ ...fieldOptions,
91
+ };
92
+ }
93
+
94
+ get idAttribute() {
95
+ return 'oid';
96
+ }
97
+
98
+ get baseFields() {
99
+ let obj = this;
100
+ return [
101
+ {
102
+ id: 'name', label: gettext('Name'), cell: 'text',
103
+ type: 'text', mode: ['properties', 'create', 'edit'],
104
+ noEmpty: true,
105
+ }, {
106
+ id: 'oid', label: gettext('OID'), cell: 'text',
107
+ type: 'text' , mode: ['properties'],
108
+ }, {
109
+ id: 'owner', label: gettext('Owner'),
110
+ editable: false, type: 'select', options: this.fieldOptions.role,
111
+ controlProps: { allowClear: false },
112
+ }, {
113
+ id: 'basensp', label: gettext('Schema'),
114
+ editable: false, type: 'select', options: this.fieldOptions.schema,
115
+ controlProps: { allowClear: false },
116
+ mode: ['create', 'edit'],
117
+ }, {
118
+ id: 'sysdomain', label: gettext('System domain?'), cell: 'boolean',
119
+ type: 'switch', mode: ['properties'],
120
+ }, {
121
+ id: 'description', label: gettext('Comment'), cell: 'text',
122
+ type: 'multiline',
123
+ }, {
124
+ id: 'basetype', label: gettext('Base type'),
125
+ type: 'select', options: this.fieldOptions.basetype,
126
+ optionsLoaded: (options) => { obj.type_options = options; },
127
+ mode:['properties', 'create', 'edit'], group: gettext('Definition'),
128
+ readonly: function(state) {return !obj.isNew(state);}, noEmpty: true,
129
+ }, {
130
+ id: 'typlen', label: gettext('Length'), cell: 'text',
131
+ type: 'text', group: gettext('Definition'), deps: ['basetype'],
132
+ readonly: function(state) {return !obj.isNew(state);},
133
+ disabled: function(state) {
134
+ // We will store type from selected from combobox
135
+ let of_type = state.basetype;
136
+ if(obj.type_options) {
137
+ // iterating over all the types
138
+ _.each(obj.type_options, function(o) {
139
+ // if type from selected from combobox matches in options
140
+ if ( of_type == o.value ) {
141
+ // if length is allowed for selected type
142
+ if(o.length) {
143
+ // set the values in model
144
+ state.is_tlength = true;
145
+ state.min_val = o.min_val;
146
+ state.max_val = o.max_val;
147
+ }
148
+ else
149
+ state.is_tlength = false;
150
+ }
151
+ });
152
+
153
+ if(!state.is_tlength) {
154
+ if(state.typlen) {
155
+ state.typlen = null;
156
+ }
157
+ }
158
+ }
159
+ return !state.is_tlength;
160
+ },
161
+ }, {
162
+ id: 'precision', label: gettext('Precision'), cell: 'text',
163
+ type: 'text', group: gettext('Definition'), deps: ['basetype'],
164
+ readonly: function(state) {return !obj.isNew(state);},
165
+ disabled: function(state) {
166
+ // We will store type from selected from combobox
167
+ let of_type = state.basetype;
168
+ if(obj.type_options) {
169
+ // iterating over all the types
170
+ _.each(obj.type_options, function(o) {
171
+ // if type from selected from combobox matches in options
172
+ if ( of_type == o.value ) {
173
+ // if precession is allowed for selected type
174
+ if(o.precision)
175
+ {
176
+ // set the values in model
177
+ state.is_precision = true;
178
+ state.min_val = o.min_val;
179
+ state.max_val = o.max_val;
180
+ }
181
+ else
182
+ state.is_precision = false;
183
+ }
184
+ });
185
+
186
+ if (!state.is_precision) {
187
+ if(state.precision) {
188
+ state.precision = null;
189
+ }
190
+ }
191
+ }
192
+ return !state.is_precision;
193
+ },
194
+ }, {
195
+ id: 'typdefault', label: gettext('Default'), cell: 'text',
196
+ type: 'text', group: gettext('Definition'),
197
+ controlProps: {placeholder: gettext('Enter an expression or a value.')},
198
+ }, {
199
+ id: 'typnotnull', label: gettext('Not NULL?'), cell: 'boolean',
200
+ type: 'switch', group: gettext('Definition'),
201
+ }, {
202
+ id: 'collname', label: gettext('Collation'), cell: 'text',
203
+ type: 'select', group: gettext('Definition'),
204
+ options: this.fieldOptions.collation,
205
+ readonly: function(state) {return !obj.isNew(state);},
206
+ }, {
207
+ id: 'constraints', label: gettext('Constraints'), type: 'collection',
208
+ schema: new DomainConstSchema(),
209
+ editable: false, group: gettext('Constraints'),
210
+ mode: ['edit', 'create'],
211
+ canAdd: true, canEdit: false, canDelete: true,
212
+ uniqueCol : ['conname'],
213
+ }, {
214
+ id: 'seclabels', label: gettext('Security labels'), type: 'collection',
215
+ schema: new SecLabelSchema(),
216
+ editable: false, group: gettext('Security'),
217
+ mode: ['edit', 'create'],
218
+ canAdd: true, canEdit: false, canDelete: true,
219
+ uniqueCol : ['provider'],
220
+ min_version: 90200,
221
+ }
222
+ ];
223
+ }
224
+ }
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/count.sql ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ SELECT COUNT(*)
2
+ FROM
3
+ pg_catalog.pg_type d
4
+ JOIN
5
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
6
+ JOIN
7
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
8
+ WHERE
9
+ d.typnamespace = {{scid}}::oid
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% import 'macros/schemas/security.macros' as SECLABEL %}
2
+ {% if data %}
3
+ CREATE DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
4
+ AS {{ conn|qtTypeIdent(data.basetype) }}{% if data.typlen %}({{data.typlen}}{% if data.precision %},{{data.precision}}{% endif %}){% endif %}{% if data.collname and data.collname != "pg_catalog.\"default\"" %}
5
+
6
+ COLLATE {{ data.collname }}{% endif %}{% if data.typdefault %}
7
+
8
+ DEFAULT {{ data.typdefault }}{% endif %}{% if data.typnotnull %}
9
+
10
+ NOT NULL{% endif %};
11
+
12
+ {% if data.owner %}
13
+ ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }} OWNER TO {{ conn|qtIdent(data.owner) }};{% endif %}
14
+
15
+ {% if data.constraints %}
16
+ {% for c in data.constraints %}{% if c.conname and c.consrc %}
17
+
18
+ ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
19
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
20
+ {% if c.description %}
21
+
22
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
23
+ IS '{{ c.description }}';
24
+ {% endif %}
25
+ {% endfor -%}
26
+ {% endif %}
27
+
28
+ {% if data.description %}
29
+ COMMENT ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
30
+ IS '{{ data.description }}';{% endif -%}
31
+
32
+ {% if data.seclabels %}
33
+ {% for r in data.seclabels %}
34
+ {% if r.label and r.provider %}
35
+
36
+
37
+ {{ SECLABEL.SET(conn, 'DOMAIN', data.name, r.provider, r.label, data.basensp) }}{% endif -%}
38
+ {% endfor -%}
39
+ {% endif -%}
40
+
41
+ {% endif -%}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/delete.sql ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% if scid and doid %}
2
+ SELECT
3
+ d.typname as name, bn.nspname as basensp
4
+ FROM
5
+ pg_catalog.pg_type d
6
+ JOIN
7
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
8
+ WHERE
9
+ d.typnamespace = {{scid}}::oid
10
+ AND
11
+ d.oid={{doid}}::oid;
12
+ {% endif %}
13
+
14
+ {% if name %}
15
+ DROP DOMAIN IF EXISTS {{ conn|qtIdent(basensp, name) }}{% if cascade %} CASCADE{% endif %};
16
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/domain_schema_diff.sql ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% import 'macros/schemas/security.macros' as SECLABEL %}
2
+
3
+ -- WARNING:
4
+ -- We have found the difference in either of datatype or collation,
5
+ -- so we need to drop the existing domain first and re-create it.
6
+ DROP DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }};
7
+
8
+ CREATE DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
9
+ AS {% if data.fulltype %}{{ data.fulltype }}{% else %}{{ o_data.fulltype }}{% endif %}{% if data.collname and data.collname != "pg_catalog.\"default\"" %}
10
+
11
+ COLLATE {{ data.collname }}{% endif %}{% if data.typdefault %}
12
+
13
+ DEFAULT {{ data.typdefault }}{% endif %}{% if data.typnotnull %}
14
+
15
+ NOT NULL{% endif %};
16
+
17
+ {% if data.owner or o_data.owner %}
18
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }} OWNER TO {% if data.owner %}{{ conn|qtIdent(data.owner) }}{% else %}{{ conn|qtIdent(o_data.owner) }}{% endif %};
19
+ {% endif %}
20
+ {% if data.constraints %}
21
+ {% for c in data.constraints.added %}{% if c.conname and c.consrc %}
22
+
23
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
24
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
25
+ {% if c.description %}
26
+
27
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
28
+ IS '{{ c.description }}';
29
+ {% endif %}
30
+ {% endfor -%}
31
+ {% for c in data.constraints.changed %}{% if c.conname and c.consrc %}
32
+
33
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
34
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
35
+ {% if c.description %}
36
+
37
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
38
+ IS '{{ c.description }}';
39
+ {% endif %}
40
+ {% endfor -%}
41
+ {% endif %}
42
+
43
+ {% if data.description %}
44
+ COMMENT ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
45
+ IS '{{ data.description }}';{% endif -%}
46
+
47
+ {% if data.seclabels %}
48
+ {% for r in data.seclabels %}
49
+ {% if r.label and r.provider %}
50
+
51
+
52
+ {{ SECLABEL.SET(conn, 'DOMAIN', data.name, r.provider, r.label, data.basensp) }}{% endif -%}
53
+ {% endfor -%}
54
+ {% endif -%}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_collations.sql ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT --nspname, collname,
2
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
3
+ pg_catalog.concat(nspname, '."', collname,'"')
4
+ ELSE '' END AS copy_collation
5
+ FROM
6
+ pg_catalog.pg_collation c, pg_catalog.pg_namespace n
7
+ WHERE
8
+ c.collnamespace=n.oid
9
+ ORDER BY
10
+ nspname, collname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_constraints.sql ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ 'DOMAIN' AS objectkind, c.oid as conoid, conname, typname as relname, nspname, description,
3
+ pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') as consrc, connoinherit, convalidated
4
+ FROM
5
+ pg_catalog.pg_constraint c
6
+ JOIN
7
+ pg_catalog.pg_type t ON t.oid=contypid
8
+ JOIN
9
+ pg_catalog.pg_namespace nl ON nl.oid=typnamespace
10
+ LEFT OUTER JOIN
11
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
12
+ WHERE
13
+ contype = 'c' AND contypid = {{doid}}::oid
14
+ ORDER BY
15
+ conname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_oid.sql ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% if doid %}
2
+ SELECT
3
+ d.typnamespace as scid
4
+ FROM
5
+ pg_catalog.pg_type d
6
+ WHERE
7
+ d.oid={{ doid }}::oid;
8
+ {% else %}
9
+ SELECT
10
+ d.oid
11
+ FROM
12
+ pg_catalog.pg_type d
13
+ JOIN
14
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
15
+ WHERE
16
+ bn.nspname = {{ basensp|qtLiteral(conn) }}
17
+ AND d.typname={{ name|qtLiteral(conn) }};
18
+ {% endif %}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/node.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ d.oid, d.typname as name, pg_catalog.pg_get_userbyid(d.typowner) as owner,
3
+ bn.nspname as basensp, des.description
4
+ FROM
5
+ pg_catalog.pg_type d
6
+ JOIN
7
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
8
+ JOIN
9
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
10
+ LEFT OUTER JOIN
11
+ pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
12
+ {% if scid is defined %}
13
+ WHERE
14
+ d.typnamespace = {{scid}}::oid
15
+ {% elif doid %}
16
+ WHERE d.oid = {{doid}}::oid
17
+ {% endif %}
18
+ {% if schema_diff %}
19
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
20
+ WHERE objid = d.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
21
+ {% endif %}
22
+ ORDER BY
23
+ d.typname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/properties.sql ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SELECT
2
+ d.oid, d.typname as name, d.typbasetype, pg_catalog.format_type(b.oid,NULL) as basetype, pg_catalog.pg_get_userbyid(d.typowner) as owner,
3
+ c.oid AS colloid, pg_catalog.format_type(b.oid, d.typtypmod) AS fulltype,
4
+ CASE WHEN length(cn.nspname::text) > 0 AND length(c.collname::text) > 0 THEN
5
+ pg_catalog.concat(cn.nspname, '."', c.collname,'"')
6
+ ELSE '' END AS collname,
7
+ d.typtypmod, d.typnotnull, d.typdefault, d.typndims, d.typdelim, bn.nspname as basensp,
8
+ description, (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=d.typname) > 1 AS domisdup,
9
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t3 WHERE t3.typname=b.typname) > 1 AS baseisdup,
10
+ (SELECT
11
+ pg_catalog.array_agg(provider || '=' || label)
12
+ FROM
13
+ pg_catalog.pg_seclabel sl1
14
+ WHERE
15
+ sl1.objoid=d.oid) AS seclabels
16
+ FROM
17
+ pg_catalog.pg_type d
18
+ JOIN
19
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
20
+ JOIN
21
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
22
+ LEFT OUTER JOIN
23
+ pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
24
+ LEFT OUTER JOIN
25
+ pg_catalog.pg_collation c ON d.typcollation=c.oid
26
+ LEFT OUTER JOIN
27
+ pg_catalog.pg_namespace cn ON c.collnamespace=cn.oid
28
+ WHERE
29
+ d.typnamespace = {{scid}}::oid
30
+ {% if doid %}
31
+ AND d.oid={{doid}}::oid
32
+ {% endif %}
33
+ ORDER BY
34
+ d.typname;
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/update.sql ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% import 'macros/schemas/security.macros' as SECLABEL %}
2
+ {% if data %}
3
+ {% set name = o_data.name %}
4
+ {% if data.name %}
5
+ {% if data.name != o_data.name %}
6
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
7
+ RENAME TO {{ conn|qtIdent(data.name) }};
8
+ {% set name = data.name %}
9
+ {% endif %}
10
+ {% endif -%}
11
+ {% if data.typnotnull and not o_data.typnotnull %}
12
+
13
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
14
+ SET NOT NULL;
15
+ {% elif 'typnotnull' in data and not data.typnotnull and o_data.typnotnull%}
16
+
17
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
18
+ DROP NOT NULL;
19
+ {% endif -%}{% if data.typdefault %}
20
+
21
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
22
+ SET DEFAULT {{ data.typdefault }};
23
+ {% elif (data.typdefault == '' or data.typdefault == None) and data.typdefault != o_data.typdefault %}
24
+
25
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
26
+ DROP DEFAULT;
27
+ {% endif -%}{% if data.owner %}
28
+
29
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
30
+ OWNER TO {{ conn|qtIdent(data.owner) }};
31
+ {% endif -%}{% if data.constraints %}
32
+ {% for c in data.constraints.deleted %}
33
+
34
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
35
+ DROP CONSTRAINT {{ conn|qtIdent(o_data['constraints'][c.conoid]['conname']) }};
36
+ {% endfor -%}
37
+ {% if data.is_schema_diff is defined and data.is_schema_diff %}
38
+ {% for c in data.constraints.changed %}
39
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
40
+ DROP CONSTRAINT {{ conn|qtIdent(c.conname) }};
41
+
42
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
43
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif -%};
44
+
45
+ {% if c.description is defined and c.description != '' %}
46
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
47
+ IS {{ c.description|qtLiteral(conn) }};{% endif %}
48
+ {% endfor -%}
49
+ {% else %}
50
+ {% for c in data.constraints.changed %}
51
+ {% if c.conname and c.conname !=o_data['constraints'][c.conoid]['conname'] %}
52
+
53
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
54
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data['constraints'][c.conoid]['conname']) }} TO {{ conn|qtIdent(c.conname) }};
55
+ {% endif %}
56
+ {% if c.convalidated and not o_data['constraints'][c.conoid]['convalidated'] %}
57
+
58
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
59
+ VALIDATE CONSTRAINT {{ conn|qtIdent(c.conname) }};
60
+ {% endif %}
61
+ {% endfor -%}
62
+ {% endif %}
63
+ {% for c in data.constraints.added %}
64
+ {% if c.conname and c.consrc %}
65
+
66
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
67
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif -%};{% endif -%}
68
+
69
+ {% if c.description %}
70
+
71
+ COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
72
+ IS '{{ c.description }}';
73
+ {% endif %}
74
+ {% endfor -%}{% endif -%}
75
+ {% set seclabels = data.seclabels %}
76
+ {% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
77
+ {% for r in seclabels.deleted %}
78
+ {{ SECLABEL.UNSET(conn, 'DOMAIN', name, r.provider, o_data.basensp) }}
79
+
80
+ {% endfor %}
81
+ {% endif -%}
82
+ {% if 'added' in seclabels and seclabels.added|length > 0 %}
83
+ {% for r in seclabels.added %}
84
+
85
+ {{ SECLABEL.SET(conn, 'DOMAIN', name, r.provider, r.label, o_data.basensp) }}
86
+ {% endfor %}
87
+ {% endif -%}{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
88
+ {% for r in seclabels.changed %}
89
+
90
+ {{ SECLABEL.SET(conn, 'DOMAIN', name, r.provider, r.label, o_data.basensp) }}
91
+ {% endfor %}
92
+ {% endif -%}{% if data.description is defined and data.description != o_data.description %}
93
+
94
+ COMMENT ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
95
+ IS {{ data.description|qtLiteral(conn) }};
96
+ {% endif -%}{% if data.basensp %}
97
+
98
+ ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
99
+ SET SCHEMA {{ conn|qtIdent(data.basensp) }};{% endif -%}
100
+ {% endif -%}
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py ADDED
@@ -0,0 +1,1942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """Implements the Foreign Table Module."""
11
+
12
+ import sys
13
+ import re
14
+ from functools import wraps
15
+
16
+ import json
17
+ from flask import render_template, request, jsonify, \
18
+ current_app
19
+ from flask_babel import gettext
20
+
21
+ from pgadmin.browser.server_groups.servers import databases
22
+ from config import PG_DEFAULT_DRIVER
23
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
24
+ SchemaChildModule, DataTypeReader
25
+ from pgadmin.browser.server_groups.servers.databases.utils import \
26
+ parse_sec_labels_from_db
27
+ from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
28
+ parse_priv_to_db
29
+ from pgadmin.browser.utils import PGChildNodeView
30
+ from pgadmin.utils.ajax import make_json_response, internal_server_error, \
31
+ make_response as ajax_response, gone
32
+ from pgadmin.utils.compile_template_name import compile_template_path
33
+ from pgadmin.utils.driver import get_driver
34
+ from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
35
+ from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
36
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
37
+ columns import utils as column_utils
38
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
39
+ triggers import utils as trigger_utils
40
+
41
+
42
+ class ForeignTableModule(SchemaChildModule):
43
+ """
44
+ class ForeignTableModule(CollectionNodeModule):
45
+
46
+ This class represents The Foreign Table Module.
47
+
48
+ Methods:
49
+ -------
50
+ * __init__(*args, **kwargs)
51
+ - Initialize the Foreign Table Module.
52
+
53
+ * get_nodes(gid, sid, did, scid)
54
+ - Generate the Foreign Table collection node.
55
+
56
+ * node_inode():
57
+ - Override this property to make the Foreign Table node as leaf node.
58
+
59
+ * script_load()
60
+ - Load the module script for Foreign Table, when schema node is
61
+ initialized.
62
+ """
63
+ _NODE_TYPE = 'foreign_table'
64
+ _COLLECTION_LABEL = gettext("Foreign Tables")
65
+
66
+ def __init__(self, *args, **kwargs):
67
+ super().__init__(*args, **kwargs)
68
+ self.min_ver = None
69
+ self.max_ver = None
70
+
71
+ def get_nodes(self, gid, sid, did, scid):
72
+ """
73
+ Generate the Foreign Table collection node.
74
+ """
75
+ if self.has_nodes(
76
+ sid, did, scid,
77
+ base_template_path=ForeignTableView.BASE_TEMPLATE_PATH):
78
+ yield self.generate_browser_collection_node(scid)
79
+
80
+ @property
81
+ def script_load(self):
82
+ """
83
+ Load the module script for foreign table, when the
84
+ schema node is initialized.
85
+ """
86
+ return databases.DatabaseModule.node_type
87
+
88
+ def register(self, app, options):
89
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
90
+ tables.triggers import blueprint as module
91
+ self.submodules.append(module)
92
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
93
+ constraints import blueprint as module
94
+ self.submodules.append(module)
95
+ from pgadmin.browser.server_groups.servers.databases.schemas. \
96
+ foreign_tables.foreign_table_columns import \
97
+ foreign_table_column_blueprint as module
98
+ self.submodules.append(module)
99
+ super().register(app, options)
100
+
101
+
102
+ blueprint = ForeignTableModule(__name__)
103
+
104
+
105
+ class ForeignTableView(PGChildNodeView, DataTypeReader,
106
+ SchemaDiffObjectCompare):
107
+ """
108
+ class ForeignTableView(PGChildNodeView)
109
+
110
+ This class inherits PGChildNodeView to get the different routes for
111
+ the module.
112
+
113
+ The class is responsible to Create, Read, Update and Delete operations for
114
+ the Foreign Table.
115
+
116
+ Methods:
117
+ -------
118
+ * validate_request(f):
119
+ - Works as a decorator.
120
+ Validating request on the request of create, update and modified SQL.
121
+
122
+ * check_precondition(f):
123
+ - Works as a decorator.
124
+ - Checks database connection status.
125
+ - Attach connection object and template path.
126
+
127
+ * list(gid, sid, did, scid):
128
+ - List the Foreign Table.
129
+
130
+ * nodes(gid, sid, did, scid):
131
+ - Returns all the Foreign Table to generate Nodes in the browser.
132
+
133
+ * properties(gid, sid, did, scid, foid):
134
+ - Returns the Foreign Table properties.
135
+
136
+ * get_collations(gid, sid, did, scid, foid=None):
137
+ - Returns Collations.
138
+
139
+ * get_types(gid, sid, did, scid, foid=None):
140
+ - Returns Data Types.
141
+
142
+ * get_foreign_servers(gid, sid, did, scid, foid=None):
143
+ - Returns the Foreign Servers.
144
+
145
+ * get_tables(gid, sid, did, scid, foid=None):
146
+ - Returns the Foreign Tables as well as Plain Tables.
147
+
148
+ * get_columns(gid, sid, did, scid, foid=None):
149
+ - Returns the Table Columns.
150
+
151
+ * create(gid, sid, did, scid):
152
+ - Creates a new Foreign Table object.
153
+
154
+ * update(gid, sid, did, scid, foid):
155
+ - Updates the Foreign Table object.
156
+
157
+ * delete(gid, sid, did, scid, foid):
158
+ - Drops the Foreign Table object.
159
+
160
+ * sql(gid, sid, did, scid, foid):
161
+ - Returns the SQL for the Foreign Table object.
162
+
163
+ * msql(gid, sid, did, scid, foid=None):
164
+ - Returns the modified SQL.
165
+
166
+ * get_sql(gid, sid, data, scid, foid=None):
167
+ - Generates the SQL statements to create/update the Foreign Table object.
168
+
169
+ * dependents(gid, sid, did, scid, foid):
170
+ - Returns the dependents for the Foreign Table object.
171
+
172
+ * dependencies(gid, sid, did, scid, foid):
173
+ - Returns the dependencies for the Foreign Table object.
174
+
175
+ * select_sql(gid, sid, did, scid, foid):
176
+ - Returns sql for Script
177
+
178
+ * insert_sql(gid, sid, did, scid, foid):
179
+ - Returns sql for Script
180
+
181
+ * update_sql(gid, sid, did, scid, foid):
182
+ - Returns sql for Script
183
+
184
+ * delete_sql(gid, sid, did, scid, foid):
185
+ - Returns sql for Script
186
+
187
+ * compare(**kwargs):
188
+ - This function will compare the foreign table nodes from two different
189
+ schemas.
190
+ """
191
+
192
+ node_type = blueprint.node_type
193
+ node_label = "Foreign Table"
194
+ BASE_TEMPLATE_PATH = 'foreign_tables/sql/#{0}#'
195
+ double_newline = '\n\n'
196
+ pattern = '\n{2,}'
197
+
198
+ parent_ids = [
199
+ {'type': 'int', 'id': 'gid'},
200
+ {'type': 'int', 'id': 'sid'},
201
+ {'type': 'int', 'id': 'did'},
202
+ {'type': 'int', 'id': 'scid'}
203
+ ]
204
+ ids = [
205
+ {'type': 'int', 'id': 'foid'}
206
+ ]
207
+
208
+ operations = dict({
209
+ 'obj': [
210
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
211
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
212
+ ],
213
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
214
+ 'children': [{'get': 'children'}],
215
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
216
+ 'sql': [{'get': 'sql'}],
217
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
218
+ 'stats': [{'get': 'statistics'}],
219
+ 'dependency': [{'get': 'dependencies'}],
220
+ 'dependent': [{'get': 'dependents'}],
221
+ 'get_collations': [
222
+ {'get': 'get_collations'},
223
+ {'get': 'get_collations'}
224
+ ],
225
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
226
+ 'get_foreign_servers': [{'get': 'get_foreign_servers'},
227
+ {'get': 'get_foreign_servers'}],
228
+ 'get_tables': [{'get': 'get_tables'}, {'get': 'get_tables'}],
229
+ 'set_trigger': [{'put': 'enable_disable_triggers'}],
230
+ 'get_columns': [{'get': 'get_columns'}, {'get': 'get_columns'}],
231
+ 'select_sql': [{'get': 'select_sql'}],
232
+ 'insert_sql': [{'get': 'insert_sql'}],
233
+ 'update_sql': [{'get': 'update_sql'}],
234
+ 'delete_sql': [{'get': 'delete_sql'}],
235
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
236
+ })
237
+
238
+ keys_to_ignore = ['oid', 'basensp', 'oid-2', 'attnum', 'strftoptions']
239
+
240
+ def validate_request(f):
241
+ """
242
+ Works as a decorator.
243
+ Validating request on the request of create, update and modified SQL.
244
+
245
+ Required Args:
246
+ name: Name of the Foreign Table
247
+ ftsrvname: Foreign Server Name
248
+
249
+ Above both the arguments will not be validated in the update action.
250
+ """
251
+
252
+ @wraps(f)
253
+ def wrap(self, **kwargs):
254
+
255
+ if request.data:
256
+ req = json.loads(request.data)
257
+ else:
258
+ req = request.args or request.form
259
+
260
+ invalid, arg = self._check_valid_foid_input(kwargs, req)
261
+
262
+ if invalid:
263
+ return make_json_response(
264
+ status=410,
265
+ success=0,
266
+ errormsg=gettext(
267
+ "Could not find the required parameter ({})."
268
+ ).format(arg)
269
+ )
270
+
271
+ try:
272
+ if request.method == 'GET':
273
+ list_params = ['constraints', 'columns', 'ftoptions',
274
+ 'seclabels', 'inherits', 'acl']
275
+ else:
276
+ list_params = ['inherits']
277
+
278
+ data = self._validate_req(req, list_params)
279
+
280
+ except Exception as e:
281
+ return internal_server_error(errormsg=str(e))
282
+
283
+ self.request = data
284
+ return f(self, **kwargs)
285
+
286
+ return wrap
287
+
288
+ @staticmethod
289
+ def _check_valid_foid_input(kwargs, req):
290
+
291
+ """
292
+ check for valid Foreign Table id
293
+ :param kwargs: user input
294
+ :param req: request object
295
+ """
296
+
297
+ if 'foid' not in kwargs:
298
+ required_args = [
299
+ 'name',
300
+ 'ftsrvname'
301
+ ]
302
+
303
+ for arg in required_args:
304
+ if arg not in req or req[arg] == '':
305
+ return True, arg
306
+ return False, ''
307
+
308
+ def _validate_req(self, req, list_params):
309
+
310
+ """
311
+ Validate & convert the string to desired output format
312
+ :param req: request data
313
+ :param list_params: prepared list of inherit, constraints, etc.
314
+ :return: data
315
+ """
316
+
317
+ data = {}
318
+
319
+ try:
320
+ for key in req:
321
+ if (
322
+ key in list_params and req[key] != '' and
323
+ req[key] is not None
324
+ ):
325
+ # Coverts string into python list as expected.
326
+ data[key] = []
327
+ self._convert_string_to_list(req, data, key)
328
+
329
+ elif key == 'typnotnull':
330
+ if req[key] == 'true' or req[key] is True:
331
+ data[key] = True
332
+ elif req[key] == 'false' or req[key] is False:
333
+ data[key] = False
334
+ else:
335
+ data[key] = ''
336
+ else:
337
+ data[key] = req[key]
338
+
339
+ except Exception as e:
340
+ current_app.logger.exception(e)
341
+ raise e
342
+
343
+ return data
344
+
345
+ def _convert_string_to_list(self, req, data, key):
346
+
347
+ """
348
+ Convert the string with utf-8 base to list
349
+ :param req: request data
350
+ :param data: output
351
+ :param key: index for data
352
+ """
353
+
354
+ if not isinstance(req[key], list) and req[key]:
355
+ data[key] = json.loads(req[key])
356
+ elif req[key]:
357
+ data[key] = req[key]
358
+
359
+ if key == 'inherits':
360
+ # Convert Table ids from unicode/string to int
361
+ # and make tuple for 'IN' query.
362
+ inherits = tuple([int(x) for x in data[key]])
363
+
364
+ if len(inherits) == 1:
365
+ # Python tupple has , after the first param
366
+ # in case of single parameter.
367
+ # So, we need to make it tuple explicitly.
368
+ inherits = "(" + str(inherits[0]) + ")"
369
+ if inherits:
370
+ # Fetch Table Names from their respective Ids,
371
+ # as we need Table names to generate the SQL.
372
+ SQL = render_template(
373
+ "/".join([self.template_path,
374
+ self._GET_TABLES_SQL]),
375
+ attrelid=inherits)
376
+ status, res = self.conn.execute_dict(SQL)
377
+
378
+ if not status:
379
+ return internal_server_error(errormsg=res)
380
+
381
+ if 'inherits' in res['rows'][0]:
382
+ data[key] = res['rows'][0]['inherits']
383
+ else:
384
+ data[key] = []
385
+
386
+ def check_precondition(f):
387
+ """
388
+ Works as a decorator.
389
+ Checks the database connection status.
390
+ Attaches the connection object and template path to the class object.
391
+ """
392
+
393
+ @wraps(f)
394
+ def wrap(*args, **kwargs):
395
+ self = args[0]
396
+ driver = get_driver(PG_DEFAULT_DRIVER)
397
+ self.manager = driver.connection_manager(kwargs['sid'])
398
+
399
+ # Get database connection
400
+ self.conn = self.manager.connection(did=kwargs['did'])
401
+ self.qtIdent = driver.qtIdent
402
+ self.datistemplate = \
403
+ self.manager.db_info[kwargs['did']]['datistemplate'] \
404
+ if self.manager.db_info is not None and \
405
+ kwargs['did'] in self.manager.db_info else False
406
+
407
+ # Set template path for sql scripts depending
408
+ # on the server version.
409
+ self.template_path = \
410
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
411
+
412
+ self.foreign_table_column_template_path = compile_template_path(
413
+ 'foreign_table_columns/sql', self.manager.version)
414
+
415
+ self.column_template_path = compile_template_path(
416
+ 'columns/sql', self.manager.version)
417
+
418
+ # Template for trigger node
419
+ self.trigger_template_path = \
420
+ 'triggers/sql/{0}/#{1}#'.format(self.manager.server_type,
421
+ self.manager.version)
422
+
423
+ return f(*args, **kwargs)
424
+
425
+ return wrap
426
+
427
+ @check_precondition
428
+ def list(self, gid, sid, did, scid):
429
+ """
430
+ List all the Foreign Tables.
431
+
432
+ Args:
433
+ gid: Server Group Id
434
+ sid: Server Id
435
+ did: Database Id
436
+ scid: Schema Id
437
+ """
438
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
439
+ scid=scid)
440
+ status, res = self.conn.execute_dict(SQL)
441
+
442
+ if not status:
443
+ return internal_server_error(errormsg=res)
444
+ return ajax_response(
445
+ response=res['rows'],
446
+ status=200
447
+ )
448
+
449
+ @check_precondition
450
+ def nodes(self, gid, sid, did, scid):
451
+ """
452
+ Returns the Foreign Tables to generate the Nodes.
453
+
454
+ Args:
455
+ gid: Server Group Id
456
+ sid: Server Id
457
+ did: Database Id
458
+ scid: Schema Id
459
+ """
460
+
461
+ res = []
462
+ SQL = render_template("/".join([self.template_path,
463
+ self._NODE_SQL]), scid=scid)
464
+ status, rset = self.conn.execute_2darray(SQL)
465
+
466
+ if not status:
467
+ return internal_server_error(errormsg=rset)
468
+
469
+ for row in rset['rows']:
470
+ res.append(
471
+ self.blueprint.generate_browser_node(
472
+ row['oid'],
473
+ scid,
474
+ row['name'],
475
+ icon="icon-foreign_table",
476
+ description=row['description'],
477
+ tigger_count=row['triggercount'],
478
+ has_enable_triggers=row['has_enable_triggers'],
479
+ ))
480
+
481
+ return make_json_response(
482
+ data=res,
483
+ status=200
484
+ )
485
+
486
+ @check_precondition
487
+ def node(self, gid, sid, did, scid, foid):
488
+ """
489
+ Returns the Foreign Tables to generate the Nodes.
490
+
491
+ Args:
492
+ gid: Server Group Id
493
+ sid: Server Id
494
+ did: Database Id
495
+ scid: Schema Id
496
+ foid: Foreign Table Id
497
+ """
498
+
499
+ SQL = render_template("/".join([self.template_path,
500
+ self._NODE_SQL]), foid=foid)
501
+ status, rset = self.conn.execute_2darray(SQL)
502
+
503
+ if not status:
504
+ return internal_server_error(errormsg=rset)
505
+
506
+ for row in rset['rows']:
507
+ return make_json_response(
508
+ data=self.blueprint.generate_browser_node(
509
+ row['oid'],
510
+ scid,
511
+ row['name'],
512
+ icon="icon-foreign_table"
513
+ ),
514
+ status=200
515
+ )
516
+
517
+ return gone(self.not_found_error_msg())
518
+
519
+ @check_precondition
520
+ def properties(self, gid, sid, did, scid, foid):
521
+ """
522
+ Returns the Foreign Table properties.
523
+
524
+ Args:
525
+ gid: Server Group Id
526
+ sid: Server Id
527
+ did: Database Id
528
+ scid: Schema Id
529
+ foid: Foreign Table Id
530
+ """
531
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
532
+ if not status:
533
+ return data
534
+ if not data:
535
+ return gone(self.not_found_error_msg())
536
+
537
+ return ajax_response(
538
+ response=data,
539
+ status=200
540
+ )
541
+
542
+ @check_precondition
543
+ def get_collations(self, gid, sid, did, scid, foid=None):
544
+ """
545
+ Returns the Collations.
546
+
547
+ Args:
548
+ gid: Server Group Id
549
+ sid: Server Id
550
+ did: Database Id
551
+ scid: Schema Id
552
+ foid: Foreign Table Id
553
+ """
554
+
555
+ res = [{'label': '', 'value': ''}]
556
+ try:
557
+ SQL = render_template("/".join([self.template_path,
558
+ 'get_collations.sql']))
559
+ status, rset = self.conn.execute_2darray(SQL)
560
+ if not status:
561
+ return internal_server_error(errormsg=res)
562
+
563
+ for row in rset['rows']:
564
+ res.append(
565
+ {'label': row['copy_collation'],
566
+ 'value': row['copy_collation']}
567
+ )
568
+
569
+ return make_json_response(
570
+ data=res,
571
+ status=200
572
+ )
573
+
574
+ except Exception as e:
575
+ return internal_server_error(errormsg=str(e))
576
+
577
+ @check_precondition
578
+ def types(self, gid, sid, did, scid, foid=None):
579
+ """
580
+ Returns the Data Types.
581
+
582
+ Args:
583
+ gid: Server Group Id
584
+ sid: Server Id
585
+ did: Database Id
586
+ scid: Schema Id
587
+ foid: Foreign Table Id
588
+ """
589
+
590
+ condition = render_template("/".join(
591
+ [self.template_path, 'types_condition.sql']),
592
+ server_type=self.manager.server_type,
593
+ show_sys_objects=self.blueprint.show_system_objects)
594
+
595
+ # Get Types
596
+ status, types = self.get_types(self.conn, condition)
597
+
598
+ if not status:
599
+ return internal_server_error(errormsg=types)
600
+
601
+ return make_json_response(
602
+ data=types,
603
+ status=200
604
+ )
605
+
606
+ @check_precondition
607
+ def get_foreign_servers(self, gid, sid, did, scid, foid=None):
608
+ """
609
+ Returns the Foreign Servers.
610
+
611
+ Args:
612
+ gid: Server Group Id
613
+ sid: Server Id
614
+ did: Database Id
615
+ scid: Schema Id
616
+ foid: Foreign Table Id
617
+ """
618
+ res = [{'label': '', 'value': ''}]
619
+ try:
620
+ SQL = render_template("/".join([self.template_path,
621
+ 'get_foreign_servers.sql']))
622
+ status, rset = self.conn.execute_2darray(SQL)
623
+ if not status:
624
+ return internal_server_error(errormsg=res)
625
+
626
+ for row in rset['rows']:
627
+ res.append(
628
+ {'label': row['srvname'], 'value': row['srvname']}
629
+ )
630
+ return make_json_response(
631
+ data=res,
632
+ status=200
633
+ )
634
+
635
+ except Exception as e:
636
+ return internal_server_error(errormsg=str(e))
637
+
638
+ @check_precondition
639
+ def get_tables(self, gid, sid, did, scid, foid=None):
640
+ """
641
+ Returns the Foreign Tables as well as Plain Tables.
642
+
643
+ Args:
644
+ gid: Server Group Id
645
+ sid: Server Id
646
+ did: Database Id
647
+ scid: Schema Id
648
+ foid: Foreign Table Id
649
+ """
650
+ res = []
651
+ try:
652
+ SQL = render_template("/".join(
653
+ [self.template_path, self._GET_TABLES_SQL]),
654
+ foid=foid, server_type=self.manager.server_type,
655
+ show_sys_objects=self.blueprint.show_system_objects)
656
+ status, rset = self.conn.execute_dict(SQL)
657
+ if not status:
658
+ return internal_server_error(errormsg=res)
659
+
660
+ return make_json_response(
661
+ data=rset['rows'],
662
+ status=200
663
+ )
664
+
665
+ except Exception:
666
+ _, exc_value, _ = sys.exc_info()
667
+ return internal_server_error(errormsg=str(exc_value))
668
+
669
+ @check_precondition
670
+ def get_columns(self, gid, sid, did, scid, foid=None):
671
+ """
672
+ Returns the Table Columns.
673
+
674
+ Args:
675
+ gid: Server Group Id
676
+ sid: Server Id
677
+ did: Database Id
678
+ scid: Schema Id
679
+ foid: Foreign Table Id
680
+ attrelid: Table oid
681
+
682
+ Returns:
683
+ JSON Array with below parameters.
684
+ attname: Column Name
685
+ datatype: Column Data Type
686
+ inherited_from: Parent Table from which the related column
687
+ is inheritted.
688
+ """
689
+ res = []
690
+ data = request.args if request.args else None
691
+ try:
692
+ if data and 'attrelid' in data:
693
+ SQL = render_template("/".join([self.template_path,
694
+ 'get_table_columns.sql']),
695
+ attrelid=data['attrelid'])
696
+ status, res = self.conn.execute_dict(SQL)
697
+
698
+ if not status:
699
+ return internal_server_error(errormsg=res)
700
+ return make_json_response(
701
+ data=res['rows'],
702
+ status=200
703
+ )
704
+ except Exception:
705
+ _, exc_value, _ = sys.exc_info()
706
+ return internal_server_error(errormsg=str(exc_value))
707
+
708
+ @check_precondition
709
+ @validate_request
710
+ def create(self, gid, sid, did, scid):
711
+ """
712
+ Creates a new Foreign Table object.
713
+
714
+ Args:
715
+ gid: Server Group Id
716
+ sid: Server Id
717
+ did: Database Id
718
+ scid: Schema Id
719
+ foid: Foreign Table Id
720
+ name: Foreign Table Name
721
+ basensp: Schema Name
722
+ ftsrvname: Foreign Server Name
723
+
724
+ Returns:
725
+ Foreign Table object in json format.
726
+ """
727
+ try:
728
+ # Get SQL to create Foreign Table
729
+ SQL, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
730
+ data=self.request)
731
+ # Most probably this is due to error
732
+ if not isinstance(SQL, str):
733
+ return SQL
734
+
735
+ status, res = self.conn.execute_scalar(SQL)
736
+ if not status:
737
+ return internal_server_error(errormsg=res)
738
+
739
+ # Need oid to add object in the tree at browser.
740
+ basensp = self.request['basensp'] if ('basensp' in self.request) \
741
+ else None
742
+ SQL = render_template("/".join([self.template_path,
743
+ self._OID_SQL]),
744
+ basensp=basensp,
745
+ name=self.request['name'],
746
+ conn=self.conn)
747
+ status, res = self.conn.execute_2darray(SQL)
748
+ if not status:
749
+ return internal_server_error(errormsg=res)
750
+
751
+ foid = res['rows'][0]['oid']
752
+ scid = res['rows'][0]['scid']
753
+
754
+ return jsonify(
755
+ node=self.blueprint.generate_browser_node(
756
+ foid,
757
+ scid,
758
+ self.request['name'],
759
+ icon="icon-foreign_table"
760
+ )
761
+ )
762
+ except Exception as e:
763
+ return internal_server_error(errormsg=str(e))
764
+
765
+ @check_precondition
766
+ def delete(self, gid, sid, did, scid, foid=None, only_sql=False):
767
+ """
768
+ Drops the Foreign Table.
769
+
770
+ Args:
771
+ gid: Server Group Id
772
+ sid: Server Id
773
+ did: Database Id
774
+ scid: Schema Id
775
+ foid: Foreign Table Id
776
+ only_sql: Return only sql if True
777
+ """
778
+ if foid is None:
779
+ data = request.form if request.form else json.loads(
780
+ request.data
781
+ )
782
+ else:
783
+ data = {'ids': [foid]}
784
+
785
+ cascade = self._check_cascade_operation()
786
+
787
+ try:
788
+ for foid in data['ids']:
789
+ # Fetch Name and Schema Name to delete the foreign table.
790
+ SQL = render_template("/".join([self.template_path,
791
+ self._DELETE_SQL]), scid=scid,
792
+ foid=foid)
793
+ status, res = self.conn.execute_2darray(SQL)
794
+ if not status:
795
+ return internal_server_error(errormsg=res)
796
+ elif not res['rows']:
797
+ return make_json_response(
798
+ success=0,
799
+ errormsg=gettext(
800
+ 'Error: Object not found.'
801
+ ),
802
+ info=self.not_found_error_msg()
803
+ )
804
+
805
+ name = res['rows'][0]['name']
806
+ basensp = res['rows'][0]['basensp']
807
+
808
+ SQL = render_template("/".join([self.template_path,
809
+ self._DELETE_SQL]),
810
+ name=name,
811
+ basensp=basensp,
812
+ cascade=cascade)
813
+
814
+ # Used for schema diff tool
815
+ if only_sql:
816
+ return SQL
817
+
818
+ status, res = self.conn.execute_scalar(SQL)
819
+ if not status:
820
+ return internal_server_error(errormsg=res)
821
+
822
+ return make_json_response(
823
+ success=1,
824
+ info=gettext("Foreign Table dropped")
825
+ )
826
+
827
+ except Exception as e:
828
+ return internal_server_error(errormsg=str(e))
829
+
830
+ @check_precondition
831
+ @validate_request
832
+ def update(self, gid, sid, did, scid, foid):
833
+ """
834
+ Updates the Foreign Table.
835
+
836
+ Args:
837
+ gid: Server Group Id
838
+ sid: Server Id
839
+ did: Database Id
840
+ scid: Schema Id
841
+ foid: Foreign Table Id
842
+ """
843
+
844
+ try:
845
+ SQL, name = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
846
+ data=self.request, foid=foid)
847
+ # Most probably this is due to error
848
+ if not isinstance(SQL, str):
849
+ return SQL
850
+
851
+ SQL = SQL.strip('\n').strip(' ')
852
+ status, res = self.conn.execute_scalar(SQL)
853
+ if not status:
854
+ return internal_server_error(errormsg=res)
855
+
856
+ SQL = render_template("/".join([self.template_path,
857
+ self._OID_SQL]),
858
+ foid=foid,
859
+ conn=self.conn)
860
+ status, res = self.conn.execute_2darray(SQL)
861
+ if not status:
862
+ return internal_server_error(errormsg=res)
863
+
864
+ scid = res['rows'][0]['scid']
865
+
866
+ other_node_info = {}
867
+ if 'description' in self.request:
868
+ other_node_info['description'] = self.request['description']
869
+
870
+ return jsonify(
871
+ node=self.blueprint.generate_browser_node(
872
+ foid,
873
+ scid,
874
+ name,
875
+ icon="icon-%s" % self.node_type,
876
+ **other_node_info
877
+ )
878
+ )
879
+ except Exception as e:
880
+ return internal_server_error(errormsg=str(e))
881
+
882
+ @check_precondition
883
+ def sql(self, gid, sid, did, scid, foid=None, **kwargs):
884
+ """
885
+ Returns the SQL for the Foreign Table object.
886
+
887
+ Args:
888
+ gid: Server Group Id
889
+ sid: Server Id
890
+ did: Database Id
891
+ scid: Schema Id
892
+ foid: Foreign Table Id
893
+ json_resp: True then return json response
894
+ """
895
+ json_resp = kwargs.get('json_resp', True)
896
+ target_schema = kwargs.get('target_schema', None)
897
+
898
+ status, data = self._fetch_properties(gid, sid, did, scid, foid,
899
+ inherits=True)
900
+ if not status:
901
+ return data
902
+ if not data:
903
+ return gone(self.not_found_error_msg())
904
+
905
+ col_data = []
906
+ for c in data['columns']:
907
+ if c.get('inheritedfrom', None) is None:
908
+ col_data.append(c)
909
+
910
+ data['columns'] = col_data
911
+ if target_schema:
912
+ data['basensp'] = target_schema
913
+
914
+ # Parse Privileges
915
+ if 'relacl' in data:
916
+ data['relacl'] = parse_priv_to_db(data['relacl'],
917
+ ["a", "r", "w", "x"])
918
+
919
+ SQL = render_template("/".join([self.template_path,
920
+ self._CREATE_SQL]),
921
+ data=data, is_sql=True,
922
+ add_not_exists_clause=True,
923
+ conn=self.conn
924
+ )
925
+
926
+ if not json_resp:
927
+ return SQL.strip('\n')
928
+
929
+ sql_header = """-- FOREIGN TABLE: {0}.{1}\n\n""".format(
930
+ data['basensp'], data['name'])
931
+
932
+ sql_header += """-- DROP FOREIGN TABLE IF EXISTS {0};
933
+
934
+ """.format(self.qtIdent(self.conn, data['basensp'], data['name']))
935
+
936
+ SQL = sql_header + SQL
937
+
938
+ trigger_sql = self._get_resql_for_triggers(
939
+ foid, data['basensp'], data['name'])
940
+
941
+ SQL = SQL + trigger_sql
942
+
943
+ return ajax_response(response=SQL.strip('\n'))
944
+
945
+ @check_precondition
946
+ @validate_request
947
+ def msql(self, gid, sid, did, scid, foid=None):
948
+ """
949
+ Returns the modified SQL.
950
+
951
+ Args:
952
+ gid: Server Group Id
953
+ sid: Server Id
954
+ did: Database Id
955
+ scid: Schema Id
956
+ foid: Foreign Table Id
957
+ name: Foreign Table Name
958
+ ftsrvname: Foreign Server Name
959
+
960
+ Returns:
961
+ SQL statements to create/update the Foreign Table.
962
+ """
963
+ data = {}
964
+ for k, v in self.request.items():
965
+ try:
966
+ # comments should be taken as is because if user enters a
967
+ # json comment it is parsed by loads which should not happen
968
+ if k in ('description',):
969
+ data[k] = v
970
+ else:
971
+ data[k] = json.loads(v)
972
+ except ValueError:
973
+ data[k] = v
974
+ except TypeError:
975
+ data[k] = v
976
+ try:
977
+ SQL, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
978
+ data=data, foid=foid)
979
+ # Most probably this is due to error
980
+ if not isinstance(SQL, str):
981
+ return SQL
982
+
983
+ if SQL == '':
984
+ SQL = "--modified SQL"
985
+
986
+ return make_json_response(
987
+ data=SQL,
988
+ status=200
989
+ )
990
+ except Exception as e:
991
+ return internal_server_error(errormsg=str(e))
992
+
993
+ @staticmethod
994
+ def _parse_privileges(data):
995
+ """
996
+ Parser privilege data as per type.
997
+ :param data: Data.
998
+ :return:
999
+ """
1000
+ if 'relacl' in data and 'added' in data['relacl']:
1001
+ data['relacl']['added'] = parse_priv_to_db(
1002
+ data['relacl']['added'], ["a", "r", "w", "x"])
1003
+ if 'relacl' in data and 'changed' in data['relacl']:
1004
+ data['relacl']['changed'] = parse_priv_to_db(
1005
+ data['relacl']['changed'], ["a", "r", "w", "x"])
1006
+ if 'relacl' in data and 'deleted' in data['relacl']:
1007
+ data['relacl']['deleted'] = parse_priv_to_db(
1008
+ data['relacl']['deleted'], ["a", "r", "w", "x"])
1009
+
1010
+ @staticmethod
1011
+ def _check_old_col_ops(old_col_frmt_options, option, col):
1012
+ """
1013
+ check old column options.
1014
+ :param old_col_frmt_options: old column option data.
1015
+ :param option: option data.
1016
+ :param col: column data.
1017
+ :return:
1018
+ """
1019
+ if (
1020
+ option['option'] in old_col_frmt_options and
1021
+ option['value'] != old_col_frmt_options[option['option']]
1022
+ ):
1023
+ col['coloptions_updated']['changed'].append(option)
1024
+ elif option['option'] not in old_col_frmt_options:
1025
+ col['coloptions_updated']['added'].append(option)
1026
+ if option['option'] in old_col_frmt_options:
1027
+ del old_col_frmt_options[option['option']]
1028
+
1029
+ @staticmethod
1030
+ def _parse_column_options(data):
1031
+ """
1032
+ Parse columns data.
1033
+ :param data: Data.
1034
+ :return:
1035
+ """
1036
+ for c in data['columns']['changed']:
1037
+ old_col_options = []
1038
+ if 'coloptions' in c and c['coloptions']:
1039
+ old_col_options = c['coloptions']
1040
+
1041
+ old_col_frmt_options = {}
1042
+
1043
+ for o in old_col_options:
1044
+ col_opt = o.split("=")
1045
+ old_col_frmt_options[col_opt[0]] = col_opt[1]
1046
+
1047
+ c['coloptions_updated'] = {'added': [],
1048
+ 'changed': [],
1049
+ 'deleted': []}
1050
+
1051
+ if 'coloptions' in c and len(c['coloptions']) > 0:
1052
+ for o in c['coloptions']:
1053
+ ForeignTableView._check_old_col_ops(old_col_frmt_options,
1054
+ o, c)
1055
+
1056
+ for o in old_col_frmt_options:
1057
+ c['coloptions_updated']['deleted'].append(
1058
+ {'option': o})
1059
+
1060
+ def _format_columns_data(self, data, old_data):
1061
+ """
1062
+ Format columns.
1063
+ :param data: data.
1064
+ :param old_data: old data for compare.
1065
+ :return:
1066
+ """
1067
+ col_data = {}
1068
+ # Prepare dict of columns with key = column's attnum
1069
+ # Will use this in the update template when any column is
1070
+ # changed, to identify the columns.
1071
+ for c in old_data['columns']:
1072
+ col_data[c['attnum']] = c
1073
+
1074
+ old_data['columns'] = col_data
1075
+
1076
+ if 'columns' in data and 'added' in data['columns']:
1077
+ data['columns']['added'] = self._format_columns(
1078
+ data['columns']['added'])
1079
+
1080
+ if 'columns' in data and 'changed' in data['columns']:
1081
+ data['columns']['changed'] = self._format_columns(
1082
+ data['columns']['changed'])
1083
+
1084
+ # Parse Column Options
1085
+ ForeignTableView._parse_column_options(data)
1086
+
1087
+ def get_sql(self, **kwargs):
1088
+ """
1089
+ Generates the SQL statements to create/update the Foreign Table.
1090
+
1091
+ Args:
1092
+ kwargs: Server Group Id
1093
+ """
1094
+ gid = kwargs.get('gid')
1095
+ sid = kwargs.get('sid')
1096
+ did = kwargs.get('did')
1097
+ scid = kwargs.get('scid')
1098
+ data = kwargs.get('data')
1099
+ foid = kwargs.get('foid', None)
1100
+ is_schema_diff = kwargs.get('is_schema_diff', False)
1101
+
1102
+ if foid is not None:
1103
+ status, old_data = self._fetch_properties(gid, sid, did, scid,
1104
+ foid, inherits=True)
1105
+ if not status:
1106
+ return old_data
1107
+ elif not old_data:
1108
+ return gone(self.not_found_error_msg())
1109
+
1110
+ if is_schema_diff:
1111
+ data['is_schema_diff'] = True
1112
+ old_data['columns_for_schema_diff'] = old_data['columns']
1113
+
1114
+ # If name is not present in request data
1115
+ if 'name' not in data:
1116
+ data['name'] = old_data['name']
1117
+
1118
+ # If name if not present
1119
+ if 'schema' not in data:
1120
+ data['schema'] = old_data['basensp']
1121
+
1122
+ # Parse Privileges
1123
+ ForeignTableView._parse_privileges(data)
1124
+
1125
+ # If ftsrvname is changed while comparing two schemas
1126
+ # then we need to drop foreign table and recreate it
1127
+ if is_schema_diff and 'ftsrvname' in data:
1128
+ # Modify the data required to recreate the foreign table.
1129
+ self.modify_data_for_schema_diff(data, old_data)
1130
+
1131
+ sql = render_template(
1132
+ "/".join([self.template_path,
1133
+ 'foreign_table_schema_diff.sql']),
1134
+ data=data, o_data=old_data, conn=self.conn)
1135
+ else:
1136
+ sql = render_template(
1137
+ "/".join([self.template_path, self._UPDATE_SQL]),
1138
+ data=data, o_data=old_data, conn=self.conn
1139
+ )
1140
+
1141
+ # Removes trailing new lines
1142
+ if sql:
1143
+ sql = sql.strip('\n') + self.double_newline
1144
+
1145
+ # Parse/Format columns & create sql
1146
+ if 'columns' in data:
1147
+ # Parse the data coming from client
1148
+ data = column_utils.parse_format_columns(data, mode='edit')
1149
+
1150
+ columns = data['columns']
1151
+ column_sql = '\n'
1152
+
1153
+ # If column(s) is/are deleted
1154
+ column_sql = self._check_for_column_delete(columns, data,
1155
+ column_sql)
1156
+
1157
+ # If column(s) is/are changed
1158
+ column_sql = self._check_for_column_update(columns, data,
1159
+ column_sql, foid)
1160
+
1161
+ # If column(s) is/are added
1162
+ column_sql = self._check_for_column_add(columns, data,
1163
+ column_sql)
1164
+
1165
+ # Combine all the SQL together
1166
+ sql += column_sql.strip('\n')
1167
+
1168
+ sql = re.sub(self.pattern, self.double_newline, sql)
1169
+ sql = sql.strip('\n')
1170
+
1171
+ return sql, data['name'] if 'name' in data else old_data['name']
1172
+ else:
1173
+ data['columns'] = self._format_columns(data['columns'])
1174
+
1175
+ # Parse Privileges
1176
+ if 'relacl' in data:
1177
+ data['relacl'] = parse_priv_to_db(data['relacl'],
1178
+ ["a", "r", "w", "x"])
1179
+
1180
+ sql = render_template("/".join([self.template_path,
1181
+ self._CREATE_SQL]), data=data,
1182
+ conn=self.conn)
1183
+ return sql, data['name']
1184
+
1185
+ def _check_for_column_delete(self, columns, data, column_sql):
1186
+ # If column(s) is/are deleted
1187
+ if 'deleted' in columns:
1188
+ for c in columns['deleted']:
1189
+ c['schema'] = data['schema']
1190
+ c['table'] = data['name']
1191
+ # Sql for drop column
1192
+ if c.get('inheritedfrom', None) is None:
1193
+ column_sql += render_template("/".join(
1194
+ [self.foreign_table_column_template_path,
1195
+ self._DELETE_SQL]),
1196
+ data=c, conn=self.conn).strip('\n') + \
1197
+ self.double_newline
1198
+ return column_sql
1199
+
1200
+ def _check_for_column_update(self, columns, data, column_sql, tid):
1201
+ # Here we will be needing previous properties of column
1202
+ # so that we can compare & update it
1203
+ if 'changed' in columns:
1204
+ for c in columns['changed']:
1205
+ c['schema'] = data['schema']
1206
+ c['table'] = data['name']
1207
+
1208
+ properties_sql = render_template(
1209
+ "/".join([self.column_template_path,
1210
+ self._PROPERTIES_SQL]),
1211
+ tid=tid,
1212
+ clid=c['attnum'] if 'attnum' in c else None,
1213
+ show_sys_objects=self.blueprint.show_system_objects
1214
+ )
1215
+
1216
+ status, res = self.conn.execute_dict(properties_sql)
1217
+ if not status:
1218
+ return internal_server_error(errormsg=res)
1219
+ old_col_data = res['rows'][0]
1220
+
1221
+ old_col_data['cltype'], \
1222
+ old_col_data['hasSqrBracket'] = \
1223
+ column_utils.type_formatter(old_col_data['cltype'])
1224
+ old_col_data = \
1225
+ column_utils.convert_length_precision_to_string(
1226
+ old_col_data)
1227
+ old_col_data = column_utils.fetch_length_precision(
1228
+ old_col_data)
1229
+
1230
+ old_col_data['cltype'] = \
1231
+ DataTypeReader.parse_type_name(
1232
+ old_col_data['cltype'])
1233
+
1234
+ # Sql for alter column
1235
+ if c.get('inheritedfrom', None) is None and \
1236
+ c.get('inheritedfromtable', None) is None:
1237
+ column_sql += render_template("/".join(
1238
+ [self.foreign_table_column_template_path,
1239
+ self._UPDATE_SQL]),
1240
+ data=c, o_data=old_col_data, conn=self.conn
1241
+ ).strip('\n') + self.double_newline
1242
+ return column_sql
1243
+
1244
+ def _check_for_column_add(self, columns, data, column_sql):
1245
+ # If column(s) is/are added
1246
+ if 'added' in columns:
1247
+ for c in columns['added']:
1248
+ c['schema'] = data['schema']
1249
+ c['table'] = data['name']
1250
+
1251
+ c = column_utils.convert_length_precision_to_string(c)
1252
+
1253
+ if c.get('inheritedfrom', None) is None and \
1254
+ c.get('inheritedfromtable', None) is None:
1255
+ column_sql += render_template("/".join(
1256
+ [self.foreign_table_column_template_path,
1257
+ self._CREATE_SQL]),
1258
+ data=c, conn=self.conn).strip('\n') + \
1259
+ self.double_newline
1260
+ return column_sql
1261
+
1262
+ @check_precondition
1263
+ def dependents(self, gid, sid, did, scid, foid):
1264
+ """
1265
+ This function get the dependents and return ajax response
1266
+ for the Foreign Table object.
1267
+
1268
+ Args:
1269
+ gid: Server Group Id
1270
+ sid: Server Id
1271
+ did: Database Id
1272
+ scid: Schema Id
1273
+ foid: Foreign Table Id
1274
+ """
1275
+ dependents_result = self.get_dependents(self.conn, foid)
1276
+ return ajax_response(
1277
+ response=dependents_result,
1278
+ status=200
1279
+ )
1280
+
1281
+ @check_precondition
1282
+ def dependencies(self, gid, sid, did, scid, foid):
1283
+ """
1284
+ This function get the dependencies and return ajax response
1285
+ for the Foreign Table object.
1286
+
1287
+ Args:
1288
+ gid: Server Group Id
1289
+ sid: Server Id
1290
+ did: Database Id
1291
+ scid: Schema Id
1292
+ foid: Foreign Table Id
1293
+ """
1294
+ dependencies_result = self.get_dependencies(self.conn, foid)
1295
+ return ajax_response(
1296
+ response=dependencies_result,
1297
+ status=200
1298
+ )
1299
+
1300
+ def _format_columns(self, columns):
1301
+ """
1302
+ Format Table Columns.
1303
+ """
1304
+ cols = []
1305
+ for c in columns:
1306
+ if len(c) > 0 and 'cltype' in c:
1307
+ if '[]' in c['cltype']:
1308
+ c['cltype'] = c['cltype'].replace('[]', '')
1309
+ c['isArrayType'] = True
1310
+ else:
1311
+ c['isArrayType'] = False
1312
+ cols.append(c)
1313
+ return cols if cols else columns
1314
+
1315
+ def _fetch_properties(self, gid, sid, did, scid, foid, inherits=False, ):
1316
+ """
1317
+ Returns the Foreign Table properties which will be used in
1318
+ properties, sql and get_sql functions.
1319
+
1320
+ Args:
1321
+ gid: Server Group Id
1322
+ sid: Server Id
1323
+ did: Database Id
1324
+ scid: Schema Id
1325
+ foid: Foreign Table Id
1326
+ inherits: If True then inherited table will be fetched from
1327
+ database
1328
+
1329
+ Returns:
1330
+
1331
+ """
1332
+ sql = render_template("/".join([self.template_path,
1333
+ self._PROPERTIES_SQL]),
1334
+ scid=scid, foid=foid)
1335
+ status, res = self.conn.execute_dict(sql)
1336
+ if not status:
1337
+ return False, internal_server_error(errormsg=res)
1338
+
1339
+ if len(res['rows']) == 0:
1340
+ return True, False
1341
+
1342
+ data = res['rows'][0]
1343
+ data['is_sys_obj'] = (
1344
+ data['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
1345
+ self.datistemplate)
1346
+
1347
+ if self.manager.version >= 90200:
1348
+ # Fetch privileges
1349
+ sql = render_template("/".join([self.template_path,
1350
+ self._ACL_SQL]),
1351
+ foid=foid)
1352
+ status, aclres = self.conn.execute_dict(sql)
1353
+ if not status:
1354
+ return False, internal_server_error(errormsg=aclres)
1355
+
1356
+ # Get Formatted Privileges
1357
+ data.update(self._format_proacl_from_db(aclres['rows']))
1358
+
1359
+ # Get formatted Security Labels
1360
+ if 'seclabels' in data:
1361
+ data.update(parse_sec_labels_from_db(data['seclabels']))
1362
+
1363
+ # Get formatted Options
1364
+ if 'ftoptions' in data:
1365
+ data.update({'strftoptions': data['ftoptions']})
1366
+ data.update(self._parse_variables_from_db(data['ftoptions']))
1367
+
1368
+ sql = render_template("/".join([self.template_path,
1369
+ self._GET_CONSTRAINTS_SQL]), foid=foid)
1370
+ status, cons = self.conn.execute_dict(sql)
1371
+ if not status:
1372
+ return False, internal_server_error(errormsg=cons)
1373
+
1374
+ if cons and 'rows' in cons:
1375
+ data['constraints'] = cons['rows']
1376
+
1377
+ sql = render_template("/".join([self.template_path,
1378
+ self._GET_COLUMNS_SQL]), foid=foid)
1379
+ status, cols = self.conn.execute_dict(sql)
1380
+ if not status:
1381
+ return False, internal_server_error(errormsg=cols)
1382
+
1383
+ # Fetch length and precision data
1384
+ for col in cols['rows']:
1385
+ column_utils.fetch_length_precision(col)
1386
+
1387
+ if 'attoptions' in col and col['attoptions'] != '':
1388
+ col['attoptions'] = column_utils.parse_column_variables(
1389
+ col['attoptions'])
1390
+
1391
+ if 'attfdwoptions' in col and col['attfdwoptions'] != '':
1392
+ col['coloptions'] = column_utils.parse_options_for_column(
1393
+ col['attfdwoptions'])
1394
+
1395
+ self._get_edit_types(cols['rows'])
1396
+
1397
+ if cols and 'rows' in cols:
1398
+ data['columns'] = cols['rows']
1399
+
1400
+ # Get Inherited table names from their OID
1401
+ is_error, errmsg = self._get_inherited_table_name(data, inherits)
1402
+
1403
+ if is_error:
1404
+ return False, internal_server_error(errormsg=errmsg)
1405
+
1406
+ return True, data
1407
+
1408
+ def _get_edit_types(self, cols):
1409
+ edit_types = {}
1410
+ for col in cols:
1411
+ edit_types[col['atttypid']] = []
1412
+
1413
+ if len(cols) > 0:
1414
+ SQL = render_template("/".join([self.template_path,
1415
+ 'edit_mode_types_multi.sql']),
1416
+ type_ids=",".join(map(lambda x: str(x),
1417
+ edit_types.keys())))
1418
+ _, res = self.conn.execute_2darray(SQL)
1419
+ for row in res['rows']:
1420
+ edit_types[row['main_oid']] = sorted(row['edit_types'])
1421
+
1422
+ for column in cols:
1423
+ edit_type_list = edit_types[column['atttypid']]
1424
+ edit_type_list.append(column['cltype'])
1425
+ column['edit_types'] = sorted(edit_type_list)
1426
+ column['cltype'] = \
1427
+ DataTypeReader.parse_type_name(column['cltype'])
1428
+
1429
+ def _get_datatype_precision(self, cols):
1430
+ """
1431
+ The Length and the precision of the Datatype should be separated.
1432
+ The Format we getting from database is: numeric(1,1)
1433
+ So, we need to separate it as Length: 1, Precision: 1
1434
+ :param cols: list of columns.
1435
+ """
1436
+ for c in cols['rows']:
1437
+ if c['fulltype'] != '' and c['fulltype'].find("(") > 0:
1438
+ substr = self.extract_type_length_precision(c)
1439
+ typlen = substr.split(",")
1440
+ if len(typlen) > 1:
1441
+ c['attlen'] = self.convert_typlen_to_int(typlen)
1442
+ c['attprecision'] = self.convert_precision_to_int(typlen)
1443
+ else:
1444
+ c['attlen'] = self.convert_typlen_to_int(typlen)
1445
+ c['attprecision'] = None
1446
+
1447
+ # Get formatted Column Options
1448
+ if 'attfdwoptions' in c and c['attfdwoptions'] != '':
1449
+ att_opt = self._parse_variables_from_db(c['attfdwoptions'])
1450
+ c['coloptions'] = att_opt['ftoptions']
1451
+
1452
+ def _get_inherited_table_name(self, data, inherits):
1453
+ """
1454
+ Get inherited table name.
1455
+ :param data: Data.
1456
+ :param inherits: flag which is used If True then inherited table
1457
+ will be fetched from database.
1458
+ """
1459
+ if inherits and 'inherits' in data and data['inherits']:
1460
+ inherits = tuple([int(x) for x in data['inherits']])
1461
+ if len(inherits) == 1:
1462
+ inherits = "(" + str(inherits[0]) + ")"
1463
+
1464
+ sql = render_template("/".join([self.template_path,
1465
+ self._GET_TABLES_SQL]),
1466
+ attrelid=inherits)
1467
+ status, res = self.conn.execute_dict(sql)
1468
+
1469
+ if not status:
1470
+ return True, res
1471
+
1472
+ if 'inherits' in res['rows'][0]:
1473
+ data['inherits'] = res['rows'][0]['inherits']
1474
+
1475
+ return False, ''
1476
+
1477
+ @staticmethod
1478
+ def convert_precision_to_int(typlen):
1479
+ return int(typlen[1]) if typlen[1].isdigit() else \
1480
+ typlen[1]
1481
+
1482
+ @staticmethod
1483
+ def convert_typlen_to_int(typlen):
1484
+ return int(typlen[0]) if typlen[0].isdigit() else \
1485
+ typlen[0]
1486
+
1487
+ def extract_type_length_precision(self, column):
1488
+ full_type = column['fulltype']
1489
+ return full_type[self.type_start_position(column):
1490
+ self.type_end_position(column)]
1491
+
1492
+ @staticmethod
1493
+ def type_end_position(column):
1494
+ return column['fulltype'].find(")")
1495
+
1496
+ @staticmethod
1497
+ def type_start_position(column):
1498
+ return column['fulltype'].find("(") + 1
1499
+
1500
+ def _format_proacl_from_db(self, proacl):
1501
+ """
1502
+ Returns privileges.
1503
+ Args:
1504
+ proacl: Privileges Dict
1505
+ """
1506
+ privileges = []
1507
+ for row in proacl:
1508
+ priv = parse_priv_from_db(row)
1509
+ privileges.append(priv)
1510
+
1511
+ return {"relacl": privileges}
1512
+
1513
+ def _parse_variables_from_db(self, db_variables):
1514
+ """
1515
+ Function to format the output for variables.
1516
+
1517
+ Args:
1518
+ db_variables: Variable object
1519
+
1520
+ Expected Object Format:
1521
+ ['option1=value1', ..]
1522
+ where:
1523
+ user_name and database are optional
1524
+ Returns:
1525
+ Variable Object in below format:
1526
+ {
1527
+ 'variables': [
1528
+ {'name': 'var_name', 'value': 'var_value',
1529
+ 'user_name': 'user_name', 'database': 'database_name'},
1530
+ ...]
1531
+ }
1532
+ where:
1533
+ user_name and database are optional
1534
+ """
1535
+ variables_lst = []
1536
+
1537
+ if db_variables is not None:
1538
+ for row in db_variables:
1539
+ # The value may contain equals in string, split on
1540
+ # first equals only
1541
+ var_name, var_value = row.split("=", 1)
1542
+
1543
+ var_dict = {'option': var_name, 'value': var_value}
1544
+
1545
+ variables_lst.append(var_dict)
1546
+
1547
+ return {"ftoptions": variables_lst}
1548
+
1549
+ @check_precondition
1550
+ def select_sql(self, gid, sid, did, scid, foid):
1551
+ """
1552
+ SELECT script sql for the object
1553
+
1554
+ Args:
1555
+ gid: Server Group Id
1556
+ sid: Server Id
1557
+ did: Database Id
1558
+ scid: Schema Id
1559
+ foid: Foreign Table Id
1560
+
1561
+ Returns:
1562
+ SELECT Script sql for the object
1563
+ """
1564
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
1565
+ if not status:
1566
+ return data
1567
+ if not data:
1568
+ return gone(self.not_found_error_msg())
1569
+
1570
+ columns = []
1571
+ for c in data['columns']:
1572
+ columns.append(self.qtIdent(self.conn, c['name']))
1573
+
1574
+ if len(columns) > 0:
1575
+ columns = ", ".join(columns)
1576
+ else:
1577
+ columns = '*'
1578
+
1579
+ sql = "SELECT {0}\n\tFROM {1};".format(
1580
+ columns,
1581
+ self.qtIdent(self.conn, data['basensp'], data['name'])
1582
+ )
1583
+
1584
+ return ajax_response(response=sql)
1585
+
1586
+ @check_precondition
1587
+ def insert_sql(self, gid, sid, did, scid, foid):
1588
+ """
1589
+ INSERT script sql for the object
1590
+
1591
+ Args:
1592
+ gid: Server Group Id
1593
+ sid: Server Id
1594
+ did: Database Id
1595
+ scid: Schema Id
1596
+ foid: Foreign Table Id
1597
+
1598
+ Returns:
1599
+ INSERT Script sql for the object
1600
+ """
1601
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
1602
+ if not status:
1603
+ return data
1604
+ if not data:
1605
+ return gone(self.not_found_error_msg())
1606
+
1607
+ columns = []
1608
+ values = []
1609
+
1610
+ # Now we have all list of columns which we need
1611
+ if 'columns' in data:
1612
+ for c in data['columns']:
1613
+ columns.append(self.qtIdent(self.conn, c['name']))
1614
+ values.append('?')
1615
+
1616
+ if len(columns) > 0:
1617
+ columns = ", ".join(columns)
1618
+ values = ", ".join(values)
1619
+ sql = "INSERT INTO {0}(\n\t{1})\n\tVALUES ({2});".format(
1620
+ self.qtIdent(self.conn, data['basensp'], data['name']),
1621
+ columns, values
1622
+ )
1623
+ else:
1624
+ sql = gettext('-- Please create column(s) first...')
1625
+
1626
+ return ajax_response(response=sql)
1627
+
1628
+ @check_precondition
1629
+ def update_sql(self, gid, sid, did, scid, foid):
1630
+ """
1631
+ UPDATE script sql for the object
1632
+
1633
+ Args:
1634
+ gid: Server Group Id
1635
+ sid: Server Id
1636
+ did: Database Id
1637
+ scid: Schema Id
1638
+ foid: Foreign Table Id
1639
+
1640
+ Returns:
1641
+ UPDATE Script sql for the object
1642
+ """
1643
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
1644
+ if not status:
1645
+ return data
1646
+ if not data:
1647
+ return gone(self.not_found_error_msg())
1648
+
1649
+ columns = []
1650
+
1651
+ # Now we have all list of columns which we need
1652
+ if 'columns' in data:
1653
+ for c in data['columns']:
1654
+ columns.append(self.qtIdent(self.conn, c['name']))
1655
+
1656
+ if len(columns) > 0:
1657
+ if len(columns) == 1:
1658
+ columns = columns[0]
1659
+ columns += "=?"
1660
+ else:
1661
+ columns = "=?, ".join(columns)
1662
+ columns += "=?"
1663
+
1664
+ sql = "UPDATE {0}\n\tSET {1}\n\tWHERE <condition>;".format(
1665
+ self.qtIdent(self.conn, data['basensp'], data['name']),
1666
+ columns
1667
+ )
1668
+ else:
1669
+ sql = gettext('-- Please create column(s) first...')
1670
+
1671
+ return ajax_response(response=sql)
1672
+
1673
+ @check_precondition
1674
+ def delete_sql(self, gid, sid, did, scid, foid, only_sql=False):
1675
+ """
1676
+ DELETE script sql for the object
1677
+
1678
+ Args:
1679
+ gid: Server Group Id
1680
+ sid: Server Id
1681
+ did: Database Id
1682
+ scid: Schema Id
1683
+ foid: Foreign Table Id
1684
+ only_sql: Return only sql if True
1685
+
1686
+ Returns:
1687
+ DELETE Script sql for the object
1688
+ """
1689
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
1690
+ if not status:
1691
+ return data
1692
+ if not data:
1693
+ return gone(self.not_found_error_msg())
1694
+
1695
+ sql = "DELETE FROM {0}\n\tWHERE <condition>;".format(
1696
+ self.qtIdent(self.conn, data['basensp'], data['name'])
1697
+ )
1698
+
1699
+ # Used for schema diff tool
1700
+ if only_sql:
1701
+ return sql
1702
+
1703
+ return ajax_response(response=sql)
1704
+
1705
+ @staticmethod
1706
+ def _check_const_for_obj_compare(data):
1707
+ """
1708
+ Check for constraint in fetched objects for compare.
1709
+ :param data: Data.
1710
+ """
1711
+ if 'constraints' in data and data['constraints'] is not None \
1712
+ and len(data['constraints']) > 0:
1713
+ for item in data['constraints']:
1714
+ if 'conoid' in item:
1715
+ item.pop('conoid')
1716
+
1717
+ @check_precondition
1718
+ def fetch_objects_to_compare(self, sid, did, scid):
1719
+ """
1720
+ This function will fetch the list of all the foreign tables for
1721
+ specified schema id.
1722
+
1723
+ :param sid: Server Id
1724
+ :param did: Database Id
1725
+ :param scid: Schema Id
1726
+ :return:
1727
+ """
1728
+ res = dict()
1729
+ SQL = render_template("/".join([self.template_path,
1730
+ self._NODE_SQL]), scid=scid,
1731
+ schema_diff=True)
1732
+ status, rset = self.conn.execute_2darray(SQL)
1733
+ if not status:
1734
+ return internal_server_error(errormsg=res)
1735
+
1736
+ for row in rset['rows']:
1737
+ status, data = self._fetch_properties(0, sid, did, scid,
1738
+ row['oid'])
1739
+ if status:
1740
+ ForeignTableView._check_const_for_obj_compare(data)
1741
+ res[row['name']] = data
1742
+
1743
+ return res
1744
+
1745
+ def get_sql_from_diff(self, **kwargs):
1746
+ """
1747
+ This function is used to get the DDL/DML statements.
1748
+ :param kwargs
1749
+ :return:
1750
+ """
1751
+ gid = kwargs.get('gid')
1752
+ sid = kwargs.get('sid')
1753
+ did = kwargs.get('did')
1754
+ scid = kwargs.get('scid')
1755
+ oid = kwargs.get('oid')
1756
+ data = kwargs.get('data', None)
1757
+ drop_sql = kwargs.get('drop_sql', False)
1758
+ target_schema = kwargs.get('target_schema', None)
1759
+
1760
+ if data:
1761
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
1762
+ data=data, foid=oid, is_schema_diff=True)
1763
+ else:
1764
+ if drop_sql:
1765
+ sql = self.delete(gid=gid, sid=sid, did=did,
1766
+ scid=scid, foid=oid, only_sql=True)
1767
+ elif target_schema:
1768
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, foid=oid,
1769
+ target_schema=target_schema, json_resp=False)
1770
+ else:
1771
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, foid=oid,
1772
+ json_resp=False)
1773
+ return sql
1774
+
1775
+ @staticmethod
1776
+ def _modify_column_data(data, tmp_columns):
1777
+ """
1778
+ Modifies data for column.
1779
+ :param data: Data for columns.
1780
+ :param tmp_columns: tmp_columns list.
1781
+ """
1782
+ if 'added' in data['columns']:
1783
+ for item in data['columns']['added']:
1784
+ tmp_columns.append(item)
1785
+ if 'changed' in data['columns']:
1786
+ for item in data['columns']['changed']:
1787
+ tmp_columns.append(item)
1788
+ if 'deleted' in data['columns']:
1789
+ for item in data['columns']['deleted']:
1790
+ tmp_columns.remove(item)
1791
+
1792
+ @staticmethod
1793
+ def _modify_constraints_data(data):
1794
+ """
1795
+ Modifies data for constraints.
1796
+ :param data: Data for constraints.
1797
+ :return: tmp_constraints list.
1798
+ """
1799
+ tmp_constraints = []
1800
+ if 'added' in data['constraints']:
1801
+ for item in data['constraints']['added']:
1802
+ tmp_constraints.append(item)
1803
+ if 'changed' in data['constraints']:
1804
+ for item in data['constraints']['changed']:
1805
+ tmp_constraints.append(item)
1806
+
1807
+ return tmp_constraints
1808
+
1809
+ @staticmethod
1810
+ def _modify_options_data(data, tmp_ftoptions):
1811
+ """
1812
+ Modifies data for options.
1813
+ :param data: Data for options.
1814
+ :param tmp_ftoptions: tmp_ftoptions list.
1815
+ """
1816
+ if 'added' in data['ftoptions']:
1817
+ for item in data['ftoptions']['added']:
1818
+ tmp_ftoptions.append(item)
1819
+ if 'changed' in data['ftoptions']:
1820
+ for item in data['ftoptions']['changed']:
1821
+ tmp_ftoptions.append(item)
1822
+ if 'deleted' in data['ftoptions']:
1823
+ for item in data['ftoptions']['deleted']:
1824
+ tmp_ftoptions.remove(item)
1825
+
1826
+ def modify_data_for_schema_diff(self, data, old_data):
1827
+ """
1828
+ This function modifies the data for columns, constraints, options
1829
+ etc...
1830
+ :param data:
1831
+ :return:
1832
+ """
1833
+ tmp_columns = []
1834
+ if 'columns_for_schema_diff' in old_data:
1835
+ tmp_columns = old_data['columns_for_schema_diff']
1836
+
1837
+ if 'columns' in data:
1838
+ ForeignTableView._modify_column_data(data, tmp_columns)
1839
+
1840
+ data['columns'] = tmp_columns
1841
+
1842
+ if 'constraints' in data:
1843
+ tmp_constraints = ForeignTableView._modify_constraints_data(data)
1844
+ data['constraints'] = tmp_constraints
1845
+
1846
+ tmp_ftoptions = []
1847
+ if 'ftoptions' in old_data:
1848
+ tmp_ftoptions = old_data['ftoptions']
1849
+ if 'ftoptions' in data:
1850
+ ForeignTableView._modify_options_data(data, tmp_ftoptions)
1851
+
1852
+ data['ftoptions'] = tmp_ftoptions
1853
+
1854
+ @check_precondition
1855
+ def enable_disable_triggers(self, gid, sid, did, scid, foid):
1856
+ """
1857
+ This function will enable/disable trigger(s) on the table object
1858
+
1859
+ Args:
1860
+ gid: Server Group ID
1861
+ sid: Server ID
1862
+ did: Database ID
1863
+ scid: Schema ID
1864
+ tid: Table ID
1865
+ """
1866
+ # Below will decide if it's simple drop or drop with cascade call
1867
+ data = request.form if request.form else json.loads(
1868
+ request.data
1869
+ )
1870
+ # Convert str 'true' to boolean type
1871
+ is_enable_trigger = data['is_enable_trigger']
1872
+
1873
+ try:
1874
+ if foid is not None:
1875
+ status, data = self._fetch_properties(
1876
+ gid, sid, did, scid, foid, inherits=True)
1877
+ if not status:
1878
+ return data
1879
+ elif not data:
1880
+ return gone(self.not_found_error_msg())
1881
+
1882
+ SQL = render_template(
1883
+ "/".join([self.template_path, 'enable_disable_trigger.sql']),
1884
+ data=data, is_enable_trigger=is_enable_trigger
1885
+ )
1886
+ status, res = self.conn.execute_scalar(SQL)
1887
+ if not status:
1888
+ return internal_server_error(errormsg=res)
1889
+
1890
+ SQL = render_template(
1891
+ "/".join([self.template_path, 'get_enabled_triggers.sql']),
1892
+ tid=foid
1893
+ )
1894
+
1895
+ status, trigger_res = self.conn.execute_scalar(SQL)
1896
+ if not status:
1897
+ return internal_server_error(errormsg=res)
1898
+
1899
+ return make_json_response(
1900
+ success=1,
1901
+ info=gettext("Trigger(s) have been disabled")
1902
+ if is_enable_trigger == 'D'
1903
+ else gettext("Trigger(s) have been enabled"),
1904
+ data={
1905
+ 'id': foid,
1906
+ 'scid': scid,
1907
+ 'has_enable_triggers': trigger_res
1908
+ }
1909
+ )
1910
+
1911
+ except Exception as e:
1912
+ return internal_server_error(errormsg=str(e))
1913
+
1914
+ def _get_resql_for_triggers(self, tid, schema,
1915
+ table):
1916
+ """
1917
+ ########################################
1918
+ # Reverse engineered sql for TRIGGERS
1919
+ ########################################
1920
+ """
1921
+ sql = render_template("/".join([self.trigger_template_path,
1922
+ self._NODES_SQL]), tid=tid)
1923
+ status, rset = self.conn.execute_2darray(sql)
1924
+ if not status:
1925
+ return internal_server_error(errormsg=rset)
1926
+
1927
+ trigger_sql = ''
1928
+ for row in rset['rows']:
1929
+ trigger_sql = trigger_utils.get_reverse_engineered_sql(
1930
+ self.conn, schema=schema, table=table, tid=tid,
1931
+ trid=row['oid'], datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
1932
+ show_system_objects=self.blueprint.show_system_objects,
1933
+ template_path=None)
1934
+ trigger_sql = "\n" + trigger_sql
1935
+
1936
+ trigger_sql = re.sub(self.pattern, self.double_newline,
1937
+ trigger_sql)
1938
+ return trigger_sql
1939
+
1940
+
1941
+ SchemaDiffRegistry(blueprint.node_type, ForeignTableView)
1942
+ ForeignTableView.register_node_view(blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/children/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ We will use the existing modules for creating children module under
3
+ foreign tables.
4
+
5
+ Do not remove these imports as they will be automatically imported by the view
6
+ module as its children
7
+ """
8
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.triggers \
9
+ import blueprint as triggers_modules
10
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
11
+ constraints import blueprint as constraints_modules
12
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
13
+ foreign_tables.foreign_table_columns import foreign_table_column_blueprint\
14
+ as foreign_tables_columns_modules
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ #
3
+ # pgAdmin 4 - PostgreSQL Tools
4
+ #
5
+ # Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ # This software is released under the PostgreSQL Licence
7
+ #
8
+ ##########################################################################
9
+
10
+ """ Implements Column Node for foreign table """
11
+ import pgadmin.browser.server_groups.servers.databases as database
12
+ from flask_babel import gettext
13
+ from pgadmin.browser.collection import CollectionNodeModule
14
+
15
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.columns \
16
+ import ColumnsView
17
+
18
+
19
+ class ForeignTableColumnsModule(CollectionNodeModule):
20
+ """
21
+ class ColumnsModule(CollectionNodeModule)
22
+
23
+ A module class for Column node derived from CollectionNodeModule.
24
+
25
+ Methods:
26
+ -------
27
+ * __init__(*args, **kwargs)
28
+ - Method is used to initialize the Column and it's base module.
29
+
30
+ * get_nodes(gid, sid, did, scid, tid)
31
+ - Method is used to generate the browser collection node.
32
+
33
+ * node_inode()
34
+ - Method is overridden from its base class to make the node as leaf node.
35
+
36
+ * script_load()
37
+ - Load the module script for schema, when any of the server node is
38
+ initialized.
39
+ """
40
+
41
+ _NODE_TYPE = 'foreign_table_column'
42
+ _COLLECTION_LABEL = gettext("Columns")
43
+
44
+ def __init__(self, *args, **kwargs):
45
+ """
46
+ Method is used to initialize the ColumnModule and it's base module.
47
+
48
+ Args:
49
+ *args:
50
+ **kwargs:
51
+ """
52
+ self.min_ver = None
53
+ self.max_ver = None
54
+ super().__init__(*args, **kwargs)
55
+
56
+ def get_nodes(self, gid, sid, did, scid, foid, **kwargs):
57
+ """
58
+ Generate the collection node
59
+ """
60
+ if self.has_nodes(
61
+ sid, did, scid=scid, tid=foid,
62
+ base_template_path=ForeignTableColumnsView.BASE_TEMPLATE_PATH):
63
+ yield self.generate_browser_collection_node(foid)
64
+
65
+ @property
66
+ def script_load(self):
67
+ """
68
+ Load the module script for server, when any of the server-group node is
69
+ initialized.
70
+ """
71
+ return database.DatabaseModule.node_type
72
+
73
+ @property
74
+ def node_inode(self):
75
+ """
76
+ Load the module node as a leaf node
77
+ """
78
+ return False
79
+
80
+ @property
81
+ def module_use_template_javascript(self):
82
+ """
83
+ Returns whether Jinja2 template is used for generating the javascript
84
+ module.
85
+ """
86
+ return False
87
+
88
+
89
+ foreign_table_column_blueprint = ForeignTableColumnsModule(__name__)
90
+
91
+
92
+ class ForeignTableColumnsView(ColumnsView):
93
+ node_type = foreign_table_column_blueprint.node_type
94
+ node_label = "Column"
95
+
96
+
97
+ ForeignTableColumnsView.register_node_view(foreign_table_column_blueprint)
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/coll-foreign_table_column.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/foreign_table_column.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/js/foreign_table_column.js ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////
2
+ //
3
+ // pgAdmin 4 - PostgreSQL Tools
4
+ //
5
+ // Copyright (C) 2013 - 2024, The pgAdmin Development Team
6
+ // This software is released under the PostgreSQL Licence
7
+ //
8
+ //////////////////////////////////////////////////////////////
9
+ import { getNodeColumnSchema } from '../../../static/js/foreign_table.ui';
10
+
11
+ define('pgadmin.node.foreign_table_column', [
12
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
13
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
14
+ ], function(
15
+ gettext, url_for, pgBrowser
16
+ ) {
17
+
18
+ if (!pgBrowser.Nodes['coll-foreign_table_column']) {
19
+ pgBrowser.Nodes['coll-foreign_table_column'] =
20
+ pgBrowser.Collection.extend({
21
+ node: 'foreign_table_column',
22
+ label: gettext('Columns'),
23
+ type: 'coll-foreign_table_column',
24
+ columns: ['name', 'cltype', 'description']
25
+ });
26
+ }
27
+
28
+ if (!pgBrowser.Nodes['foreign_table_column']) {
29
+ pgBrowser.Nodes['foreign_table_column'] = pgBrowser.Node.extend({
30
+ // Foreign table is added in parent_type to support triggers on
31
+ // foreign table where we need column information.
32
+ parent_type: ['foreign_table'],
33
+ collection_type: ['coll-foreign_table'],
34
+ type: 'foreign_table_column',
35
+ label: gettext('Column'),
36
+ hasSQL: true,
37
+ sqlAlterHelp: 'sql-altertable.html',
38
+ sqlCreateHelp: 'sql-altertable.html',
39
+ dialogHelp: url_for('help.static', {'filename': 'column_dialog.html'}),
40
+ canDrop: true,
41
+ canDropCascade: false,
42
+ hasDepends: true,
43
+ hasStatistics: true,
44
+ Init: function() {
45
+ /* Avoid multiple registration of menus */
46
+ if (this.initialized)
47
+ return;
48
+
49
+ this.initialized = true;
50
+ pgBrowser.add_menus([{
51
+ name: 'create_column_on_coll', node: 'coll-foreign_table_column', module: this,
52
+ applies: ['object', 'context'], callback: 'show_obj_properties',
53
+ category: 'create', priority: 4, label: gettext('Column...'),
54
+ data: {action: 'create'}, enable: 'canCreate',
55
+ },{
56
+ name: 'create_column_onTable', node: 'foreign_table', module: this,
57
+ applies: ['object', 'context'], callback: 'show_obj_properties',
58
+ category: 'create', priority: 4, label: gettext('Column...'),
59
+ data: {action: 'create'}, enable: 'canCreate',
60
+ },
61
+ ]);
62
+ },
63
+ getSchema: function(treeNodeInfo, itemNodeData) {
64
+ return getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser);
65
+ },
66
+ });
67
+ }
68
+
69
+ return pgBrowser.Nodes['foreign_table_column'];
70
+ });
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/coll-foreign_table.svg ADDED
pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/foreign_table.svg ADDED