diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/aggregates/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/aggregates/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e451d52930526ef00ebf1ddb01e28031a8384e17
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/aggregates/__init__.py
@@ -0,0 +1,371 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Aggregate Node """
+
+from functools import wraps
+
+from flask import render_template
+from flask_babel import gettext
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+
+
+class AggregateModule(SchemaChildModule):
+ """
+ class AggregateModule(SchemaChildModule)
+
+ A module class for Aggregate node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Aggregate and it's base module.
+
+ * get_nodes(gid, sid, did, scid, agid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'aggregate'
+ _COLLECTION_LABEL = gettext("Aggregates")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the AggregateModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90100
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=AggregateView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ return False
+
+
+blueprint = AggregateModule(__name__)
+
+
+class AggregateView(PGChildNodeView):
+ """
+ This class is responsible for generating routes for Aggregate node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the AggregateView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Aggregate nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Aggregate node.
+
+ * properties(gid, sid, did, scid, agid)
+ - This function will show the properties of the selected Aggregate node
+
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Aggregate node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Aggregate"
+ BASE_TEMPLATE_PATH = 'aggregates/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'agid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = \
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the aggregate nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available aggregate nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the aggregate node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available aggregate child nodes
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-aggregate",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, agid):
+ """
+ This function will fetch properties of the aggregate node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ agid: Aggregate ID
+
+ Returns:
+ JSON of given aggregate node
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), agid=agid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-aggregate"
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, agid):
+ """
+ This function will show the properties of the selected aggregate node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ agid: Aggregate ID
+
+ Returns:
+ JSON of selected aggregate node
+ """
+
+ status, res = self._fetch_properties(scid, agid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, agid):
+ """
+ This function fetch the properties for the specified object.
+
+ :param scid: Schema ID
+ :param agid: Aggregate ID
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, agid=agid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return True, res['rows'][0]
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, agid, **kwargs):
+ """
+ This function will generates reverse engineered sql for aggregate
+ object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ agid: Aggregate ID
+ json_resp: True then return json response
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, agid=agid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data)
+
+ sql_header = "-- Aggregate: {0};\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data)
+ SQL = sql_header + '\n' + SQL.strip('\n')
+
+ return ajax_response(response=SQL)
+
+
+AggregateView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b166c0ebf596a53fd633101eb7666b777cc142a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py
@@ -0,0 +1,364 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Catalog objects Node."""
+
+from functools import wraps
+
+from flask import render_template
+from flask_babel import gettext
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import gone
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response
+from pgadmin.utils.driver import get_driver
+
+
+class CatalogObjectModule(SchemaChildModule):
+ """
+ class CatalogObjectModule(SchemaChildModule)
+
+ A module class for Catalog objects node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Catalog objects and it's base module.
+
+ * get_nodes(gid, sid, did, scid, coid)
+ - Method is used to generate the browser collection node.
+
+ * script_load()
+ - Load the module script for Catalog objects, when any of the server node
+ is initialized.
+ """
+ _NODE_TYPE = 'catalog_object'
+ _COLLECTION_LABEL = gettext("Catalog Objects")
+
+ # Flag for not to show node under Schema/Catalog node
+ # By default its set to True to display node in schema/catalog
+ # We do not want to display 'Catalog Objects' under Schema/Catalog
+ # but only in information_schema/sys
+ CATALOG_DB_SUPPORTED = False
+ SUPPORTED_SCHEMAS = ['information_schema', 'sys']
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the CatalogObjectModule and it's base
+ module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ def register(self, app, options):
+ """
+ Override the default register function to automagically register
+ sub-modules at once.
+ """
+ super().register(app, options)
+
+ from .columns import blueprint as module
+ app.register_blueprint(module)
+
+
+blueprint = CatalogObjectModule(__name__)
+
+
+class CatalogObjectView(PGChildNodeView):
+ """
+ This class is responsible for generating routes for Catalog objects node.
+
+ Methods:
+ -------
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - Lists all the Catalog objects nodes within that collection.
+
+ * nodes()
+ - Creates all the nodes of type Catalog objects.
+
+ * properties(gid, sid, did, scid, coid)
+ - Shows the properties of the selected Catalog objects node.
+
+ * dependency(gid, sid, did, scid):
+ - Returns the dependencies list for the given catalog object node.
+
+ * dependent(gid, sid, did, scid):
+ - Returns the dependents list for the given Catalog objects node.
+ """
+ node_type = blueprint.node_type
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'coid'}
+ ]
+
+ operations = dict({
+ 'obj': [{'get': 'properties'}, {'get': 'list'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.template_path = 'catalog_object/sql/{0}/#{1}#'.format(
+ 'ppas' if self.manager.server_type == 'ppas' else 'pg',
+ self.manager.version
+ )
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the catalog objects
+ nodes within that collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available catalog objects nodes
+ """
+
+ SQL = render_template("/".join([
+ self.template_path, self._PROPERTIES_SQL
+ ]), scid=scid
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the catalog objects node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available catalog objects child nodes
+ """
+ res = []
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]), scid=scid
+ )
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-catalog_object",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, coid):
+ """
+ This function will fetch properties of catalog objects node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Catalog object ID
+
+ Returns:
+ JSON of given catalog objects child node
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]), coid=coid
+ )
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-catalog_object"
+ ),
+ status=200
+ )
+
+ return gone(
+ errormsg=gettext("Could not find the specified catalog object."))
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, coid):
+ """
+ This function will show the properties of the selected
+ catalog objects node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ coid: Catalog object ID
+
+ Returns:
+ JSON of selected catalog objects node
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, coid=coid
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("""Could not find the specified catalog object."""))
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return ajax_response(
+ response=res['rows'][0],
+ status=200
+ )
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, coid):
+ """
+ This function get the dependents and return ajax response
+ for the catalog objects node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: catalog objects ID
+ """
+ dependents_result = self.get_dependents(self.conn, coid)
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, coid):
+ """
+ This function get the dependencies and return ajax response
+ for the catalog objects node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: catalog objects ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, coid)
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+
+CatalogObjectView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d80931067552976a2984d5f9a6d4824fc363923b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/__init__.py
@@ -0,0 +1,853 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Collation Node """
+
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class CollationModule(SchemaChildModule):
+ """
+ class CollationModule(CollectionNodeModule)
+
+ A module class for Collation node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Collation and it's base module.
+
+ * get_nodes(gid, sid, did, scid, coid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'collation'
+ _COLLECTION_LABEL = gettext("Collations")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the CollationModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90100
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=CollationView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ return False
+
+
+blueprint = CollationModule(__name__)
+
+
+class CollationView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Collation node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the CollationView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Collation nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Collation node.
+
+ * properties(gid, sid, did, scid, coid)
+ - This function will show the properties of the selected Collation node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new Collation object
+
+ * update(gid, sid, did, scid, coid)
+ - This function will update the data for the selected Collation node
+
+ * delete(self, gid, sid, scid, coid):
+ - This function will drop the Collation object
+
+ * msql(gid, sid, did, scid, coid)
+ - This function is used to return modified SQL for the selected
+ Collation node
+
+ * get_sql(data, scid, coid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Collation node.
+
+ * dependency(gid, sid, did, scid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Collation node.
+
+ * dependent(gid, sid, did, scid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Collation node.
+
+ * compare(**kwargs):
+ - This function will compare the collation nodes from two different
+ schemas.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Collation"
+ BASE_TEMPLATE_PATH = 'collations/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'coid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_collations': [{'get': 'get_collation'},
+ {'get': 'get_collation'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = \
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the collation nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available collation nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the collation node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available collation child nodes
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-collation",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, coid):
+ """
+ This function will fetch properties of the collation node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+
+ Returns:
+ JSON of given collation node
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), coid=coid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-collation"
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, coid):
+ """
+ This function will show the properties of the selected collation node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ coid: Collation ID
+
+ Returns:
+ JSON of selected collation node
+ """
+
+ status, res = self._fetch_properties(scid, coid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, coid):
+ """
+ This function fetch the properties for the specified object.
+
+ :param scid: Schema ID
+ :param coid: Collation ID
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, coid=coid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return True, res['rows'][0]
+
+ @check_precondition
+ def get_collation(self, gid, sid, did, scid, coid=None):
+ """
+ This function will return list of collation available
+ as AJAX response.
+ """
+
+ res = []
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_collations.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['copy_collation'],
+ 'value': row['copy_collation']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _check_definition(self, data):
+ """
+ Args:
+ data: request data received from client
+
+ Returns:
+ True if defination is missing, False otherwise
+ """
+ definition_args = [
+ 'locale',
+ 'copy_collation',
+ 'lc_collate',
+ 'lc_type'
+ ]
+
+ # Additional server side validation to check if
+ # definition is sent properly from client side
+ missing_definition_flag = False
+
+ for arg in definition_args:
+ if (
+ arg == 'locale' and
+ (arg not in data or data[arg] == '') and
+ 'copy_collation' not in data and
+ 'lc_collate' not in data and 'lc_type' not in data
+ ):
+ missing_definition_flag = True
+
+ if (
+ arg == 'copy_collation' and
+ (arg not in data or data[arg] == '') and
+ 'locale' not in data and
+ 'lc_collate' not in data and 'lc_type' not in data
+ ):
+ missing_definition_flag = True
+
+ if (
+ (arg == 'lc_collate' or arg == 'lc_type') and
+ (arg not in data or data[arg] == '') and
+ 'copy_collation' not in data and 'locale' not in data
+ ):
+ missing_definition_flag = True
+
+ return missing_definition_flag
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the collation object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ required_args = [
+ 'schema',
+ 'name'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ if self._check_definition(data):
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Definition incomplete. Please provide Locale OR Copy "
+ "Collation OR LC_TYPE/LC_COLLATE."
+ )
+ )
+
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need oid to add object in tree at browser
+ SQL = render_template(
+ "/".join([self.template_path, self._OID_SQL]), data=data,
+ conn=self.conn
+ )
+ status, coid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=coid)
+
+ # Get updated schema oid
+ SQL = render_template(
+ "/".join([self.template_path, self._OID_SQL]), coid=coid,
+ conn=self.conn
+ )
+
+ status, new_scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=coid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ coid,
+ new_scid,
+ data['name'],
+ icon="icon-collation"
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, coid=None, only_sql=False):
+ """
+ This function will delete the existing collation object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ only_sql: Return only sql if True
+ """
+ data = json.loads(request.data) if coid is None \
+ else {'ids': [coid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for coid in data['ids']:
+ SQL = render_template("/".join([self.template_path,
+ 'get_name.sql']),
+ scid=scid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=data['name'],
+ nspname=data['schema'],
+ cascade=cascade,
+ conn=self.conn)
+
+ # Used for schema diff tool
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Collation dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, coid):
+ """
+ This function will updates the existing collation object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ SQL, name = self.get_sql(gid, sid, data, scid, coid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need oid to add object in tree at browser
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]), coid=coid)
+
+ status, res = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ scid = res['rows'][0]['scid']
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ coid,
+ scid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, coid=None):
+ """
+ This function will generates modified sql for collation object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ try:
+ SQL, _ = self.get_sql(gid, sid, data, scid, coid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_sql(self, gid, sid, data, scid, coid=None):
+ """
+ This function will genrate sql from model data
+ """
+ if coid is not None:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ old_data = res['rows'][0]
+ SQL = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ return SQL.strip('\n'), data['name'] if 'name' in data else \
+ old_data['name']
+ else:
+ required_args = [
+ 'name'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return gettext("-- missing definition")
+
+ if self._check_definition(data):
+ return gettext("-- missing definition")
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ return SQL.strip('\n'), data['name']
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, coid, **kwargs):
+ """
+ This function will generates reverse engineered sql for collation
+ object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+ if target_schema:
+ data['schema'] = target_schema
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn,
+ add_not_exists_clause=True
+ )
+
+ sql_header = "-- Collation: {0};\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=data['name'],
+ nspname=data['schema'])
+ SQL = sql_header + '\n\n' + SQL.strip('\n')
+
+ if not json_resp:
+ return SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, coid):
+ """
+ This function get the dependents and return ajax response
+ for the Collation node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, coid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, coid):
+ """
+ This function get the dependencies and return ajax response
+ for the Collation node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ coid: Collation ID
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, coid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the collations for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.get_sql(gid=gid, sid=sid, data=data, scid=scid,
+ coid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, coid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, coid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, coid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, CollationView)
+CollationView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bf35b779a4d71e3275c47884aab0d48135a10ef2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/create.sql
@@ -0,0 +1,59 @@
+{% if data %}
+CREATE COLLATION{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if not data.copy_collation %}
+{% set options = [] %}
+{# if user has provided lc_collate & lc_type #}
+{% if data.lc_collate and data.lc_type %}
+{% if data.lc_collate and data.lc_type %}
+ {% set options = options + ['LC_COLLATE = ' ~ data.lc_collate|qtLiteral(conn), 'LC_CTYPE = ' ~ data.lc_type|qtLiteral(conn)] %}
+{% endif %}
+{% if data.provider %}
+{% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
+{% endif %}
+{% if data.is_deterministic is defined %}
+{% set options = options + ['DETERMINISTIC = ' ~ data.is_deterministic|qtLiteral(conn)] %}
+{% endif %}
+{% if data.rules %}
+{% set options = options + ['RULES = ' ~ data.rules|qtLiteral(conn)] %}
+{% endif %}
+{% if data.version %}
+{% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
+{% endif %}
+{% endif %}
+{# if user has provided locale only #}
+{% if data.locale %}
+{% if data.locale %}
+ {% set options = options + ['LOCALE = ' ~ data.locale|qtLiteral(conn)] %}
+{% endif %}
+{% if data.provider %}
+{% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
+{% endif %}
+{% if data.is_deterministic is defined %}
+{% set options = options + ['DETERMINISTIC = ' ~ data.is_deterministic|qtLiteral(conn)] %}
+{% endif %}
+{% if data.rules %}
+{% set options = options + ['RULES = ' ~ data.rules|qtLiteral(conn)] %}
+{% endif %}
+{% if data.version %}
+{% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
+{% endif %}
+{% endif %}
+{% if options %}
+({{ options|join(', ') }});
+{% endif %}
+{% endif %}
+{# if user has choosed to copy from existing collation #}
+{% if data.copy_collation %}
+ FROM {{ data.copy_collation }};
+{% endif %}
+{% if data.owner %}
+
+ALTER COLLATION {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.description %}
+
+COMMENT ON COLLATION {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..976dd8802656eb03d74da6525c965f64fa96e37b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/12_plus/properties.sql
@@ -0,0 +1,10 @@
+SELECT c.oid, c.collname AS name, c.collcollate AS lc_collate, c.collctype AS lc_type,
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, c.collisdeterministic AS is_deterministic, c.collversion AS version,
+ c.collprovider AS provider, des.description, n.nspname AS schema
+
+FROM pg_catalog.pg_collation c
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
+WHERE c.collnamespace = {{scid}}::oid
+{% if coid %} AND c.oid = {{coid}}::oid {% endif %}
+ORDER BY c.collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/15_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/15_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8fa6f6c0ef38df29398006a4829d6871568c030b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/15_plus/properties.sql
@@ -0,0 +1,10 @@
+SELECT c.oid, c.collname AS name, COALESCE(c.collcollate, c.colliculocale) AS lc_collate,
+ COALESCE(c.collctype, c.colliculocale) AS lc_type, c.collisdeterministic AS is_deterministic, c.collversion AS version,
+ c.collprovider AS provider,
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, description, n.nspname AS schema
+FROM pg_catalog.pg_collation c
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
+WHERE c.collnamespace = {{scid}}::oid
+{% if coid %} AND c.oid = {{coid}}::oid {% endif %}
+ORDER BY c.collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/16_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/16_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ef0f510849252209843521dc108e65759e33ecc9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/16_plus/properties.sql
@@ -0,0 +1,10 @@
+SELECT c.oid, c.collname AS name, COALESCE(c.collcollate, c.colliculocale) AS lc_collate,
+ COALESCE(c.collctype, c.colliculocale) AS lc_type, c.collisdeterministic AS is_deterministic, c.collversion AS version,
+ c.collprovider AS provider, c.collicurules AS rules,
+ pg_catalog.pg_get_userbyid(c.collowner) AS owner, description, n.nspname AS schema
+FROM pg_catalog.pg_collation c
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.collnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_collation'::regclass)
+WHERE c.collnamespace = {{scid}}::oid
+{% if coid %} AND c.oid = {{coid}}::oid {% endif %}
+ORDER BY c.collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ba519cc709df52a6aaf7d498c07a4be82025b269
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/backend_support.sql
@@ -0,0 +1,18 @@
+SELECT
+ CASE WHEN nsp.nspname IN ('sys', 'information_schema') THEN true ELSE false END AS dbSupport
+FROM pg_catalog.pg_namespace nsp
+WHERE nsp.oid={{scid}}::oid
+AND (
+ (nspname = 'pg_catalog' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'pgagent' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'information_schema' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname LIKE '_%' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1))
+)
+AND
+ nspname NOT LIKE E'pg\\temp\\%'
+AND
+ nspname NOT LIKE E'pg\\toast_temp\\%'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb36a1e9320deccc3dd1f9ea0a84ed87badb84d7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/count.sql
@@ -0,0 +1,5 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_collation c
+{% if scid %}
+WHERE c.collnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7035e746cf169095c52972a2121dea1336eb446d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/create.sql
@@ -0,0 +1,47 @@
+{% if data %}
+CREATE COLLATION{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if not data.copy_collation %}
+{% set options = [] %}
+{# if user has provided lc_collate & lc_type #}
+{% if data.lc_collate and data.lc_type %}
+{% if data.lc_collate and data.lc_type %}
+ {% set options = options + ['LC_COLLATE = ' ~ data.lc_collate|qtLiteral(conn), 'LC_CTYPE = ' ~ data.lc_type|qtLiteral(conn)] %}
+{% endif %}
+{% if data.provider %}
+{% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
+{% endif %}
+{% if data.version %}
+{% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
+{% endif %}
+{% endif %}
+{# if user has provided locale only #}
+{% if data.locale %}
+{% if data.locale %}
+ {% set options = options + ['LOCALE = ' ~ data.locale|qtLiteral(conn)] %}
+{% endif %}
+{% if data.provider %}
+{% set options = options + ['PROVIDER = ' ~ data.provider|qtLiteral(conn)] %}
+{% endif %}
+{% if data.version %}
+{% set options = options + ['VERSION = ' ~ data.version|qtLiteral(conn)] %}
+{% endif %}
+{% endif %}
+{% if options %}
+({{ options|join(', ') }});
+{% endif %}
+{% endif %}
+{# if user has choosed to copy from existing collation #}
+{% if data.copy_collation %}
+ FROM {{ data.copy_collation }};
+{% endif %}
+{% if data.owner %}
+
+ALTER COLLATION {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.description %}
+
+COMMENT ON COLLATION {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..958885c7d476a5946aca76a0798d31dcbc423367
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP COLLATION IF EXISTS {{ conn|qtIdent(nspname, name) }}{% if cascade%} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4a531560d7047225b862a836f8ae72fb3def7b4e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_collations.sql
@@ -0,0 +1,7 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
+ ELSE '' END AS copy_collation
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE c.collnamespace=n.oid
+ORDER BY nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bde071ed112e6eaf7384c84ad7871e2186e1f783
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/collations/templates/collations/sql/default/get_name.sql
@@ -0,0 +1,5 @@
+SELECT nspname AS schema, collname AS name
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE c.collnamespace = n.oid AND
+ n.oid = {{ scid }}::oid AND
+ c.oid = {{ coid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..929adc81a0fd7926327006d104d4146a7c03e475
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/__init__.py
@@ -0,0 +1,1030 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements the Domain Node."""
+
+from functools import wraps
+
+import json
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule, DataTypeReader
+from pgadmin.browser.server_groups.servers.databases.utils import \
+ parse_sec_labels_from_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class DomainModule(SchemaChildModule):
+ """
+ class DomainModule(SchemaChildModule):
+
+ This class represents The Domain Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Domain Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the domain collection node.
+
+ * script_load()
+ - Load the module script for domain, when schema node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'domain'
+ _COLLECTION_LABEL = gettext("Domains")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the domain collection node.
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=DomainView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for domain, when schema node is
+ initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+ def register(self, app, options):
+ """
+ Override the default register function to automagically register
+ sub-modules at once.
+ """
+ from .domain_constraints import blueprint as module
+ self.submodules.append(module)
+ super().register(app, options)
+
+
+blueprint = DomainModule(__name__)
+
+
+class DomainView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
+ """
+ class DomainView
+
+ This class inherits PGChildNodeView to get the different routes for
+ the module. Also, inherits DataTypeReader to get data types.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Domain.
+
+ Methods:
+ -------
+ * validate_request(f):
+ - Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid, doid):
+ - List the Domains.
+
+ * nodes(gid, sid, did, scid):
+ - Returns all the Domains to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, doid):
+ - Returns the Domain properties.
+
+ * get_collations(gid, sid, did, scid, doid=None):
+ - Returns Collations.
+
+ * create(gid, sid, did, scid):
+ - Creates a new Domain object.
+
+ * update(gid, sid, did, scid, doid):
+ - Updates the Domain object.
+
+ * delete(gid, sid, did, scid, doid):
+ - Drops the Domain object.
+
+ * sql(gid, sid, did, scid, doid=None):
+ - Returns the SQL for the Domain object.
+
+ * msql(gid, sid, did, scid, doid=None):
+ - Returns the modified SQL.
+
+ * get_sql(gid, sid, data, scid, doid=None):
+ - Generates the SQL statements to create/update the Domain object.
+
+ * dependents(gid, sid, did, scid, doid):
+ - Returns the dependents for the Domain object.
+
+ * dependencies(gid, sid, did, scid, doid):
+ - Returns the dependencies for the Domain object.
+
+ * types(gid, sid, did, scid, fnid=None):
+ - Returns Data Types.
+
+ * compare(**kwargs):
+ - This function will compare the domain nodes from two different
+ schemas.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Domain"
+ BASE_TEMPLATE_PATH = 'domains/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'doid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
+ 'get_collations': [
+ {'get': 'get_collations'},
+ {'get': 'get_collations'}
+ ],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ keys_to_ignore = ['oid', 'basensp', 'conoid', 'nspname', 'oid-2']
+
+ @staticmethod
+ def _get_req_data(kwargs):
+ """
+ Get req data from request.
+ :param kwargs: kwargs.
+ :return: if any error return error, else return req.
+ """
+ if request.data:
+ req = json.loads(request.data)
+ else:
+ req = request.args or request.form
+
+ if 'doid' not in kwargs:
+ required_args = [
+ 'name',
+ 'basetype'
+ ]
+
+ for arg in required_args:
+ if arg not in req or req[arg] == '':
+ return req, True, make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg),
+ )
+ return req, False, ''
+
+ @staticmethod
+ def _get_data(req):
+ """
+ Get data from request and update required values.
+ :param req: request object.
+ :return: data.
+ """
+ data = {}
+ list_params = []
+ if request.method == 'GET':
+ list_params = ['constraints', 'seclabels']
+
+ for key in req:
+ if (
+ key in list_params and req[key] != '' and
+ req[key] is not None
+ ):
+ # Coverts string into python list as expected.
+ data[key] = json.loads(req[key])
+ elif key == 'typnotnull':
+ if req[key] == 'true' or req[key] is True:
+ data[key] = True
+ elif req[key] == 'false' or req[key] is False:
+ data[key] = False
+ else:
+ data[key] = ''
+ else:
+ data[key] = req[key]
+ return data
+
+ def validate_request(f):
+ """
+ Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ Required Args:
+ name: Name of the Domain
+ owner: Domain Owner
+ basensp: Schema Name
+ basetype: Data Type of the Domain
+
+ Above both the arguments will not be validated in the update action.
+ """
+
+ @wraps(f)
+ def wrap(self, **kwargs):
+
+ req, is_error, errmsg = DomainView._get_req_data(kwargs)
+ if is_error:
+ return errmsg
+
+ try:
+ data = DomainView._get_data(req)
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ self.request = data
+ return f(self, **kwargs)
+
+ return wrap
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks database connection status.
+ Attach connection object and template path.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+ # Get database connection
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # we will set template path for sql scripts
+ self.template_path = \
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ List the Domains.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
+ scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ Returns all the Domains to generate Nodes in the browser.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
+ scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-domain",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, doid):
+ """
+ This function will fetch the properties of the domain node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
+ doid=doid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-domain"
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, doid):
+ """
+ Returns the Domain properties.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+ status, res = self._fetch_properties(did, scid, doid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, did, scid, doid):
+ """
+ This function is used to fecth the properties of specified object.
+ :param did:
+ :param scid:
+ :param doid:
+ :return:
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(gettext("""
+Could not find the domain in the database.
+It may have been removed by another user or moved to another schema.
+"""))
+
+ data = res['rows'][0]
+
+ # Get Type Length and Precision
+ data.update(self._parse_type(data['fulltype']))
+
+ # Get Domain Constraints
+ SQL = render_template("/".join([self.template_path,
+ self._GET_CONSTRAINTS_SQL]),
+ doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ data['constraints'] = res['rows']
+
+ # Get formatted Security Labels
+ if 'seclabels' in data:
+ data.update(parse_sec_labels_from_db(data['seclabels']))
+
+ # Set System Domain Status
+ data['sysdomain'] = False
+ if doid <= self._DATABASE_LAST_SYSTEM_OID or \
+ self.datistemplate:
+ data['sysdomain'] = True
+
+ return True, data
+
+ def _parse_type(self, basetype):
+ """
+ Returns Type and Data Type from the basetype.
+ """
+ typ_len = ''
+ typ_precision = ''
+
+ # The Length and the precision of the Datatype should be separate.
+ # The Format we getting from database is: numeric(1,1)
+ # So, we need to separate Length: 1, Precision: 1
+
+ if basetype != '' and basetype.find("(") > 0:
+ substr = basetype[basetype.find("(") + 1:len(
+ basetype) - 1]
+ typlen = substr.split(",")
+ typ_len = typlen[0]
+ if len(typlen) > 1:
+ typ_precision = typlen[1]
+ else:
+ typ_precision = ''
+
+ return {'typlen': typ_len, 'precision': typ_precision}
+
+ @check_precondition
+ def get_collations(self, gid, sid, did, scid, doid=None):
+ """
+ Returns Collations.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+
+ res = [{'label': '', 'value': ''}]
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_collations.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append({'label': row['copy_collation'],
+ 'value': row['copy_collation']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def types(self, gid, sid, did, scid, doid=None):
+ """
+ Returns the Data Types.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ condition = """typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r')
+AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class
+WHERE relnamespace=typnamespace AND relname = typname AND relkind != 'c') AND
+(typname NOT LIKE '_%' OR NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class WHERE
+relnamespace=typnamespace AND relname = substring(typname FROM 2)::name
+AND relkind != 'c'))"""
+
+ # To show hidden objects
+ if not self.blueprint.show_system_objects:
+ condition += " AND nsp.nspname != 'information_schema'"
+
+ # Get Types
+ status, types = self.get_types(self.conn, condition)
+
+ if not status:
+ return internal_server_error(errormsg=types)
+
+ return make_json_response(
+ data=types,
+ status=200
+ )
+
+ @check_precondition
+ @validate_request
+ def create(self, gid, sid, did, scid):
+ """
+ Creates a new Domain object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+
+ Required Args:
+ name: Domain Name
+ owner: Owner Name
+ basensp: Schema Name
+ basetype: Domain Base Type
+
+ Returns:
+ Domain object in json format.
+ """
+
+ data = self.request
+ SQL, _ = self.get_sql(gid, sid, data, scid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need oid to add object in tree at browser, below sql will
+ # gives the same
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ basensp=data['basensp'],
+ name=data['name'],
+ conn=self.conn)
+ status, doid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=doid)
+
+ # Get updated schema oid
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ doid=doid,
+ conn=self.conn)
+ status, scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=scid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ doid,
+ scid,
+ data['name'],
+ icon="icon-domain"
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, doid=None, only_sql=False):
+ """
+ Drops the Domain object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ only_sql: Return only sql if True
+ """
+ if doid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [doid]}
+
+ cascade = self._check_cascade_operation(only_sql)
+
+ for doid in data['ids']:
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ scid=scid, doid=doid)
+ status, res = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ name = res['rows'][0]['name']
+ basensp = res['rows'][0]['basensp']
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=name, basensp=basensp, cascade=cascade)
+
+ # Used for schema diff tool
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Domain dropped")
+ )
+
+ @check_precondition
+ @validate_request
+ def update(self, gid, sid, did, scid, doid):
+ """
+ Updates the Domain object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+
+ SQL, name = self.get_sql(gid, sid, self.request, scid, doid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Get Schema Id
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ doid=doid,
+ conn=self.conn)
+ status, scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=scid)
+
+ other_node_info = {}
+ if 'description' in self.request:
+ other_node_info['description'] = self.request['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ doid,
+ scid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, doid=None, **kwargs):
+ """
+ Returns the SQL for the Domain object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+ if target_schema:
+ data['basensp'] = target_schema
+
+ # Get Type Length and Precision
+ data.update(self._parse_type(data['fulltype']))
+
+ # Get Domain Constraints
+ SQL = render_template("/".join([self.template_path,
+ self._GET_CONSTRAINTS_SQL]),
+ doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ data['constraints'] = res['rows']
+
+ # Get formatted Security Labels
+ if 'seclabels' in data:
+ data.update(parse_sec_labels_from_db(data['seclabels']))
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]), data=data)
+
+ sql_header = """-- DOMAIN: {0}.{1}\n\n""".format(
+ data['basensp'], data['name'])
+
+ sql_header += """-- DROP DOMAIN IF EXISTS {0};\n
+""".format(self.qtIdent(self.conn, data['basensp'], data['name']))
+ SQL = sql_header + SQL
+
+ if not json_resp:
+ return SQL.strip('\n')
+
+ return ajax_response(response=SQL.strip('\n'))
+
+ @check_precondition
+ @validate_request
+ def msql(self, gid, sid, did, scid, doid=None):
+ """
+ Returns the modified SQL.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+
+ Required Args:
+ name: Domain Name
+ owner: Owner Name
+ basensp: Schema Name
+ basetype: Domain Base Type
+
+ Returns:
+ SQL statements to create/update the Domain.
+ """
+
+ try:
+ SQL, _ = self.get_sql(gid, sid, self.request, scid, doid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def check_domain_type(self, data, old_data, is_schema_diff):
+ """
+ Check domain type
+ :return:
+ """
+ # If fulltype or basetype or collname is changed while comparing
+ # two schemas then we need to drop domain and recreate it
+ if 'fulltype' in data or 'basetype' in data or 'collname' in data:
+ SQL = render_template(
+ "/".join([self.template_path, 'domain_schema_diff.sql']),
+ data=data, o_data=old_data)
+ else:
+ if is_schema_diff:
+ data['is_schema_diff'] = True
+
+ SQL = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn)
+ return SQL, data
+
+ def get_sql(self, gid, sid, data, scid, doid=None, is_schema_diff=False):
+ """
+ Generates the SQL statements to create/update the Domain.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ is_schema_diff: True is function gets called from schema diff
+ """
+
+ if doid is not None:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ old_data = res['rows'][0]
+
+ # Get Domain Constraints
+ SQL = render_template("/".join([self.template_path,
+ self._GET_CONSTRAINTS_SQL]),
+ doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ con_data = {}
+ for c in res['rows']:
+ con_data[c['conoid']] = c
+
+ old_data['constraints'] = con_data
+
+ SQL, data = self.check_domain_type(data, old_data, is_schema_diff)
+ return SQL.strip('\n'), data['name'] if 'name' in data else \
+ old_data['name']
+ else:
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data)
+ return SQL.strip('\n'), data['name']
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, doid):
+ """
+ This function get the dependents and return ajax response
+ for the Domain node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+ dependents_result = self.get_dependents(self.conn, doid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, doid):
+ """
+ This function get the dependencies and return ajax response
+ for the Domain node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, doid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the domains for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODE_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(did, scid, row['oid'])
+
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.get_sql(gid=gid, sid=sid, scid=scid,
+ data=data, doid=oid, is_schema_diff=True)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, doid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, doid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, doid=oid,
+ json_resp=False)
+ return sql
+
+ def get_dependencies(self, conn, object_id, where=None,
+ show_system_objects=None, is_schema_diff=False):
+ """
+ This function is used to get dependencies of domain and it's
+ domain constraints.
+ """
+ domain_dependencies = []
+ domain_deps = super().get_dependencies(
+ conn, object_id, where=None, show_system_objects=None,
+ is_schema_diff=True)
+ if len(domain_deps) > 0:
+ domain_dependencies.extend(domain_deps)
+
+ # Get Domain Constraints
+ SQL = render_template("/".join([self.template_path,
+ self._GET_CONSTRAINTS_SQL]),
+ doid=object_id)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ # Get the domain constraints dependencies.
+ for row in res['rows']:
+ constraint_deps = super().get_dependencies(
+ conn, row['conoid'], where=None, show_system_objects=None,
+ is_schema_diff=True)
+ if len(constraint_deps) > 0:
+ domain_dependencies.extend(constraint_deps)
+
+ return domain_dependencies
+
+
+SchemaDiffRegistry(blueprint.node_type, DomainView)
+DomainView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..beb7606f9cc4c4c0c45a7940d17eda0e60dd0034
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/__init__.py
@@ -0,0 +1,770 @@
+
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements the Domain Constraint Module."""
+
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers.databases.schemas import domains
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.utils.exception import ObjectGone
+
+
+class DomainConstraintModule(CollectionNodeModule):
+ """
+ class DomainConstraintModule(CollectionNodeModule):
+
+ This class represents The Domain Constraint Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Domain Constraint Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Domain Constraint collection node.
+
+ * node_inode(gid, sid, did, scid)
+ - Returns Domain Constraint node as leaf node.
+
+ * script_load()
+ - Load the module script for the Domain Constraint, when any of the
+ Domain node is initialized.
+ """
+ _NODE_TYPE = 'domain_constraints'
+ _COLLECTION_LABEL = gettext("Domain Constraints")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid, doid):
+ """
+ Generate the Domain Constraint collection node.
+ """
+ yield self.generate_browser_collection_node(doid)
+
+ @property
+ def node_inode(self):
+ """
+ Returns Domain Constraint node as leaf node.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for the Domain Constraint, when any of the
+ Domain node is initialized.
+ """
+ return domains.DomainModule.node_type
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ return [
+ render_template(
+ "domain_constraints/css/domain_constraints.css",
+ node_type=self.node_type
+ )
+ ]
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = DomainConstraintModule(__name__)
+
+
+class DomainConstraintView(PGChildNodeView):
+ """
+ class DomainConstraintView(PGChildNodeView):
+
+ This class inherits PGChildNodeView to get the different routes for
+ the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Domain Constraint.
+
+ Methods:
+ -------
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid, doid):
+ - List the Domain Constraints.
+
+ * nodes(gid, sid, did, scid):
+ - Returns all the Domain Constraints to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, doid):
+ - Returns the Domain Constraint properties.
+
+ * create(gid, sid, did, scid):
+ - Creates a new Domain Constraint object.
+
+ * update(gid, sid, did, scid, doid):
+ - Updates the Domain Constraint object.
+
+ * delete(gid, sid, did, scid, doid):
+ - Drops the Domain Constraint object.
+
+ * sql(gid, sid, did, scid, doid=None):
+ - Returns the SQL for the Domain Constraint object.
+
+ * msql(gid, sid, did, scid, doid=None):
+ - Returns the modified SQL.
+
+ * get_sql(gid, sid, data, scid, doid=None):
+ - Generates the SQL statements to create/update the Domain Constraint.
+ object.
+
+ * dependents(gid, sid, did, scid, doid, coid):
+ - Returns the dependents for the Domain Constraint object.
+
+ * dependencies(gid, sid, did, scid, doid, coid):
+ - Returns the dependencies for the Domain Constraint object.
+ """
+ node_type = blueprint.node_type
+ node_label = "Domain Constraint"
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'doid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'coid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ @staticmethod
+ def _get_req_data(kwargs):
+ """
+ Get data from request.
+ :param kwargs: kwargs for request.
+ :return: if any error return error with error msg else return req data
+ """
+ if request.data:
+ req = json.loads(request.data)
+ else:
+ req = request.args or request.form
+
+ if 'coid' not in kwargs:
+ required_args = [
+ 'name',
+ 'consrc'
+ ]
+
+ for arg in required_args:
+ if arg not in req or req[arg] == '':
+ return True, make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ ), req
+ return False, '', req
+
+ def validate_request(f):
+ """
+ Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ Required Args:
+ name: Name of the Domain Constraint
+ consrc: Check Constraint Definition
+
+ Above both the arguments will not be validated in the update action.
+ """
+
+ @wraps(f)
+ def wrap(self, **kwargs):
+
+ data = {}
+ is_error, errmsg, req = DomainConstraintView._get_req_data(kwargs)
+ if is_error:
+ return errmsg
+
+ try:
+ for key in req:
+ if key == 'convalidated':
+ data[key] = True if (req[key] == 'true' or req[key] is
+ True) else False
+ else:
+ data[key] = req[key]
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ self.request = data
+ return f(self, **kwargs)
+
+ return wrap
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks database connection status.
+ Attach connection object and template path.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = 'domain_constraints/sql/#{0}#'.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, doid):
+ """
+ List the Domain Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, doid):
+ """
+ Returns all the Domain Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ if 'convalidated' not in row:
+ icon = 'icon-domain_constraints'
+ elif row['convalidated']:
+ icon = 'icon-domain_constraints'
+ else:
+ icon = 'icon-domain_constraints-bad'
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ doid,
+ row['name'],
+ icon=icon,
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, doid, coid):
+ """
+ Returns all the Domain Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ coid=coid)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ if 'convalidated' not in row:
+ icon = 'icon-domain_constraints'
+ elif row['convalidated']:
+ icon = 'icon-domain_constraints'
+ else:
+ icon = 'icon-domain_constraints-bad'
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ doid,
+ row['name'],
+ icon=icon
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, doid, coid):
+ """
+ Returns the Domain Constraints property.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+ data['is_sys_obj'] = (
+ data['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ @check_precondition
+ @validate_request
+ def create(self, gid, sid, did, scid, doid):
+ """
+ Creates a new Domain Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+
+ Returns:
+ Domain Constraint object in json format.
+ """
+ data = self.request
+ try:
+ status, SQL, _ = self.get_sql(gid, sid, data, scid, doid)
+ if not status:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Get the recently added constraints oid
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ doid=doid, name=data['name'],
+ conn=self.conn)
+ status, coid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=coid)
+
+ if 'convalidated' not in data:
+ icon = 'icon-domain_constraints'
+ elif 'convalidated' in data and data['convalidated']:
+ icon = 'icon-domain_constraints'
+ else:
+ icon = 'icon-domain_constraints-bad'
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ coid,
+ doid,
+ data['name'],
+ icon=icon
+ )
+ )
+ except ObjectGone:
+ raise
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, doid, coid=None):
+ """
+ Drops the Domain Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ if coid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [coid]}
+
+ try:
+ for coid in data['ids']:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Domain Constraint dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ @validate_request
+ def update(self, gid, sid, did, scid, doid, coid):
+ """
+ Updates the Domain Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ data = self.request
+ status, SQL, name = self.get_sql(gid, sid, data, scid, doid, coid)
+ if not status:
+ return SQL
+
+ try:
+ if SQL and status:
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if 'convalidated' in data and data['convalidated']:
+ icon = 'icon-domain_constraints'
+ elif 'convalidated' in data and not data['convalidated']:
+ icon = 'icon-domain_constraints-bad'
+ else:
+ icon = ''
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ coid,
+ doid,
+ name,
+ icon=icon,
+ **other_node_info
+ )
+ )
+ else:
+ return make_json_response(
+ success=1,
+ info="Nothing to update",
+ data={
+ 'id': coid,
+ 'doid': doid,
+ 'scid': scid,
+ 'sid': sid,
+ 'gid': gid,
+ 'did': did
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, doid, coid=None):
+ """
+ Returns the SQL for the Domain Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+
+ # Get Schema and Domain.
+ schema, domain = self._get_domain(doid)
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, domain=domain, schema=schema)
+
+ sql_header = """-- CHECK: {1}.{0}
+
+-- ALTER DOMAIN {1} DROP CONSTRAINT {0};
+
+""".format(self.qtIdent(self.conn, data['name']),
+ self.qtIdent(self.conn, schema, domain))
+
+ SQL = sql_header + SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ @validate_request
+ def msql(self, gid, sid, did, scid, doid, coid=None):
+ """
+ Returns the modified SQL.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+
+ Returns:
+ Domain Constraint object in json format.
+ """
+ data = self.request
+
+ status, SQL, _ = self.get_sql(gid, sid, data, scid, doid, coid)
+ if status and SQL:
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ else:
+ return SQL
+
+ def get_sql(self, gid, sid, data, scid, doid, coid=None):
+ """
+ Generates the SQL statements to create/update the Domain Constraint.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ try:
+ if coid is not None:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ doid=doid, coid=coid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ old_data = res['rows'][0]
+
+ SQL = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ else:
+ schema, domain = self._get_domain(doid)
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, domain=domain, schema=schema)
+ if 'name' in data:
+ return True, SQL.strip('\n'), data['name']
+ else:
+ return True, SQL.strip('\n'), old_data['name']
+ except ObjectGone:
+ raise
+ except Exception as e:
+ return False, internal_server_error(errormsg=str(e)), None
+
+ def _get_domain(self, doid):
+ """
+ Returns Domain and Schema name.
+
+ Args:
+ doid: Domain Id
+
+ """
+ SQL = render_template("/".join([self.template_path,
+ 'get_domain.sql']),
+ doid=doid)
+ status, res = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ raise ObjectGone(self.not_found_error_msg('Domain'))
+
+ return res['rows'][0]['schema'], res['rows'][0]['domain']
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, doid, coid):
+ """
+ This function get the dependents and return ajax response
+ for the Domain Constraint node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ dependents_result = self.get_dependents(self.conn, coid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, doid, coid):
+ """
+ This function get the dependencies and return ajax response
+ for the Domain Constraint node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Domain Id
+ coid: Domain Constraint Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, coid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+
+DomainConstraintView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/coll-domain_constraints.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/coll-domain_constraints.svg
new file mode 100644
index 0000000000000000000000000000000000000000..9e180f9dbe928ca892deebb5fe1e76efbd3ed955
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/coll-domain_constraints.svg
@@ -0,0 +1 @@
+coll-domain_constraints
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints-bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints-bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..566f5aa07d1f5dede5d048854b29a30c691c1008
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints-bad.svg
@@ -0,0 +1 @@
+domain_constraints-bad
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b12455588d0745294ab1afb3cac983d9a0bd1900
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/img/domain_constraints.svg
@@ -0,0 +1 @@
+domain_constraints
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.js
new file mode 100644
index 0000000000000000000000000000000000000000..886ea36f04ff9e34f01beba6cebd3dd2c85ff9e8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.js
@@ -0,0 +1,79 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import DomainConstraintSchema from './domain_constraints.ui';
+
+// Domain Constraint Module: Collection and Node
+define('pgadmin.node.domain_constraints', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChildTreeNode) {
+
+ // Define Domain Constraint Collection Node
+ if (!pgBrowser.Nodes['coll-domain_constraints']) {
+ pgAdmin.Browser.Nodes['coll-domain_constraints'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'domain_constraints',
+ label: gettext('Domain Constraints'),
+ type: 'coll-domain_constraints',
+ columns: ['name', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: false,
+ });
+ }
+
+ // Domain Constraint Node
+ if (!pgBrowser.Nodes['domain_constraints']) {
+ pgAdmin.Browser.Nodes['domain_constraints'] = pgBrowser.Node.extend({
+ type: 'domain_constraints',
+ sqlAlterHelp: 'sql-alterdomain.html',
+ sqlCreateHelp: 'sql-alterdomain.html',
+ dialogHelp: url_for('help.static', {'filename': 'domain_constraint_dialog.html'}),
+ label: gettext('Domain Constraints'),
+ collection_type: 'coll-domain_constraints',
+ hasSQL: true,
+ hasDepends: true,
+ parent_type: ['domain'],
+ Init: function() {
+ // Avoid mulitple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_domain_on_coll', node: 'coll-domain_constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_domain_constraints', node: 'domain_constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_domain_constraints', node: 'domain', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Domain Constraint...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },
+ ]);
+
+ },
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+
+ getSchema: function() {
+ return new DomainConstraintSchema();
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['domain'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..7d7140a9664f5fba030358efe294764b56496c37
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/static/js/domain_constraints.ui.js
@@ -0,0 +1,59 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class DomainConstraintSchema extends BaseUISchema {
+ constructor(initValues) {
+ super({
+ name: undefined,
+ oid: undefined,
+ description: undefined,
+ consrc: undefined,
+ convalidated: true,
+ ...initValues,
+ });
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), type:'text', cell:'text',
+ noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'],
+ }, {
+ id: 'is_sys_obj', label: gettext('System domain constraint?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ }, {
+ id: 'description', label: gettext('Comment'), type: 'multiline', cell:
+ 'text', mode: ['properties', 'create', 'edit'], min_version: 90500,
+ }, {
+ id: 'consrc', label: gettext('Check'), type: 'multiline',
+ group: gettext('Definition'), mode: ['properties', 'create', 'edit'],
+ readonly: function(state) {return !obj.isNew(state); },
+ noEmpty: true,
+ }, {
+ id: 'convalidated', label: gettext('Validate?'), type: 'switch',
+ cell:'boolean', group: gettext('Definition'), min_version: 90200,
+ mode: ['properties', 'create', 'edit'],
+ readonly: function(state) {
+ return !obj.isNew(state) && obj._origData.convalidated;
+ }
+ }
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/css/domain_constraints.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/css/domain_constraints.css
new file mode 100644
index 0000000000000000000000000000000000000000..7ec4afdb37ae88af63ff97b2d0782c56d2dea88f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/css/domain_constraints.css
@@ -0,0 +1,26 @@
+.icon-coll-domain_constraints {
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/coll-domain_constraints.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-check-bad, .icon-domain_constraints-bad {
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/domain_constraints-bad.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-check, .icon-domain_constraints {
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/domain_constraints.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ad993f7ab7a0e0d26187d524b83f8df185505f3e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/create.sql
@@ -0,0 +1,10 @@
+{% if data and schema and domain %}
+ALTER DOMAIN {{ conn|qtIdent(schema, domain) }}
+ ADD CONSTRAINT {{ conn|qtIdent(data.name) }} CHECK ({{ data.consrc }}){% if not data.convalidated %}
+
+ NOT VALID{% endif %};{% if data.description %}
+
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON DOMAIN {{ conn|qtIdent(schema, domain) }}
+ IS '{{ data.description }}';{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..260c3c0a9187ed6504862372bed6f1b706673af5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/delete.sql
@@ -0,0 +1,4 @@
+{% if data %}
+ALTER DOMAIN {{ conn|qtIdent(data.nspname, data.relname) }}
+ DROP CONSTRAINT {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_domain.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_domain.sql
new file mode 100644
index 0000000000000000000000000000000000000000..373cff2be7a20a201a523b04f503ba32c6a59939
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_domain.sql
@@ -0,0 +1,8 @@
+SELECT
+ d.typname as domain, bn.nspname as schema
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+WHERE
+ d.oid = {{doid}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2739ae8acdc9a757de7a540f1527aac638f0a47a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_oid.sql
@@ -0,0 +1,7 @@
+SELECT
+ oid, conname as name
+FROM
+ pg_catalog.pg_constraint
+WHERE
+ contypid = {{doid}}::oid
+ AND conname={{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_type_category.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_type_category.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3d92443f1c7cf1942866f49342b4f9872ac879c2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/get_type_category.sql
@@ -0,0 +1,5 @@
+SELECT
+ typcategory
+FROM
+ pg_catalog.pg_type
+WHERE typname = {{datatype}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..09a7be5772d140adb3c15813d81733dae8c903b8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/properties.sql
@@ -0,0 +1,22 @@
+SELECT
+ c.oid, conname AS name, typname AS relname, nspname, description,
+ pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') AS consrc,
+ connoinherit, convalidated, convalidated AS convalidated_p
+FROM
+ pg_catalog.pg_constraint c
+JOIN
+ pg_catalog.pg_type t ON t.oid=contypid
+JOIN
+ pg_catalog.pg_namespace nl ON nl.oid=typnamespace
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
+{% if doid %}
+WHERE
+ contype = 'c' AND contypid = {{doid}}::oid
+{% if coid %}
+ AND c.oid = {{ coid }}
+{% endif %}
+{% elif coid %}
+WHERE
+c.oid = {{ coid }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb8bf47c21e97f70991c989db3befdf60e3da269
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/domain_constraints/templates/domain_constraints/sql/default/update.sql
@@ -0,0 +1,13 @@
+{% set name = o_data.name %}
+{% if data.name %}
+{% set name = data.name %}
+ALTER DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};{% endif -%}{% if data.convalidated %}
+
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(name) }};{% endif -%}{% if data.description is defined %}
+
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(name) }} ON DOMAIN {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{ data.description|qtLiteral(conn) }};{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/coll-domain.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/coll-domain.svg
new file mode 100644
index 0000000000000000000000000000000000000000..dd64999b4bb451d2775f2f2b56dbaed87a0cc62f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/coll-domain.svg
@@ -0,0 +1 @@
+coll-domains
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/domain.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/domain.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5730f6f990fbaaf928a00f80d2ad7caea0443a2e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/img/domain.svg
@@ -0,0 +1 @@
+domain
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.js
new file mode 100644
index 0000000000000000000000000000000000000000..2ac41d6a33865439ef650ddbb4ce606644cf618d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.js
@@ -0,0 +1,100 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import DomainSchema from './domain.ui';
+
+// Domain Module: Collection and Node.
+define('pgadmin.node.domain', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ // Define Domain Collection Node
+ if (!pgBrowser.Nodes['coll-domain']) {
+ pgBrowser.Nodes['coll-domain'] =
+ pgBrowser.Collection.extend({
+ node: 'domain',
+ label: gettext('Domains'),
+ type: 'coll-domain',
+ columns: ['name', 'owner', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Domain Node
+ if (!pgBrowser.Nodes['domain']) {
+ pgBrowser.Nodes['domain'] = schemaChild.SchemaChildNode.extend({
+ type: 'domain',
+ sqlAlterHelp: 'sql-alterdomain.html',
+ sqlCreateHelp: 'sql-createdomain.html',
+ dialogHelp: url_for('help.static', {'filename': 'domain_dialog.html'}),
+ label: gettext('Domain'),
+ collection_type: 'coll-domain',
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+ // Avoid mulitple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_domain_on_coll', node: 'coll-domain', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Domain...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_domain', node: 'domain', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Domain...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_domain', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Domain...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },
+ ]);
+
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new DomainSchema(
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ basetype: ()=>getNodeAjaxOptions('get_types', this, treeNodeInfo, itemNodeData, {
+ cacheNode: 'type'
+ }),
+ collation: ()=>getNodeAjaxOptions('get_collations', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ cacheNode: 'schema'
+ }),
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: itemNodeData.label,
+ basensp: itemNodeData.label,
+ }
+ );
+ },
+ });
+
+ }
+
+ return pgBrowser.Nodes['domain'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..c5db4e78b4165c0b159bd84dd34d5606e4e96790
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui.js
@@ -0,0 +1,224 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import { isEmptyString } from 'sources/validators';
+import _ from 'lodash';
+
+export class DomainConstSchema extends BaseUISchema {
+ constructor() {
+ super({
+ conoid: undefined,
+ conname: undefined,
+ consrc: undefined,
+ convalidated: true,
+ });
+ }
+
+ get idAttribute() {
+ return 'conoid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'conname', label: gettext('Name'), cell: 'text', type: 'text',
+ }, {
+ id: 'consrc', label: gettext('Check'), cell: 'text', type: 'text',
+ editable: function(state) {return obj.isNew(state);},
+ }, {
+ id: 'convalidated', label: gettext('Validate?'), cell: 'checkbox',
+ type: 'checkbox',
+ readonly: function(state) {
+ let currCon = _.find(obj.top.origData.constraints, (con)=>con.conoid == state.conoid);
+ return !obj.isNew(state) && currCon.convalidated;
+ },
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ if (isEmptyString(state.conname)) {
+ setError('conname', 'Constraint Name cannot be empty.');
+ return true;
+ } else {
+ setError('conname', null);
+ }
+
+ if (isEmptyString(state.consrc)) {
+ setError('consrc', 'Constraint Check cannot be empty.');
+ return true;
+ } else {
+ setError('consrc', null);
+ }
+ }
+}
+
+export default class DomainSchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ owner: undefined,
+ basensp: undefined,
+ description: undefined,
+ basetype: undefined,
+ typlen: undefined,
+ precision: undefined,
+ typdefault: undefined,
+ typnotnull: undefined,
+ sysdomain: undefined,
+ collname: undefined,
+ constraints: [],
+ seclabels: [],
+ ...initValues,
+ });
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ basetype: [],
+ collation: [],
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'],
+ }, {
+ id: 'owner', label: gettext('Owner'),
+ editable: false, type: 'select', options: this.fieldOptions.role,
+ controlProps: { allowClear: false },
+ }, {
+ id: 'basensp', label: gettext('Schema'),
+ editable: false, type: 'select', options: this.fieldOptions.schema,
+ controlProps: { allowClear: false },
+ mode: ['create', 'edit'],
+ }, {
+ id: 'sysdomain', label: gettext('System domain?'), cell: 'boolean',
+ type: 'switch', mode: ['properties'],
+ }, {
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline',
+ }, {
+ id: 'basetype', label: gettext('Base type'),
+ type: 'select', options: this.fieldOptions.basetype,
+ optionsLoaded: (options) => { obj.type_options = options; },
+ mode:['properties', 'create', 'edit'], group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state);}, noEmpty: true,
+ }, {
+ id: 'typlen', label: gettext('Length'), cell: 'text',
+ type: 'text', group: gettext('Definition'), deps: ['basetype'],
+ readonly: function(state) {return !obj.isNew(state);},
+ disabled: function(state) {
+ // We will store type from selected from combobox
+ let of_type = state.basetype;
+ if(obj.type_options) {
+ // iterating over all the types
+ _.each(obj.type_options, function(o) {
+ // if type from selected from combobox matches in options
+ if ( of_type == o.value ) {
+ // if length is allowed for selected type
+ if(o.length) {
+ // set the values in model
+ state.is_tlength = true;
+ state.min_val = o.min_val;
+ state.max_val = o.max_val;
+ }
+ else
+ state.is_tlength = false;
+ }
+ });
+
+ if(!state.is_tlength) {
+ if(state.typlen) {
+ state.typlen = null;
+ }
+ }
+ }
+ return !state.is_tlength;
+ },
+ }, {
+ id: 'precision', label: gettext('Precision'), cell: 'text',
+ type: 'text', group: gettext('Definition'), deps: ['basetype'],
+ readonly: function(state) {return !obj.isNew(state);},
+ disabled: function(state) {
+ // We will store type from selected from combobox
+ let of_type = state.basetype;
+ if(obj.type_options) {
+ // iterating over all the types
+ _.each(obj.type_options, function(o) {
+ // if type from selected from combobox matches in options
+ if ( of_type == o.value ) {
+ // if precession is allowed for selected type
+ if(o.precision)
+ {
+ // set the values in model
+ state.is_precision = true;
+ state.min_val = o.min_val;
+ state.max_val = o.max_val;
+ }
+ else
+ state.is_precision = false;
+ }
+ });
+
+ if (!state.is_precision) {
+ if(state.precision) {
+ state.precision = null;
+ }
+ }
+ }
+ return !state.is_precision;
+ },
+ }, {
+ id: 'typdefault', label: gettext('Default'), cell: 'text',
+ type: 'text', group: gettext('Definition'),
+ controlProps: {placeholder: gettext('Enter an expression or a value.')},
+ }, {
+ id: 'typnotnull', label: gettext('Not NULL?'), cell: 'boolean',
+ type: 'switch', group: gettext('Definition'),
+ }, {
+ id: 'collname', label: gettext('Collation'), cell: 'text',
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.collation,
+ readonly: function(state) {return !obj.isNew(state);},
+ }, {
+ id: 'constraints', label: gettext('Constraints'), type: 'collection',
+ schema: new DomainConstSchema(),
+ editable: false, group: gettext('Constraints'),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ uniqueCol : ['conname'],
+ }, {
+ id: 'seclabels', label: gettext('Security labels'), type: 'collection',
+ schema: new SecLabelSchema(),
+ editable: false, group: gettext('Security'),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'],
+ min_version: 90200,
+ }
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1bb6660e59466c6542aad686b78a84c697b9e50c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/count.sql
@@ -0,0 +1,9 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+WHERE
+ d.typnamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c8cc08313714a24ade3923dbe06f5ccae72cf2bf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql
@@ -0,0 +1,41 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% if data %}
+CREATE DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
+ 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\"" %}
+
+ COLLATE {{ data.collname }}{% endif %}{% if data.typdefault %}
+
+ DEFAULT {{ data.typdefault }}{% endif %}{% if data.typnotnull %}
+
+ NOT NULL{% endif %};
+
+{% if data.owner %}
+ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }} OWNER TO {{ conn|qtIdent(data.owner) }};{% endif %}
+
+{% if data.constraints %}
+{% for c in data.constraints %}{% if c.conname and c.consrc %}
+
+ALTER DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
+{% if c.description %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
+ IS '{{ c.description }}';
+{% endif %}
+{% endfor -%}
+{% endif %}
+
+{% if data.description %}
+COMMENT ON DOMAIN {{ conn|qtIdent(data.basensp, data.name) }}
+ IS '{{ data.description }}';{% endif -%}
+
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+
+{{ SECLABEL.SET(conn, 'DOMAIN', data.name, r.provider, r.label, data.basensp) }}{% endif -%}
+{% endfor -%}
+{% endif -%}
+
+{% endif -%}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..55edb00d15eea663ac13d3c0d26383b0e7fbb131
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/delete.sql
@@ -0,0 +1,16 @@
+{% if scid and doid %}
+SELECT
+ d.typname as name, bn.nspname as basensp
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+WHERE
+ d.typnamespace = {{scid}}::oid
+AND
+ d.oid={{doid}}::oid;
+{% endif %}
+
+{% if name %}
+DROP DOMAIN IF EXISTS {{ conn|qtIdent(basensp, name) }}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/domain_schema_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/domain_schema_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3c5e152a7737283f22d06d39347c1582e5718dc7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/domain_schema_diff.sql
@@ -0,0 +1,54 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+
+-- WARNING:
+-- We have found the difference in either of datatype or collation,
+-- so we need to drop the existing domain first and re-create it.
+DROP DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }};
+
+CREATE DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ AS {% if data.fulltype %}{{ data.fulltype }}{% else %}{{ o_data.fulltype }}{% endif %}{% if data.collname and data.collname != "pg_catalog.\"default\"" %}
+
+ COLLATE {{ data.collname }}{% endif %}{% if data.typdefault %}
+
+ DEFAULT {{ data.typdefault }}{% endif %}{% if data.typnotnull %}
+
+ NOT NULL{% endif %};
+
+{% if data.owner or o_data.owner %}
+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 %};
+{% endif %}
+{% if data.constraints %}
+{% for c in data.constraints.added %}{% if c.conname and c.consrc %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
+{% if c.description %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ IS '{{ c.description }}';
+{% endif %}
+{% endfor -%}
+{% for c in data.constraints.changed %}{% if c.conname and c.consrc %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% endif -%};
+{% if c.description %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ IS '{{ c.description }}';
+{% endif %}
+{% endfor -%}
+{% endif %}
+
+{% if data.description %}
+COMMENT ON DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ IS '{{ data.description }}';{% endif -%}
+
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+
+{{ SECLABEL.SET(conn, 'DOMAIN', data.name, r.provider, r.label, data.basensp) }}{% endif -%}
+{% endfor -%}
+{% endif -%}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec6f83b5ba1b996de6384d8fb17adc5e2960eee7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_collations.sql
@@ -0,0 +1,10 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(nspname, '."', collname,'"')
+ ELSE '' END AS copy_collation
+FROM
+ pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE
+ c.collnamespace=n.oid
+ORDER BY
+ nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e813a2c911525fb9036fd0d0dbd574ece43e9cb7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_constraints.sql
@@ -0,0 +1,15 @@
+SELECT
+ 'DOMAIN' AS objectkind, c.oid as conoid, conname, typname as relname, nspname, description,
+ pg_catalog.regexp_replace(pg_catalog.pg_get_constraintdef(c.oid, true), E'CHECK \\((.*)\\).*', E'\\1') as consrc, connoinherit, convalidated
+FROM
+ pg_catalog.pg_constraint c
+JOIN
+ pg_catalog.pg_type t ON t.oid=contypid
+JOIN
+ pg_catalog.pg_namespace nl ON nl.oid=typnamespace
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_constraint'::regclass)
+WHERE
+ contype = 'c' AND contypid = {{doid}}::oid
+ORDER BY
+ conname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d43d04c9643d9451cab98372d9a6fdce0a0899b5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/get_oid.sql
@@ -0,0 +1,18 @@
+{% if doid %}
+SELECT
+ d.typnamespace as scid
+FROM
+ pg_catalog.pg_type d
+WHERE
+ d.oid={{ doid }}::oid;
+{% else %}
+SELECT
+ d.oid
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+WHERE
+ bn.nspname = {{ basensp|qtLiteral(conn) }}
+ AND d.typname={{ name|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3f671c76dfeaee830c2f9a2129a83969c5938f28
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/node.sql
@@ -0,0 +1,23 @@
+SELECT
+ d.oid, d.typname as name, pg_catalog.pg_get_userbyid(d.typowner) as owner,
+ bn.nspname as basensp, des.description
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
+{% if scid is defined %}
+WHERE
+ d.typnamespace = {{scid}}::oid
+{% elif doid %}
+WHERE d.oid = {{doid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = d.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ d.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8201ad62277bb111735218c275158b3786faefdd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/properties.sql
@@ -0,0 +1,34 @@
+SELECT
+ 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,
+ c.oid AS colloid, pg_catalog.format_type(b.oid, d.typtypmod) AS fulltype,
+ CASE WHEN length(cn.nspname::text) > 0 AND length(c.collname::text) > 0 THEN
+ pg_catalog.concat(cn.nspname, '."', c.collname,'"')
+ ELSE '' END AS collname,
+ d.typtypmod, d.typnotnull, d.typdefault, d.typndims, d.typdelim, bn.nspname as basensp,
+ description, (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=d.typname) > 1 AS domisdup,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t3 WHERE t3.typname=b.typname) > 1 AS baseisdup,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=d.oid) AS seclabels
+FROM
+ pg_catalog.pg_type d
+JOIN
+ pg_catalog.pg_type b ON b.oid = d.typbasetype
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=d.typnamespace
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=d.oid AND des.classoid='pg_type'::regclass)
+LEFT OUTER JOIN
+ pg_catalog.pg_collation c ON d.typcollation=c.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace cn ON c.collnamespace=cn.oid
+WHERE
+ d.typnamespace = {{scid}}::oid
+{% if doid %}
+ AND d.oid={{doid}}::oid
+{% endif %}
+ORDER BY
+ d.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4241b505abdfe287d80af8783256fe8fb1b5675d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/update.sql
@@ -0,0 +1,100 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% if data %}
+{% set name = o_data.name %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.typnotnull and not o_data.typnotnull %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ SET NOT NULL;
+{% elif 'typnotnull' in data and not data.typnotnull and o_data.typnotnull%}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP NOT NULL;
+{% endif -%}{% if data.typdefault %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ SET DEFAULT {{ data.typdefault }};
+{% elif (data.typdefault == '' or data.typdefault == None) and data.typdefault != o_data.typdefault %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP DEFAULT;
+{% endif -%}{% if data.owner %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif -%}{% if data.constraints %}
+{% for c in data.constraints.deleted %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP CONSTRAINT {{ conn|qtIdent(o_data['constraints'][c.conoid]['conname']) }};
+{% endfor -%}
+{% if data.is_schema_diff is defined and data.is_schema_diff %}
+{% for c in data.constraints.changed %}
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP CONSTRAINT {{ conn|qtIdent(c.conname) }};
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif -%};
+
+{% if c.description is defined and c.description != '' %}
+COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ IS {{ c.description|qtLiteral(conn) }};{% endif %}
+{% endfor -%}
+{% else %}
+{% for c in data.constraints.changed %}
+{% if c.conname and c.conname !=o_data['constraints'][c.conoid]['conname'] %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data['constraints'][c.conoid]['conname']) }} TO {{ conn|qtIdent(c.conname) }};
+{% endif %}
+{% if c.convalidated and not o_data['constraints'][c.conoid]['convalidated'] %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(c.conname) }};
+{% endif %}
+{% endfor -%}
+{% endif %}
+{% for c in data.constraints.added %}
+{% if c.conname and c.consrc %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif -%};{% endif -%}
+
+{% if c.description %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(c.conname) }} ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ IS '{{ c.description }}';
+{% endif %}
+{% endfor -%}{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'DOMAIN', name, r.provider, o_data.basensp) }}
+
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'DOMAIN', name, r.provider, r.label, o_data.basensp) }}
+{% endfor %}
+{% endif -%}{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'DOMAIN', name, r.provider, r.label, o_data.basensp) }}
+{% endfor %}
+{% endif -%}{% if data.description is defined and data.description != o_data.description %}
+
+COMMENT ON DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}{% if data.basensp %}
+
+ALTER DOMAIN {{ conn|qtIdent(o_data.basensp, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.basensp) }};{% endif -%}
+{% endif -%}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..384a5fdc39dd1bc61a500a5e7d251cf59873fc48
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py
@@ -0,0 +1,1942 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements the Foreign Table Module."""
+
+import sys
+import re
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify, \
+ current_app
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule, DataTypeReader
+from pgadmin.browser.server_groups.servers.databases.utils import \
+ parse_sec_labels_from_db
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ columns import utils as column_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ triggers import utils as trigger_utils
+
+
+class ForeignTableModule(SchemaChildModule):
+ """
+ class ForeignTableModule(CollectionNodeModule):
+
+ This class represents The Foreign Table Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Foreign Table Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Foreign Table collection node.
+
+ * node_inode():
+ - Override this property to make the Foreign Table node as leaf node.
+
+ * script_load()
+ - Load the module script for Foreign Table, when schema node is
+ initialized.
+ """
+ _NODE_TYPE = 'foreign_table'
+ _COLLECTION_LABEL = gettext("Foreign Tables")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the Foreign Table collection node.
+ """
+ if self.has_nodes(
+ sid, did, scid,
+ base_template_path=ForeignTableView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for foreign table, when the
+ schema node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+ def register(self, app, options):
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.triggers import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas. \
+ foreign_tables.foreign_table_columns import \
+ foreign_table_column_blueprint as module
+ self.submodules.append(module)
+ super().register(app, options)
+
+
+blueprint = ForeignTableModule(__name__)
+
+
+class ForeignTableView(PGChildNodeView, DataTypeReader,
+ SchemaDiffObjectCompare):
+ """
+ class ForeignTableView(PGChildNodeView)
+
+ This class inherits PGChildNodeView to get the different routes for
+ the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Foreign Table.
+
+ Methods:
+ -------
+ * validate_request(f):
+ - Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid):
+ - List the Foreign Table.
+
+ * nodes(gid, sid, did, scid):
+ - Returns all the Foreign Table to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, foid):
+ - Returns the Foreign Table properties.
+
+ * get_collations(gid, sid, did, scid, foid=None):
+ - Returns Collations.
+
+ * get_types(gid, sid, did, scid, foid=None):
+ - Returns Data Types.
+
+ * get_foreign_servers(gid, sid, did, scid, foid=None):
+ - Returns the Foreign Servers.
+
+ * get_tables(gid, sid, did, scid, foid=None):
+ - Returns the Foreign Tables as well as Plain Tables.
+
+ * get_columns(gid, sid, did, scid, foid=None):
+ - Returns the Table Columns.
+
+ * create(gid, sid, did, scid):
+ - Creates a new Foreign Table object.
+
+ * update(gid, sid, did, scid, foid):
+ - Updates the Foreign Table object.
+
+ * delete(gid, sid, did, scid, foid):
+ - Drops the Foreign Table object.
+
+ * sql(gid, sid, did, scid, foid):
+ - Returns the SQL for the Foreign Table object.
+
+ * msql(gid, sid, did, scid, foid=None):
+ - Returns the modified SQL.
+
+ * get_sql(gid, sid, data, scid, foid=None):
+ - Generates the SQL statements to create/update the Foreign Table object.
+
+ * dependents(gid, sid, did, scid, foid):
+ - Returns the dependents for the Foreign Table object.
+
+ * dependencies(gid, sid, did, scid, foid):
+ - Returns the dependencies for the Foreign Table object.
+
+ * select_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * insert_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * update_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * delete_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * compare(**kwargs):
+ - This function will compare the foreign table nodes from two different
+ schemas.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Foreign Table"
+ BASE_TEMPLATE_PATH = 'foreign_tables/sql/#{0}#'
+ double_newline = '\n\n'
+ pattern = '\n{2,}'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'foid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_collations': [
+ {'get': 'get_collations'},
+ {'get': 'get_collations'}
+ ],
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
+ 'get_foreign_servers': [{'get': 'get_foreign_servers'},
+ {'get': 'get_foreign_servers'}],
+ 'get_tables': [{'get': 'get_tables'}, {'get': 'get_tables'}],
+ 'set_trigger': [{'put': 'enable_disable_triggers'}],
+ 'get_columns': [{'get': 'get_columns'}, {'get': 'get_columns'}],
+ 'select_sql': [{'get': 'select_sql'}],
+ 'insert_sql': [{'get': 'insert_sql'}],
+ 'update_sql': [{'get': 'update_sql'}],
+ 'delete_sql': [{'get': 'delete_sql'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ keys_to_ignore = ['oid', 'basensp', 'oid-2', 'attnum', 'strftoptions']
+
+ def validate_request(f):
+ """
+ Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ Required Args:
+ name: Name of the Foreign Table
+ ftsrvname: Foreign Server Name
+
+ Above both the arguments will not be validated in the update action.
+ """
+
+ @wraps(f)
+ def wrap(self, **kwargs):
+
+ if request.data:
+ req = json.loads(request.data)
+ else:
+ req = request.args or request.form
+
+ invalid, arg = self._check_valid_foid_input(kwargs, req)
+
+ if invalid:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ try:
+ if request.method == 'GET':
+ list_params = ['constraints', 'columns', 'ftoptions',
+ 'seclabels', 'inherits', 'acl']
+ else:
+ list_params = ['inherits']
+
+ data = self._validate_req(req, list_params)
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ self.request = data
+ return f(self, **kwargs)
+
+ return wrap
+
+ @staticmethod
+ def _check_valid_foid_input(kwargs, req):
+
+ """
+ check for valid Foreign Table id
+ :param kwargs: user input
+ :param req: request object
+ """
+
+ if 'foid' not in kwargs:
+ required_args = [
+ 'name',
+ 'ftsrvname'
+ ]
+
+ for arg in required_args:
+ if arg not in req or req[arg] == '':
+ return True, arg
+ return False, ''
+
+ def _validate_req(self, req, list_params):
+
+ """
+ Validate & convert the string to desired output format
+ :param req: request data
+ :param list_params: prepared list of inherit, constraints, etc.
+ :return: data
+ """
+
+ data = {}
+
+ try:
+ for key in req:
+ if (
+ key in list_params and req[key] != '' and
+ req[key] is not None
+ ):
+ # Coverts string into python list as expected.
+ data[key] = []
+ self._convert_string_to_list(req, data, key)
+
+ elif key == 'typnotnull':
+ if req[key] == 'true' or req[key] is True:
+ data[key] = True
+ elif req[key] == 'false' or req[key] is False:
+ data[key] = False
+ else:
+ data[key] = ''
+ else:
+ data[key] = req[key]
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ raise e
+
+ return data
+
+ def _convert_string_to_list(self, req, data, key):
+
+ """
+ Convert the string with utf-8 base to list
+ :param req: request data
+ :param data: output
+ :param key: index for data
+ """
+
+ if not isinstance(req[key], list) and req[key]:
+ data[key] = json.loads(req[key])
+ elif req[key]:
+ data[key] = req[key]
+
+ if key == 'inherits':
+ # Convert Table ids from unicode/string to int
+ # and make tuple for 'IN' query.
+ inherits = tuple([int(x) for x in data[key]])
+
+ if len(inherits) == 1:
+ # Python tupple has , after the first param
+ # in case of single parameter.
+ # So, we need to make it tuple explicitly.
+ inherits = "(" + str(inherits[0]) + ")"
+ if inherits:
+ # Fetch Table Names from their respective Ids,
+ # as we need Table names to generate the SQL.
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._GET_TABLES_SQL]),
+ attrelid=inherits)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if 'inherits' in res['rows'][0]:
+ data[key] = res['rows'][0]['inherits']
+ else:
+ data[key] = []
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks the database connection status.
+ Attaches the connection object and template path to the class object.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+
+ # Get database connection
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.datistemplate = \
+ self.manager.db_info[kwargs['did']]['datistemplate'] \
+ if self.manager.db_info is not None and \
+ kwargs['did'] in self.manager.db_info else False
+
+ # Set template path for sql scripts depending
+ # on the server version.
+ self.template_path = \
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
+
+ self.foreign_table_column_template_path = compile_template_path(
+ 'foreign_table_columns/sql', self.manager.version)
+
+ self.column_template_path = compile_template_path(
+ 'columns/sql', self.manager.version)
+
+ # Template for trigger node
+ self.trigger_template_path = \
+ 'triggers/sql/{0}/#{1}#'.format(self.manager.server_type,
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ List all the Foreign Tables.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+ SQL = render_template("/".join([self.template_path, self._NODE_SQL]),
+ scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ Returns the Foreign Tables to generate the Nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODE_SQL]), scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-foreign_table",
+ description=row['description'],
+ tigger_count=row['triggercount'],
+ has_enable_triggers=row['has_enable_triggers'],
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, foid):
+ """
+ Returns the Foreign Tables to generate the Nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODE_SQL]), foid=foid)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-foreign_table"
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, foid):
+ """
+ Returns the Foreign Table properties.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ @check_precondition
+ def get_collations(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the Collations.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+
+ res = [{'label': '', 'value': ''}]
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_collations.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['copy_collation'],
+ 'value': row['copy_collation']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def types(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the Data Types.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+
+ condition = render_template("/".join(
+ [self.template_path, 'types_condition.sql']),
+ server_type=self.manager.server_type,
+ show_sys_objects=self.blueprint.show_system_objects)
+
+ # Get Types
+ status, types = self.get_types(self.conn, condition)
+
+ if not status:
+ return internal_server_error(errormsg=types)
+
+ return make_json_response(
+ data=types,
+ status=200
+ )
+
+ @check_precondition
+ def get_foreign_servers(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the Foreign Servers.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+ res = [{'label': '', 'value': ''}]
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_foreign_servers.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['srvname'], 'value': row['srvname']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_tables(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the Foreign Tables as well as Plain Tables.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+ res = []
+ try:
+ SQL = render_template("/".join(
+ [self.template_path, self._GET_TABLES_SQL]),
+ foid=foid, server_type=self.manager.server_type,
+ show_sys_objects=self.blueprint.show_system_objects)
+ status, rset = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=rset['rows'],
+ status=200
+ )
+
+ except Exception:
+ _, exc_value, _ = sys.exc_info()
+ return internal_server_error(errormsg=str(exc_value))
+
+ @check_precondition
+ def get_columns(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the Table Columns.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ attrelid: Table oid
+
+ Returns:
+ JSON Array with below parameters.
+ attname: Column Name
+ datatype: Column Data Type
+ inherited_from: Parent Table from which the related column
+ is inheritted.
+ """
+ res = []
+ data = request.args if request.args else None
+ try:
+ if data and 'attrelid' in data:
+ SQL = render_template("/".join([self.template_path,
+ 'get_table_columns.sql']),
+ attrelid=data['attrelid'])
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return make_json_response(
+ data=res['rows'],
+ status=200
+ )
+ except Exception:
+ _, exc_value, _ = sys.exc_info()
+ return internal_server_error(errormsg=str(exc_value))
+
+ @check_precondition
+ @validate_request
+ def create(self, gid, sid, did, scid):
+ """
+ Creates a new Foreign Table object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ name: Foreign Table Name
+ basensp: Schema Name
+ ftsrvname: Foreign Server Name
+
+ Returns:
+ Foreign Table object in json format.
+ """
+ try:
+ # Get SQL to create Foreign Table
+ SQL, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=self.request)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Need oid to add object in the tree at browser.
+ basensp = self.request['basensp'] if ('basensp' in self.request) \
+ else None
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ basensp=basensp,
+ name=self.request['name'],
+ conn=self.conn)
+ status, res = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ foid = res['rows'][0]['oid']
+ scid = res['rows'][0]['scid']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ foid,
+ scid,
+ self.request['name'],
+ icon="icon-foreign_table"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, foid=None, only_sql=False):
+ """
+ Drops the Foreign Table.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ only_sql: Return only sql if True
+ """
+ if foid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [foid]}
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for foid in data['ids']:
+ # Fetch Name and Schema Name to delete the foreign table.
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]), scid=scid,
+ foid=foid)
+ status, res = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ name = res['rows'][0]['name']
+ basensp = res['rows'][0]['basensp']
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=name,
+ basensp=basensp,
+ cascade=cascade)
+
+ # Used for schema diff tool
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Foreign Table dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ @validate_request
+ def update(self, gid, sid, did, scid, foid):
+ """
+ Updates the Foreign Table.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+
+ try:
+ SQL, name = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=self.request, foid=foid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ foid=foid,
+ conn=self.conn)
+ status, res = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ scid = res['rows'][0]['scid']
+
+ other_node_info = {}
+ if 'description' in self.request:
+ other_node_info['description'] = self.request['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ foid,
+ scid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, foid=None, **kwargs):
+ """
+ Returns the SQL for the Foreign Table object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ status, data = self._fetch_properties(gid, sid, did, scid, foid,
+ inherits=True)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ col_data = []
+ for c in data['columns']:
+ if c.get('inheritedfrom', None) is None:
+ col_data.append(c)
+
+ data['columns'] = col_data
+ if target_schema:
+ data['basensp'] = target_schema
+
+ # Parse Privileges
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'],
+ ["a", "r", "w", "x"])
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, is_sql=True,
+ add_not_exists_clause=True,
+ conn=self.conn
+ )
+
+ if not json_resp:
+ return SQL.strip('\n')
+
+ sql_header = """-- FOREIGN TABLE: {0}.{1}\n\n""".format(
+ data['basensp'], data['name'])
+
+ sql_header += """-- DROP FOREIGN TABLE IF EXISTS {0};
+
+""".format(self.qtIdent(self.conn, data['basensp'], data['name']))
+
+ SQL = sql_header + SQL
+
+ trigger_sql = self._get_resql_for_triggers(
+ foid, data['basensp'], data['name'])
+
+ SQL = SQL + trigger_sql
+
+ return ajax_response(response=SQL.strip('\n'))
+
+ @check_precondition
+ @validate_request
+ def msql(self, gid, sid, did, scid, foid=None):
+ """
+ Returns the modified SQL.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ name: Foreign Table Name
+ ftsrvname: Foreign Server Name
+
+ Returns:
+ SQL statements to create/update the Foreign Table.
+ """
+ data = {}
+ for k, v in self.request.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+ except TypeError:
+ data[k] = v
+ try:
+ SQL, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, foid=foid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @staticmethod
+ def _parse_privileges(data):
+ """
+ Parser privilege data as per type.
+ :param data: Data.
+ :return:
+ """
+ if 'relacl' in data and 'added' in data['relacl']:
+ data['relacl']['added'] = parse_priv_to_db(
+ data['relacl']['added'], ["a", "r", "w", "x"])
+ if 'relacl' in data and 'changed' in data['relacl']:
+ data['relacl']['changed'] = parse_priv_to_db(
+ data['relacl']['changed'], ["a", "r", "w", "x"])
+ if 'relacl' in data and 'deleted' in data['relacl']:
+ data['relacl']['deleted'] = parse_priv_to_db(
+ data['relacl']['deleted'], ["a", "r", "w", "x"])
+
+ @staticmethod
+ def _check_old_col_ops(old_col_frmt_options, option, col):
+ """
+ check old column options.
+ :param old_col_frmt_options: old column option data.
+ :param option: option data.
+ :param col: column data.
+ :return:
+ """
+ if (
+ option['option'] in old_col_frmt_options and
+ option['value'] != old_col_frmt_options[option['option']]
+ ):
+ col['coloptions_updated']['changed'].append(option)
+ elif option['option'] not in old_col_frmt_options:
+ col['coloptions_updated']['added'].append(option)
+ if option['option'] in old_col_frmt_options:
+ del old_col_frmt_options[option['option']]
+
+ @staticmethod
+ def _parse_column_options(data):
+ """
+ Parse columns data.
+ :param data: Data.
+ :return:
+ """
+ for c in data['columns']['changed']:
+ old_col_options = []
+ if 'coloptions' in c and c['coloptions']:
+ old_col_options = c['coloptions']
+
+ old_col_frmt_options = {}
+
+ for o in old_col_options:
+ col_opt = o.split("=")
+ old_col_frmt_options[col_opt[0]] = col_opt[1]
+
+ c['coloptions_updated'] = {'added': [],
+ 'changed': [],
+ 'deleted': []}
+
+ if 'coloptions' in c and len(c['coloptions']) > 0:
+ for o in c['coloptions']:
+ ForeignTableView._check_old_col_ops(old_col_frmt_options,
+ o, c)
+
+ for o in old_col_frmt_options:
+ c['coloptions_updated']['deleted'].append(
+ {'option': o})
+
+ def _format_columns_data(self, data, old_data):
+ """
+ Format columns.
+ :param data: data.
+ :param old_data: old data for compare.
+ :return:
+ """
+ col_data = {}
+ # Prepare dict of columns with key = column's attnum
+ # Will use this in the update template when any column is
+ # changed, to identify the columns.
+ for c in old_data['columns']:
+ col_data[c['attnum']] = c
+
+ old_data['columns'] = col_data
+
+ if 'columns' in data and 'added' in data['columns']:
+ data['columns']['added'] = self._format_columns(
+ data['columns']['added'])
+
+ if 'columns' in data and 'changed' in data['columns']:
+ data['columns']['changed'] = self._format_columns(
+ data['columns']['changed'])
+
+ # Parse Column Options
+ ForeignTableView._parse_column_options(data)
+
+ def get_sql(self, **kwargs):
+ """
+ Generates the SQL statements to create/update the Foreign Table.
+
+ Args:
+ kwargs: Server Group Id
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ data = kwargs.get('data')
+ foid = kwargs.get('foid', None)
+ is_schema_diff = kwargs.get('is_schema_diff', False)
+
+ if foid is not None:
+ status, old_data = self._fetch_properties(gid, sid, did, scid,
+ foid, inherits=True)
+ if not status:
+ return old_data
+ elif not old_data:
+ return gone(self.not_found_error_msg())
+
+ if is_schema_diff:
+ data['is_schema_diff'] = True
+ old_data['columns_for_schema_diff'] = old_data['columns']
+
+ # If name is not present in request data
+ if 'name' not in data:
+ data['name'] = old_data['name']
+
+ # If name if not present
+ if 'schema' not in data:
+ data['schema'] = old_data['basensp']
+
+ # Parse Privileges
+ ForeignTableView._parse_privileges(data)
+
+ # If ftsrvname is changed while comparing two schemas
+ # then we need to drop foreign table and recreate it
+ if is_schema_diff and 'ftsrvname' in data:
+ # Modify the data required to recreate the foreign table.
+ self.modify_data_for_schema_diff(data, old_data)
+
+ sql = render_template(
+ "/".join([self.template_path,
+ 'foreign_table_schema_diff.sql']),
+ data=data, o_data=old_data, conn=self.conn)
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+
+ # Removes trailing new lines
+ if sql:
+ sql = sql.strip('\n') + self.double_newline
+
+ # Parse/Format columns & create sql
+ if 'columns' in data:
+ # Parse the data coming from client
+ data = column_utils.parse_format_columns(data, mode='edit')
+
+ columns = data['columns']
+ column_sql = '\n'
+
+ # If column(s) is/are deleted
+ column_sql = self._check_for_column_delete(columns, data,
+ column_sql)
+
+ # If column(s) is/are changed
+ column_sql = self._check_for_column_update(columns, data,
+ column_sql, foid)
+
+ # If column(s) is/are added
+ column_sql = self._check_for_column_add(columns, data,
+ column_sql)
+
+ # Combine all the SQL together
+ sql += column_sql.strip('\n')
+
+ sql = re.sub(self.pattern, self.double_newline, sql)
+ sql = sql.strip('\n')
+
+ return sql, data['name'] if 'name' in data else old_data['name']
+ else:
+ data['columns'] = self._format_columns(data['columns'])
+
+ # Parse Privileges
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'],
+ ["a", "r", "w", "x"])
+
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]), data=data,
+ conn=self.conn)
+ return sql, data['name']
+
+ def _check_for_column_delete(self, columns, data, column_sql):
+ # If column(s) is/are deleted
+ if 'deleted' in columns:
+ for c in columns['deleted']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+ # Sql for drop column
+ if c.get('inheritedfrom', None) is None:
+ column_sql += render_template("/".join(
+ [self.foreign_table_column_template_path,
+ self._DELETE_SQL]),
+ data=c, conn=self.conn).strip('\n') + \
+ self.double_newline
+ return column_sql
+
+ def _check_for_column_update(self, columns, data, column_sql, tid):
+ # Here we will be needing previous properties of column
+ # so that we can compare & update it
+ if 'changed' in columns:
+ for c in columns['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ properties_sql = render_template(
+ "/".join([self.column_template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid,
+ clid=c['attnum'] if 'attnum' in c else None,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(properties_sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ old_col_data = res['rows'][0]
+
+ old_col_data['cltype'], \
+ old_col_data['hasSqrBracket'] = \
+ column_utils.type_formatter(old_col_data['cltype'])
+ old_col_data = \
+ column_utils.convert_length_precision_to_string(
+ old_col_data)
+ old_col_data = column_utils.fetch_length_precision(
+ old_col_data)
+
+ old_col_data['cltype'] = \
+ DataTypeReader.parse_type_name(
+ old_col_data['cltype'])
+
+ # Sql for alter column
+ if c.get('inheritedfrom', None) is None and \
+ c.get('inheritedfromtable', None) is None:
+ column_sql += render_template("/".join(
+ [self.foreign_table_column_template_path,
+ self._UPDATE_SQL]),
+ data=c, o_data=old_col_data, conn=self.conn
+ ).strip('\n') + self.double_newline
+ return column_sql
+
+ def _check_for_column_add(self, columns, data, column_sql):
+ # If column(s) is/are added
+ if 'added' in columns:
+ for c in columns['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ c = column_utils.convert_length_precision_to_string(c)
+
+ if c.get('inheritedfrom', None) is None and \
+ c.get('inheritedfromtable', None) is None:
+ column_sql += render_template("/".join(
+ [self.foreign_table_column_template_path,
+ self._CREATE_SQL]),
+ data=c, conn=self.conn).strip('\n') + \
+ self.double_newline
+ return column_sql
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, foid):
+ """
+ This function get the dependents and return ajax response
+ for the Foreign Table object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+ dependents_result = self.get_dependents(self.conn, foid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, foid):
+ """
+ This function get the dependencies and return ajax response
+ for the Foreign Table object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, foid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ def _format_columns(self, columns):
+ """
+ Format Table Columns.
+ """
+ cols = []
+ for c in columns:
+ if len(c) > 0 and 'cltype' in c:
+ if '[]' in c['cltype']:
+ c['cltype'] = c['cltype'].replace('[]', '')
+ c['isArrayType'] = True
+ else:
+ c['isArrayType'] = False
+ cols.append(c)
+ return cols if cols else columns
+
+ def _fetch_properties(self, gid, sid, did, scid, foid, inherits=False, ):
+ """
+ Returns the Foreign Table properties which will be used in
+ properties, sql and get_sql functions.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ inherits: If True then inherited table will be fetched from
+ database
+
+ Returns:
+
+ """
+ sql = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, foid=foid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return True, False
+
+ data = res['rows'][0]
+ data['is_sys_obj'] = (
+ data['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ if self.manager.version >= 90200:
+ # Fetch privileges
+ sql = render_template("/".join([self.template_path,
+ self._ACL_SQL]),
+ foid=foid)
+ status, aclres = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=aclres)
+
+ # Get Formatted Privileges
+ data.update(self._format_proacl_from_db(aclres['rows']))
+
+ # Get formatted Security Labels
+ if 'seclabels' in data:
+ data.update(parse_sec_labels_from_db(data['seclabels']))
+
+ # Get formatted Options
+ if 'ftoptions' in data:
+ data.update({'strftoptions': data['ftoptions']})
+ data.update(self._parse_variables_from_db(data['ftoptions']))
+
+ sql = render_template("/".join([self.template_path,
+ self._GET_CONSTRAINTS_SQL]), foid=foid)
+ status, cons = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=cons)
+
+ if cons and 'rows' in cons:
+ data['constraints'] = cons['rows']
+
+ sql = render_template("/".join([self.template_path,
+ self._GET_COLUMNS_SQL]), foid=foid)
+ status, cols = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=cols)
+
+ # Fetch length and precision data
+ for col in cols['rows']:
+ column_utils.fetch_length_precision(col)
+
+ if 'attoptions' in col and col['attoptions'] != '':
+ col['attoptions'] = column_utils.parse_column_variables(
+ col['attoptions'])
+
+ if 'attfdwoptions' in col and col['attfdwoptions'] != '':
+ col['coloptions'] = column_utils.parse_options_for_column(
+ col['attfdwoptions'])
+
+ self._get_edit_types(cols['rows'])
+
+ if cols and 'rows' in cols:
+ data['columns'] = cols['rows']
+
+ # Get Inherited table names from their OID
+ is_error, errmsg = self._get_inherited_table_name(data, inherits)
+
+ if is_error:
+ return False, internal_server_error(errormsg=errmsg)
+
+ return True, data
+
+ def _get_edit_types(self, cols):
+ edit_types = {}
+ for col in cols:
+ edit_types[col['atttypid']] = []
+
+ if len(cols) > 0:
+ SQL = render_template("/".join([self.template_path,
+ 'edit_mode_types_multi.sql']),
+ type_ids=",".join(map(lambda x: str(x),
+ edit_types.keys())))
+ _, res = self.conn.execute_2darray(SQL)
+ for row in res['rows']:
+ edit_types[row['main_oid']] = sorted(row['edit_types'])
+
+ for column in cols:
+ edit_type_list = edit_types[column['atttypid']]
+ edit_type_list.append(column['cltype'])
+ column['edit_types'] = sorted(edit_type_list)
+ column['cltype'] = \
+ DataTypeReader.parse_type_name(column['cltype'])
+
+ def _get_datatype_precision(self, cols):
+ """
+ The Length and the precision of the Datatype should be separated.
+ The Format we getting from database is: numeric(1,1)
+ So, we need to separate it as Length: 1, Precision: 1
+ :param cols: list of columns.
+ """
+ for c in cols['rows']:
+ if c['fulltype'] != '' and c['fulltype'].find("(") > 0:
+ substr = self.extract_type_length_precision(c)
+ typlen = substr.split(",")
+ if len(typlen) > 1:
+ c['attlen'] = self.convert_typlen_to_int(typlen)
+ c['attprecision'] = self.convert_precision_to_int(typlen)
+ else:
+ c['attlen'] = self.convert_typlen_to_int(typlen)
+ c['attprecision'] = None
+
+ # Get formatted Column Options
+ if 'attfdwoptions' in c and c['attfdwoptions'] != '':
+ att_opt = self._parse_variables_from_db(c['attfdwoptions'])
+ c['coloptions'] = att_opt['ftoptions']
+
+ def _get_inherited_table_name(self, data, inherits):
+ """
+ Get inherited table name.
+ :param data: Data.
+ :param inherits: flag which is used If True then inherited table
+ will be fetched from database.
+ """
+ if inherits and 'inherits' in data and data['inherits']:
+ inherits = tuple([int(x) for x in data['inherits']])
+ if len(inherits) == 1:
+ inherits = "(" + str(inherits[0]) + ")"
+
+ sql = render_template("/".join([self.template_path,
+ self._GET_TABLES_SQL]),
+ attrelid=inherits)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return True, res
+
+ if 'inherits' in res['rows'][0]:
+ data['inherits'] = res['rows'][0]['inherits']
+
+ return False, ''
+
+ @staticmethod
+ def convert_precision_to_int(typlen):
+ return int(typlen[1]) if typlen[1].isdigit() else \
+ typlen[1]
+
+ @staticmethod
+ def convert_typlen_to_int(typlen):
+ return int(typlen[0]) if typlen[0].isdigit() else \
+ typlen[0]
+
+ def extract_type_length_precision(self, column):
+ full_type = column['fulltype']
+ return full_type[self.type_start_position(column):
+ self.type_end_position(column)]
+
+ @staticmethod
+ def type_end_position(column):
+ return column['fulltype'].find(")")
+
+ @staticmethod
+ def type_start_position(column):
+ return column['fulltype'].find("(") + 1
+
+ def _format_proacl_from_db(self, proacl):
+ """
+ Returns privileges.
+ Args:
+ proacl: Privileges Dict
+ """
+ privileges = []
+ for row in proacl:
+ priv = parse_priv_from_db(row)
+ privileges.append(priv)
+
+ return {"relacl": privileges}
+
+ def _parse_variables_from_db(self, db_variables):
+ """
+ Function to format the output for variables.
+
+ Args:
+ db_variables: Variable object
+
+ Expected Object Format:
+ ['option1=value1', ..]
+ where:
+ user_name and database are optional
+ Returns:
+ Variable Object in below format:
+ {
+ 'variables': [
+ {'name': 'var_name', 'value': 'var_value',
+ 'user_name': 'user_name', 'database': 'database_name'},
+ ...]
+ }
+ where:
+ user_name and database are optional
+ """
+ variables_lst = []
+
+ if db_variables is not None:
+ for row in db_variables:
+ # The value may contain equals in string, split on
+ # first equals only
+ var_name, var_value = row.split("=", 1)
+
+ var_dict = {'option': var_name, 'value': var_value}
+
+ variables_lst.append(var_dict)
+
+ return {"ftoptions": variables_lst}
+
+ @check_precondition
+ def select_sql(self, gid, sid, did, scid, foid):
+ """
+ SELECT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+
+ Returns:
+ SELECT Script sql for the object
+ """
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ columns = []
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ else:
+ columns = '*'
+
+ sql = "SELECT {0}\n\tFROM {1};".format(
+ columns,
+ self.qtIdent(self.conn, data['basensp'], data['name'])
+ )
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def insert_sql(self, gid, sid, did, scid, foid):
+ """
+ INSERT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+
+ Returns:
+ INSERT Script sql for the object
+ """
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ columns = []
+ values = []
+
+ # Now we have all list of columns which we need
+ if 'columns' in data:
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+ values.append('?')
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ values = ", ".join(values)
+ sql = "INSERT INTO {0}(\n\t{1})\n\tVALUES ({2});".format(
+ self.qtIdent(self.conn, data['basensp'], data['name']),
+ columns, values
+ )
+ else:
+ sql = gettext('-- Please create column(s) first...')
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def update_sql(self, gid, sid, did, scid, foid):
+ """
+ UPDATE script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+
+ Returns:
+ UPDATE Script sql for the object
+ """
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ columns = []
+
+ # Now we have all list of columns which we need
+ if 'columns' in data:
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+
+ if len(columns) > 0:
+ if len(columns) == 1:
+ columns = columns[0]
+ columns += "=?"
+ else:
+ columns = "=?, ".join(columns)
+ columns += "=?"
+
+ sql = "UPDATE {0}\n\tSET {1}\n\tWHERE ;".format(
+ self.qtIdent(self.conn, data['basensp'], data['name']),
+ columns
+ )
+ else:
+ sql = gettext('-- Please create column(s) first...')
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def delete_sql(self, gid, sid, did, scid, foid, only_sql=False):
+ """
+ DELETE script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+ only_sql: Return only sql if True
+
+ Returns:
+ DELETE Script sql for the object
+ """
+ status, data = self._fetch_properties(gid, sid, did, scid, foid)
+ if not status:
+ return data
+ if not data:
+ return gone(self.not_found_error_msg())
+
+ sql = "DELETE FROM {0}\n\tWHERE ;".format(
+ self.qtIdent(self.conn, data['basensp'], data['name'])
+ )
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ return ajax_response(response=sql)
+
+ @staticmethod
+ def _check_const_for_obj_compare(data):
+ """
+ Check for constraint in fetched objects for compare.
+ :param data: Data.
+ """
+ if 'constraints' in data and data['constraints'] is not None \
+ and len(data['constraints']) > 0:
+ for item in data['constraints']:
+ if 'conoid' in item:
+ item.pop('conoid')
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the foreign tables for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODE_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(0, sid, did, scid,
+ row['oid'])
+ if status:
+ ForeignTableView._check_const_for_obj_compare(data)
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, foid=oid, is_schema_diff=True)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, foid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, foid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, foid=oid,
+ json_resp=False)
+ return sql
+
+ @staticmethod
+ def _modify_column_data(data, tmp_columns):
+ """
+ Modifies data for column.
+ :param data: Data for columns.
+ :param tmp_columns: tmp_columns list.
+ """
+ if 'added' in data['columns']:
+ for item in data['columns']['added']:
+ tmp_columns.append(item)
+ if 'changed' in data['columns']:
+ for item in data['columns']['changed']:
+ tmp_columns.append(item)
+ if 'deleted' in data['columns']:
+ for item in data['columns']['deleted']:
+ tmp_columns.remove(item)
+
+ @staticmethod
+ def _modify_constraints_data(data):
+ """
+ Modifies data for constraints.
+ :param data: Data for constraints.
+ :return: tmp_constraints list.
+ """
+ tmp_constraints = []
+ if 'added' in data['constraints']:
+ for item in data['constraints']['added']:
+ tmp_constraints.append(item)
+ if 'changed' in data['constraints']:
+ for item in data['constraints']['changed']:
+ tmp_constraints.append(item)
+
+ return tmp_constraints
+
+ @staticmethod
+ def _modify_options_data(data, tmp_ftoptions):
+ """
+ Modifies data for options.
+ :param data: Data for options.
+ :param tmp_ftoptions: tmp_ftoptions list.
+ """
+ if 'added' in data['ftoptions']:
+ for item in data['ftoptions']['added']:
+ tmp_ftoptions.append(item)
+ if 'changed' in data['ftoptions']:
+ for item in data['ftoptions']['changed']:
+ tmp_ftoptions.append(item)
+ if 'deleted' in data['ftoptions']:
+ for item in data['ftoptions']['deleted']:
+ tmp_ftoptions.remove(item)
+
+ def modify_data_for_schema_diff(self, data, old_data):
+ """
+ This function modifies the data for columns, constraints, options
+ etc...
+ :param data:
+ :return:
+ """
+ tmp_columns = []
+ if 'columns_for_schema_diff' in old_data:
+ tmp_columns = old_data['columns_for_schema_diff']
+
+ if 'columns' in data:
+ ForeignTableView._modify_column_data(data, tmp_columns)
+
+ data['columns'] = tmp_columns
+
+ if 'constraints' in data:
+ tmp_constraints = ForeignTableView._modify_constraints_data(data)
+ data['constraints'] = tmp_constraints
+
+ tmp_ftoptions = []
+ if 'ftoptions' in old_data:
+ tmp_ftoptions = old_data['ftoptions']
+ if 'ftoptions' in data:
+ ForeignTableView._modify_options_data(data, tmp_ftoptions)
+
+ data['ftoptions'] = tmp_ftoptions
+
+ @check_precondition
+ def enable_disable_triggers(self, gid, sid, did, scid, foid):
+ """
+ This function will enable/disable trigger(s) on the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ # Below will decide if it's simple drop or drop with cascade call
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ # Convert str 'true' to boolean type
+ is_enable_trigger = data['is_enable_trigger']
+
+ try:
+ if foid is not None:
+ status, data = self._fetch_properties(
+ gid, sid, did, scid, foid, inherits=True)
+ if not status:
+ return data
+ elif not data:
+ return gone(self.not_found_error_msg())
+
+ SQL = render_template(
+ "/".join([self.template_path, 'enable_disable_trigger.sql']),
+ data=data, is_enable_trigger=is_enable_trigger
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template(
+ "/".join([self.template_path, 'get_enabled_triggers.sql']),
+ tid=foid
+ )
+
+ status, trigger_res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Trigger(s) have been disabled")
+ if is_enable_trigger == 'D'
+ else gettext("Trigger(s) have been enabled"),
+ data={
+ 'id': foid,
+ 'scid': scid,
+ 'has_enable_triggers': trigger_res
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _get_resql_for_triggers(self, tid, schema,
+ table):
+ """
+ ########################################
+ # Reverse engineered sql for TRIGGERS
+ ########################################
+ """
+ sql = render_template("/".join([self.trigger_template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ trigger_sql = ''
+ for row in rset['rows']:
+ trigger_sql = trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=table, tid=tid,
+ trid=row['oid'], datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects,
+ template_path=None)
+ trigger_sql = "\n" + trigger_sql
+
+ trigger_sql = re.sub(self.pattern, self.double_newline,
+ trigger_sql)
+ return trigger_sql
+
+
+SchemaDiffRegistry(blueprint.node_type, ForeignTableView)
+ForeignTableView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/children/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/children/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc5915632436afd2bf9f7250b8b4bfa2b5ff314
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/children/__init__.py
@@ -0,0 +1,14 @@
+"""
+We will use the existing modules for creating children module under
+foreign tables.
+
+Do not remove these imports as they will be automatically imported by the view
+module as its children
+"""
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.triggers \
+ import blueprint as triggers_modules
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints import blueprint as constraints_modules
+from pgadmin.browser.server_groups.servers.databases.schemas.\
+ foreign_tables.foreign_table_columns import foreign_table_column_blueprint\
+ as foreign_tables_columns_modules
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6e2d278a78df87fc514f04744464974f53d8715
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/__init__.py
@@ -0,0 +1,97 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Column Node for foreign table """
+import pgadmin.browser.server_groups.servers.databases as database
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.columns \
+ import ColumnsView
+
+
+class ForeignTableColumnsModule(CollectionNodeModule):
+ """
+ class ColumnsModule(CollectionNodeModule)
+
+ A module class for Column node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Column and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'foreign_table_column'
+ _COLLECTION_LABEL = gettext("Columns")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the ColumnModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, foid, **kwargs):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(
+ sid, did, scid=scid, tid=foid,
+ base_template_path=ForeignTableColumnsView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(foid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return False
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+foreign_table_column_blueprint = ForeignTableColumnsModule(__name__)
+
+
+class ForeignTableColumnsView(ColumnsView):
+ node_type = foreign_table_column_blueprint.node_type
+ node_label = "Column"
+
+
+ForeignTableColumnsView.register_node_view(foreign_table_column_blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/coll-foreign_table_column.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/coll-foreign_table_column.svg
new file mode 100644
index 0000000000000000000000000000000000000000..7688f535569dcb8daab02d27edb759e3dc42dded
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/coll-foreign_table_column.svg
@@ -0,0 +1 @@
+coll-column
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/foreign_table_column.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/foreign_table_column.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5afb75a9962771bc0207b56440075a4f463de57f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/img/foreign_table_column.svg
@@ -0,0 +1 @@
+column
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/js/foreign_table_column.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/js/foreign_table_column.js
new file mode 100644
index 0000000000000000000000000000000000000000..783e8598e27946cb62c889ad7108aa814c8570b4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/foreign_table_columns/static/js/foreign_table_column.js
@@ -0,0 +1,70 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import { getNodeColumnSchema } from '../../../static/js/foreign_table.ui';
+
+define('pgadmin.node.foreign_table_column', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser
+) {
+
+ if (!pgBrowser.Nodes['coll-foreign_table_column']) {
+ pgBrowser.Nodes['coll-foreign_table_column'] =
+ pgBrowser.Collection.extend({
+ node: 'foreign_table_column',
+ label: gettext('Columns'),
+ type: 'coll-foreign_table_column',
+ columns: ['name', 'cltype', 'description']
+ });
+ }
+
+ if (!pgBrowser.Nodes['foreign_table_column']) {
+ pgBrowser.Nodes['foreign_table_column'] = pgBrowser.Node.extend({
+ // Foreign table is added in parent_type to support triggers on
+ // foreign table where we need column information.
+ parent_type: ['foreign_table'],
+ collection_type: ['coll-foreign_table'],
+ type: 'foreign_table_column',
+ label: gettext('Column'),
+ hasSQL: true,
+ sqlAlterHelp: 'sql-altertable.html',
+ sqlCreateHelp: 'sql-altertable.html',
+ dialogHelp: url_for('help.static', {'filename': 'column_dialog.html'}),
+ canDrop: true,
+ canDropCascade: false,
+ hasDepends: true,
+ hasStatistics: true,
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+ pgBrowser.add_menus([{
+ name: 'create_column_on_coll', node: 'coll-foreign_table_column', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_column_onTable', node: 'foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },
+ ]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['foreign_table_column'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/coll-foreign_table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/coll-foreign_table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..9222f44300b5ab1eec507fc808c081261a50d6bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/coll-foreign_table.svg
@@ -0,0 +1 @@
+coll-foreign_table
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/foreign_table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/foreign_table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..50349086e047090c15fbfcd56b31066577765c49
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/img/foreign_table.svg
@@ -0,0 +1 @@
+foreign_table
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.js
new file mode 100644
index 0000000000000000000000000000000000000000..1669d0ae3ce529f49fff9304245f0b536c43d513
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.js
@@ -0,0 +1,153 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import { getNodeListByName, getNodeAjaxOptions } from '../../../../../../../static/js/node_ajax';
+import { getNodeVariableSchema } from '../../../../../static/js/variable.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import ForeignTableSchema from './foreign_table.ui';
+import _ from 'lodash';
+import Notify from '../../../../../../../../static/js/helpers/Notifier';
+
+/* Create and Register Foreign Table Collection and Node. */
+define('pgadmin.node.foreign_table', ['pgadmin.tables.js/enable_disable_triggers',
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection','pgadmin.node.column',
+ 'pgadmin.node.constraints'
+], function(
+ tableFunctions, gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode,
+) {
+
+ if (!pgBrowser.Nodes['coll-foreign_table']) {
+ pgBrowser.Nodes['coll-foreign_table'] =
+ pgBrowser.Collection.extend({
+ node: 'foreign_table',
+ label: gettext('Foreign Tables'),
+ type: 'coll-foreign_table',
+ columns: ['name', 'owner', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['foreign_table']) {
+ pgBrowser.Nodes['foreign_table'] = schemaChild.SchemaChildNode.extend({
+ type: 'foreign_table',
+ sqlAlterHelp: 'sql-alterforeigntable.html',
+ sqlCreateHelp: 'sql-createforeigntable.html',
+ dialogHelp: url_for('help.static', {'filename': 'foreign_table_dialog.html'}),
+ label: gettext('Foreign Table'),
+ collection_type: 'coll-foreign_table',
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.md + 'px',
+ hasScriptTypes: ['create', 'select', 'insert', 'update', 'delete'],
+ parent_type: ['schema'],
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_foreign_table_on_coll', node: 'coll-foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Foreign Table...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_foreign_table', node: 'foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Foreign Table...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_foreign_table', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Foreign Table...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },{
+ // To enable/disable all triggers for the table
+ name: 'enable_all_triggers', node: 'foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'enable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Enable All'),
+ enable : 'canCreate_with_trigger_enable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ action: 'create'
+ },
+ },{
+ name: 'disable_all_triggers', node: 'foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'disable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Disable All'),
+ enable : 'canCreate_with_trigger_disable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ action: 'create'
+ }}
+ ]);
+ },
+ callbacks: {
+ /* Enable trigger(s) on table */
+ enable_triggers_on_table: function(args) {
+ tableFunctions.enableTriggers(
+ pgBrowser.tree,
+ Notify,
+ this.generate_url.bind(this),
+ args
+ );
+ },
+ /* Disable trigger(s) on table */
+ disable_triggers_on_table: function(args) {
+ tableFunctions.disableTriggers(
+ pgBrowser.tree,
+ Notify,
+ this.generate_url.bind(this),
+ args
+ );
+ },
+ },
+ // Check to whether table has disable trigger(s)
+ canCreate_with_trigger_enable: function(itemData) {
+ return itemData.tigger_count > 0 && (itemData.has_enable_triggers == 0 || itemData.has_enable_triggers < itemData.tigger_count);
+ },
+ // Check to whether table has enable trigger(s)
+ canCreate_with_trigger_disable: function(itemData) {
+ return itemData.tigger_count > 0 && itemData.has_enable_triggers > 0;
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new ForeignTableSchema(
+ (privileges)=>getNodePrivilegeRoleSchema('', treeNodeInfo, itemNodeData, privileges),
+ ()=>getNodeVariableSchema(this, treeNodeInfo, itemNodeData, false, false),
+ (params)=>{
+ return getNodeAjaxOptions('get_columns', pgBrowser.Nodes['foreign_table'], treeNodeInfo, itemNodeData, {urlParams: params, useCache:false});
+ },
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {cacheLevel: 'database'}),
+ foreignServers: ()=>getNodeAjaxOptions('get_foreign_servers', this, treeNodeInfo, itemNodeData, {cacheLevel: 'database'}, (res) => {
+ return _.reject(res, function(o) {
+ return o.label == '' || o.label == null;
+ });
+ }),
+ tables: ()=>getNodeAjaxOptions('get_tables', this, treeNodeInfo, itemNodeData, {cacheLevel: 'database'}),
+ nodeInfo: treeNodeInfo,
+ nodeData: itemNodeData,
+ pgBrowser: pgBrowser
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ basensp: treeNodeInfo.schema ? treeNodeInfo.schema.label : ''
+ }
+ );
+ },
+ });
+
+ }
+
+ return pgBrowser.Nodes['foreign_table'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..4bbb8f6672bb80c3149a7d39a0cdc0a2e7c65219
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/static/js/foreign_table.ui.js
@@ -0,0 +1,673 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import OptionsSchema from '../../../../../static/js/options.ui';
+import { isEmptyString } from 'sources/validators';
+import VariableSchema from 'top/browser/server_groups/servers/static/js/variable.ui';
+
+import _ from 'lodash';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import { getNodeAjaxOptions } from '../../../../../../../static/js/node_ajax';
+
+
+export default class ForeignTableSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, getVariableSchema, getColumns, fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ owner: undefined,
+ basensp: undefined,
+ is_sys_obj: undefined,
+ description: undefined,
+ ftsrvname: undefined,
+ strftoptions: undefined,
+ inherits: [],
+ columns: [],
+ ftoptions: [],
+ relacl: [],
+ seclabels: [],
+ ...initValues
+ });
+
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.getVariableSchema = getVariableSchema;
+ this.getColumns = getColumns;
+ this.inheritedTableList = [];
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ foreignServers: [],
+ tables: [],
+ nodeInfo: null,
+ ...fieldOptions,
+ };
+
+ this.columnsObj = getNodeColumnSchema(this.fieldOptions.nodeInfo, this.fieldOptions.nodeData, this.fieldOptions.pgBrowser);
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ canEditDeleteRowColumns(colstate) {
+ return isEmptyString(colstate.inheritedfrom);
+ }
+
+ inSchemaWithColumnCheck(state) {
+ if(this.nodeInfo && ('schema' in this.nodeInfo)) {
+ if(this.isNew(state)) {
+ return false;
+ }
+
+ // We will disable control if it's system columns
+ // inheritedfrom check is useful when we use this schema in table node
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)){
+ return true;
+ }
+
+ // ie: it's position is less than 1
+ return !(!_.isUndefined(state.attnum) && state.attnum > 0);
+ }
+ return false;
+ }
+
+ getTableOid(tabId) {
+ // Here we will fetch the table oid from table name
+ // iterate over list to find table oid
+ for(const t of this.inheritedTableList) {
+ if(t.value === tabId) {
+ return t.value;
+ }
+ }
+ }
+
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ noEmpty: true
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'owner', label: gettext('Owner'), cell: 'text',
+ type: 'select', controlProps: { allowClear: false },
+ options: obj.fieldOptions.role
+ },{
+ id: 'basensp', label: gettext('Schema'), cell: 'text',
+ type: 'select', mode:['create', 'edit'],
+ options: obj.fieldOptions.schema
+ },{
+ id: 'is_sys_obj', label: gettext('System foreign table?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline',
+ },{
+ id: 'ftsrvname', label: gettext('Foreign server'), cell: 'text',
+ type: 'select', group: gettext('Definition'),
+ options: obj.fieldOptions.foreignServers,
+ readonly: (state) => { return !obj.isNew(state); },
+ },{
+ id: 'inherits', label: gettext('Inherits'), group: gettext('Definition'),
+ type: 'select', min_version: 90500, controlProps: {multiple: true},
+ options: obj.fieldOptions.tables,
+ optionsLoaded: (res)=>obj.inheritedTableList=res,
+ deferredDepChange: (state, source, topState, actionObj)=>{
+ return new Promise((resolve)=>{
+ // current table list and previous table list
+ let newColInherits = state.inherits || [];
+ let oldColInherits = actionObj.oldState.inherits || [];
+
+ let tabName;
+ let tabColsResponse;
+
+ // Add columns logic
+ // If new table is added in list
+ if(newColInherits.length > 1 && newColInherits.length > oldColInherits.length) {
+ // Find newly added table from current list
+ tabName = _.difference(newColInherits, oldColInherits);
+ tabColsResponse = obj.getColumns({attrelid: this.getTableOid(tabName[0])});
+ } else if (newColInherits.length == 1) {
+ // First table added
+ tabColsResponse = obj.getColumns({attrelid: this.getTableOid(newColInherits[0])});
+ }
+
+ if(tabColsResponse) {
+ tabColsResponse.then((res)=>{
+ resolve((tmpstate)=>{
+ let finalCols = res.map((col)=>obj.columnsObj.getNewData(col));
+ finalCols = [...tmpstate.columns, ...finalCols];
+ return {
+ adding_inherit_cols: false,
+ columns: finalCols,
+ };
+ });
+ });
+ }
+
+ // Remove columns logic
+ let removeOid;
+ if(newColInherits.length > 0 && newColInherits.length < oldColInherits.length) {
+ // Find deleted table from previous list
+ tabName = _.difference(oldColInherits, newColInherits);
+ removeOid = this.getTableOid(tabName[0]);
+ } else if (oldColInherits.length === 1 && newColInherits.length < 1) {
+ // We got last table from list
+ tabName = oldColInherits[0];
+ removeOid = this.getTableOid(tabName);
+ }
+ if(removeOid) {
+ resolve((tmpstate)=>{
+ let finalCols = tmpstate.columns;
+ _.remove(tmpstate.columns, (col)=>col.inheritedid==removeOid);
+ return {
+ adding_inherit_cols: false,
+ columns: finalCols
+ };
+ });
+ }
+ });
+ },
+ },
+ {
+ id: 'columns', label: gettext('Columns'), cell: 'text',
+ type: 'collection', group: gettext('Columns'), mode: ['edit', 'create'],
+ schema: this.columnsObj,
+ canAdd: true, canDelete: true, canEdit: true, columns: ['name', 'cltype', 'attprecision', 'attlen', 'inheritedfrom'],
+ // For each row edit/delete button enable/disable
+ canEditRow: this.canEditDeleteRowColumns,
+ canDeleteRow: this.canEditDeleteRowColumns,
+ },
+ {
+ id: 'constraints', label: gettext('Constraints'), cell: 'text',
+ type: 'collection', group: gettext('Constraints'), mode: ['edit', 'create'],
+ schema: new CheckConstraintSchema(),
+ canAdd: true, canDelete: true, columns: ['conname','consrc', 'connoinherit', 'convalidated'],
+ canEdit: true,
+ canDeleteRow: function(state) {
+ return (state.conislocal || _.isUndefined(state.conislocal));
+ },
+ canEditRow: function(state) {
+ return obj.isNew(state);
+ }
+ },
+ {
+ id: 'strftoptions', label: gettext('Options'), cell: 'text',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },
+ {
+ id: 'ftoptions', label: gettext('Options'), type: 'collection',
+ schema: new OptionsSchema('option', 'value'),
+ group: gettext('Options'),
+ mode: ['edit', 'create'],
+ canAdd: true, canDelete: true, uniqueCol : ['option'],
+ },
+ {
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'], min_version: 90200,
+ },
+ {
+ id: 'relacl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['a','r','w','x']),
+ uniqueCol : ['grantee', 'grantor'],
+ editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ min_version: 90200
+ },
+ {
+ id: 'seclabels', label: gettext('Security labels'), type: 'collection',
+ schema: new SecLabelSchema(),
+ editable: false, group: gettext('Security'),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'],
+ min_version: 90100,
+ disabled: obj.inCatalog()
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+
+ if (isEmptyString(state.service)) {
+
+ /* code validation*/
+ if (isEmptyString(state.ftsrvname)) {
+ errmsg = gettext('Foreign server cannot be empty.');
+ setError('ftsrvname', errmsg);
+ return true;
+ } else {
+ setError('ftsrvname', null);
+ }
+
+ }
+ }
+}
+
+
+export function getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser) {
+ return new ColumnSchema(
+ {},
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ treeNodeInfo,
+ ()=>getNodeAjaxOptions('get_types', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'table',
+ }),
+ ()=>getNodeAjaxOptions('get_collations', pgBrowser.Nodes['collation'], treeNodeInfo, itemNodeData),
+ );
+}
+
+export class ColumnSchema extends BaseUISchema {
+ constructor(initValues, getPrivilegeRoleSchema, nodeInfo, datatypeOptions, collspcnameOptions) {
+ super({
+ name: undefined,
+ description: undefined,
+ atttypid: undefined,
+ cltype: undefined,
+ edit_types: undefined,
+ attlen: undefined,
+ attprecision: undefined,
+ defval: undefined,
+ attnotnull: false,
+ collspcname: undefined,
+ attstattarget:undefined,
+ attnum: undefined,
+ inheritedfrom: undefined,
+ inheritedid: undefined,
+ coloptions: [],
+ colconstype: 'n',
+ });
+
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.nodeInfo = nodeInfo;
+ this.cltypeOptions = datatypeOptions;
+ this.collspcnameOptions = collspcnameOptions;
+
+ this.datatypes = [];
+ }
+
+ get idAttribute() {
+ return 'attnum';
+ }
+
+ editable_check_for_column(state) {
+ return (_.isUndefined(state.inheritedid) || _.isNull(state.inheritedid) || _.isUndefined(state.inheritedfrom) || _.isNull(state.inheritedfrom));
+ }
+
+ // Check whether the column is a generated column
+ isTypeGenerated(state) {
+ let colconstype = state.colconstype;
+ return (!_.isUndefined(colconstype) && !_.isNull(colconstype) && colconstype == 'g');
+ }
+
+ attlenRange(state) {
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ if(o.length) return {min: o.min_val || 0, max: o.max_val};
+ }
+ }
+ return null;
+ }
+
+ attprecisionRange(state) {
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ if(o.precision) return {min: o.min_val || 0, max: o.max_val};
+ }
+ }
+ return null;
+ }
+
+ attCell(state) {
+ return { cell: this.attlenRange(state) ? 'int' : '' };
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', editable: obj.editable_check_for_column, noEmpty: true,
+ minWidth: 115,
+ disabled: (state)=>{
+ return state.is_inherited;
+ },
+ },
+ {
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ },
+ {
+ id: 'cltype',
+ label: gettext('Data type'),
+ minWidth: 150,
+ group: gettext('Definition'),
+ noEmpty: true,
+ editable: obj.editable_check_for_column,
+ disabled: (state)=>{
+ return state.is_inherited;
+ },
+ options: obj.cltypeOptions,
+ optionsLoaded: (options)=>{
+ obj.datatypes = options;
+ },
+ cell: (row)=>{
+ return {
+ cell: 'select',
+ options: this.cltypeOptions,
+ controlProps: {
+ allowClear: false,
+ filter: (options)=>{
+ let result = options;
+ let edit_types = row?.edit_types || [];
+ if(!obj.isNew(row) && !this.inErd) {
+ result = _.filter(options, (o)=>edit_types.indexOf(o.value) > -1);
+ }
+ return result;
+ },
+ }
+ };
+ },
+ type: (state)=>{
+ return {
+ type: 'select',
+ options: this.cltypeOptions,
+ controlProps: {
+ allowClear: false,
+ filter: (options)=>{
+ let result = options;
+ let edit_types = state?.edit_types || [];
+ if(!obj.isNew(state) && !this.inErd) {
+ result = _.filter(options, (o)=>edit_types.indexOf(o.value) > -1);
+ }
+ return result;
+ },
+ }
+ };
+ },
+ controlProps: {
+ allowClear: false,
+ }
+ },
+ {
+ id: 'inheritedfrom', label: gettext('Inherited from'), cell: 'label', type: 'text',
+ readonly: true, editable: false, mode: ['create','properties', 'edit'],
+ },
+ {
+ id: 'attnum', label: gettext('Position'), cell: 'text',
+ type: 'text', disabled: obj.inCatalog(), mode: ['properties'],
+ },
+ {
+ id: 'attlen',
+ label: gettext('Length'),
+ group: gettext('Definition'),
+ deps: ['cltype'],
+ type: 'int',
+ minWidth: 60,
+ cell: (state)=>{
+ return obj.attCell(state);
+ },
+ depChange: (state)=>{
+ let range = this.attlenRange(state);
+ if(range) {
+ return {
+ ...state, min_val_attlen: range.min, max_val_attlen: range.max,
+ };
+ } else {
+ return {
+ ...state, attlen: null,
+ };
+ }
+ },
+ disabled: function(state) {
+ return !obj.attlenRange(state);
+ },
+ editable: function(state) {
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)) {
+ return false;
+ }
+ return Boolean(obj.attlenRange(state));
+ },
+
+
+ },{
+ id: 'min_val_attlen', skipChange: true, visible: false, type: '',
+ },{
+ id: 'max_val_attlen', skipChange: true, visible: false, type: '',
+ },{
+ id: 'attprecision', label: gettext('Scale'), width: 60, disableResizing: true,
+ deps: ['cltype'], type: 'int', group: gettext('Definition'),
+ cell: (state)=>{
+ return obj.attCell(state);
+ },
+ depChange: (state)=>{
+ let range = this.attprecisionRange(state);
+ if(range) {
+ return {
+ ...state, min_val_attprecision: range.min, max_val_attprecision: range.max,
+ };
+ } else {
+ return {
+ ...state, attprecision: null,
+ };
+ }
+ },
+ disabled: function(state) {
+ return !this.attprecisionRange(state);
+ },
+ editable: function(state) {
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)) {
+ return false;
+ }
+ return Boolean(this.attprecisionRange(state));
+ },
+ },{
+ id: 'min_val_attprecision', skipChange: true, visible: false, type: '',
+ },{
+ id: 'max_val_attprecision', skipChange: true, visible: false, type: '',
+ },
+ {
+ id: 'attstattarget',
+ label: gettext('Statistics'),
+ cell: 'text',
+ type: 'text',
+ readonly: obj.inSchemaWithColumnCheck,
+ mode: ['properties', 'edit'],
+ group: gettext('Definition'),
+ },
+ {
+ id: 'attstorage', label: gettext('Storage'), group: gettext('Definition'),
+ type: 'select', mode: ['properties', 'edit'],
+ cell: 'select', readonly: obj.inSchemaWithColumnCheck,
+ controlProps: { placeholder: gettext('Select storage'),
+ allowClear: false,
+ },
+ options: [
+ {label: 'PLAIN', value: 'p'},
+ {label: 'MAIN', value: 'm'},
+ {label: 'EXTERNAL', value: 'e'},
+ {label: 'EXTENDED', value: 'x'},
+ ],
+ },
+ {
+ id: 'defval',
+ label: gettext('Default'),
+ cell: 'text',
+ type: 'text',
+ group: gettext('Constraints'),
+ editable: (state) => {
+ if(!(_.isUndefined(state.inheritedid)
+ || _.isNull(state.inheritedid)
+ || _.isUndefined(state.inheritedfrom)
+ || _.isNull(state.inheritedfrom))) { return false; }
+
+ return obj.nodeInfo.server.version >= 90300;
+ },
+ },
+ {
+ id: 'attnotnull',
+ label: gettext('Not NULL?'),
+ cell: 'switch',
+ type: 'switch',
+ minWidth: 80,
+ group: gettext('Constraints'),
+ editable: obj.editable_check_for_column,
+ },
+ {
+ id: 'colconstype',
+ label: gettext('Type'),
+ cell: 'text',
+ group: gettext('Constraints'),
+ type: (state)=>{
+ let options = [
+ { 'label': gettext('NONE'), 'value': 'n'},
+ ];
+ // You can't change the existing column to Generated column.
+ if (this.isNew(state)) {
+ options.push({
+ 'label': gettext('GENERATED'),
+ 'value': 'g',
+ });
+ } else {
+ options.push({
+ 'label': gettext('GENERATED'),
+ 'value': 'g',
+ 'disabled': true,
+ });
+ }
+ return {
+ type: 'toggle',
+ options: options,
+ };
+ },
+ disabled: function(state) {
+ return (!this.isNew(state) && state.colconstype == 'g');
+ },
+ min_version: 120000,
+ },
+ {
+ id: 'genexpr',
+ label: gettext('Expression'),
+ type: 'text',
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Constraints'),
+ min_version: 120000,
+ deps: ['colconstype'],
+ visible: this.isTypeGenerated,
+ readonly: function(state) {
+ return !this.isNew(state);
+ },
+ },
+ {
+ id: 'attoptions', label: gettext('Variables'), type: 'collection',
+ group: gettext('Variables'),
+ schema: new VariableSchema([
+ {label: 'n_distinct', value: 'n_distinct', vartype: 'string'},
+ {label: 'n_distinct_inherited', value: 'n_distinct_inherited', vartype: 'string'}
+ ], null, null, ['name', 'value']),
+ uniqueCol : ['name'], mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ },
+ {
+ id: 'collspcname', label: gettext('Collation'), cell: 'select',
+ type: 'select', group: gettext('Definition'),
+ deps: ['cltype'], options: obj.collspcnameOptions,
+ disabled: (state)=>{
+ if (!(_.isUndefined(obj.isNew)) && !obj.isNew(state)) { return false; }
+
+ return (_.isUndefined(state.inheritedid)
+ || _.isNull(state.inheritedid) ||
+ _.isUndefined(state.inheritedfrom) ||
+ _.isNull(state.inheritedfrom));
+ }
+ },
+ {
+ id: 'coloptions', label: gettext('Options'), type: 'collection',
+ group: gettext('Options'),
+ schema: new OptionsSchema('option', 'value'),
+ uniqueCol : ['option'], mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ }
+ ];
+ }
+}
+
+
+export class CheckConstraintSchema extends BaseUISchema {
+ constructor() {
+ super({
+ name: undefined,
+ oid: undefined,
+ description: undefined,
+ consrc: undefined,
+ connoinherit: undefined,
+ convalidated: true,
+ });
+
+ this.convalidated_default = true;
+
+ }
+
+ get idAttribute() {
+ return 'conoid';
+ }
+
+ isReadonly(state) {
+ return !this.isNew(state);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'conname', label: gettext('Name'), type:'text', cell:'text',
+ mode: ['properties', 'create', 'edit'],
+ editable: (state) => {
+ return _.isUndefined(obj.isNew) ? true : obj.isNew(state);
+ }, noEmpty: true, readonly: obj.isReadonly
+ },{
+ id: 'consrc', label: gettext('Check'), type: 'multiline', cell: 'text',
+ mode: ['properties', 'create', 'edit'],
+ editable: (state) => {
+ return _.isUndefined(obj.isNew) ? true : obj.isNew(state);
+ }, noEmpty: true, readonly: obj.isReadonly
+ },{
+ id: 'connoinherit', label: gettext('No inherit?'), type: 'switch', cell: 'switch',
+ mode: ['properties', 'create', 'edit'],
+ deps: [['is_partitioned']],
+ editable: (state) => {
+ return _.isUndefined(obj.isNew) ? true : obj.isNew(state);
+ }, readonly: obj.isReadonly
+ },{
+ id: 'convalidated', label: gettext('Validate?'), type: 'switch', cell: 'switch',
+ readonly: obj.isReadonly,
+ editable: (state) => {
+ if (_.isUndefined(obj.isNew)) { return true; }
+ if (!obj.isNew(state)) {
+ return !(state.convalidated && obj.convalidated_default);
+ }
+ return true;
+ },
+ mode: ['properties', 'create', 'edit'],
+ }];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cf55c6672d4f76e4c792a0cbbf952af0b485007a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/create.sql
@@ -0,0 +1,39 @@
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Add column ###}
+{% if data.name and data.cltype %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ADD COLUMN {{conn|qtIdent(data.name)}} {% if is_sql %}{{data.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.attlen, data.attprecision, data.hasSqrBracket) }}{% endif %}
+{### Add coloptions to column ###}
+{% if data.coloptions %}{% for o in data.coloptions %}{% if o.option is defined and o.value is defined %}{% if loop.first %}
+ OPTIONS ({% endif %}{% if not loop.first %}, {% endif %}{{o.option}} {{o.value|qtLiteral(conn)}}{% if loop.last %}){% endif %}{% endif %}{% endfor %}{% endif %}{% if data.collspcname %}
+ COLLATE {{data.collspcname}}{% endif %}{% if data.attnotnull %}
+ NOT NULL{% endif %}{% if data.defval is defined and data.defval is not none and data.defval != '' and data.colconstype != 'g' %}
+ DEFAULT {{data.defval}}{% endif %}{% if data.colconstype == 'g' and data.genexpr and data.genexpr != '' %}
+ GENERATED ALWAYS AS ({{data.genexpr}}) STORED{% endif %}{% endif %};
+{### Add comments ###}
+{% if data and data.description and data.description != None %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if data.attoptions %}
+
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, data.attoptions) }}
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget > -1 %}
+
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STATISTICS {{data.attstattarget}};
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != data.defaultstorage %}
+
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9c986ce01f803b9ecfc3a52facb7f10e2638de90
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/delete.sql
@@ -0,0 +1 @@
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}} DROP COLUMN IF EXISTS {{conn|qtIdent(data.name)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c0cd2fbf8349ebd6626d4f012a68648b1a914729
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_table_columns/sql/default/update.sql
@@ -0,0 +1,113 @@
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Rename column name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ RENAME {{conn|qtIdent(o_data.name)}} TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{### Add/Update column options ###}
+{% if 'coloptions' in data and data.coloptions != None and data.coloptions|length > 0 %}
+{% set coloptions = data.coloptions %}
+{% if data.name %}
+{% set colname = data.name %}
+{% else %}
+{% set colname = o_data.name %}
+{% endif %}
+{% if 'added' in coloptions and coloptions.added|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtIdent(colname)}} OPTIONS (ADD {% for opt in coloptions.added %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(opt.option) }} {{ opt.value|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{% if 'changed' in coloptions and coloptions.changed|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtIdent(colname)}} OPTIONS (SET {% for opt in coloptions.changed %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(opt.option) }} {{ opt.value|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{% if 'deleted' in coloptions and coloptions.deleted|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtIdent(colname)}} OPTIONS (DROP {% for opt in coloptions.deleted %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(opt.option) }}{% endfor %});
+{% endif %}
+{% endif %}
+{### Alter column type and collation ###}
+{% if (data.cltype and data.cltype != o_data.cltype) or (data.attlen is defined and data.attlen != o_data.attlen) or (data.attprecision is defined and data.attprecision != o_data.attprecision) or (data.collspcname and data.collspcname != o_data.collspcname) or data.col_type_conversion is defined %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %}
+-- WARNING:
+-- The SQL statement below would normally be used to alter the cltype for the {{o_data.name}} column, however,
+-- the current datatype cannot be cast to the target cltype so this conversion cannot be made automatically.
+{% endif %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %}ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %} ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} TYPE {{ GET_TYPE.UPDATE_TYPE_SQL(conn, data, o_data) }}{% if data.collspcname and data.collspcname != o_data.collspcname and data.cltype != '"char"' %}
+ COLLATE {{data.collspcname}}{% elif o_data.collspcname and data.cltype != '"char"' %} COLLATE {{o_data.collspcname}}{% endif %};
+
+{% endif %}
+{### Alter column default value ###}
+{% if is_view_only and data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER VIEW {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+{% elif data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% endif %}
+{### Drop column default value ###}
+{% if data.defval is defined and (data.defval == '' or data.defval is none) and data.defval != o_data.defval %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP DEFAULT;
+
+{% endif %}
+{### Alter column not null value ###}
+{% if 'attnotnull' in data and data.attnotnull != o_data.attnotnull %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attnotnull %}SET{% else %}DROP{% endif %} NOT NULL;
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget != o_data.attstattarget %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != o_data.attstorage %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{% if data.description is defined and data.description != None %}
+{% if data.name %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+{% else %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, o_data.name)}}
+{% endif %}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Update column variables ###}
+{% if 'attoptions' in data and data.attoptions != None and data.attoptions|length > 0 %}
+{% set variables = data.attoptions %}
+{% if 'deleted' in variables and variables.deleted|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', data.name, variables.deleted) }}
+{% else %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', o_data.name, variables.deleted) }}
+{% endif %}
+{% endif %}
+{% if 'added' in variables and variables.added|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.added) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.added) }}
+{% endif %}
+{% endif %}
+{% if 'changed' in variables and variables.changed|length > 0 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.changed) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.changed) }}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..24f290a201c5525a1c1b36d1c47d3a7e4f5f6e42
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_columns.sql
@@ -0,0 +1,52 @@
+WITH INH_TABLES AS
+ (SELECT
+ at.attname AS name, ph.inhparent AS inheritedid, ph.inhseqno,
+ pg_catalog.concat(nmsp_parent.nspname, '.',parent.relname ) AS inheritedfrom
+ FROM
+ pg_catalog.pg_attribute at
+ JOIN
+ pg_catalog.pg_inherits ph ON ph.inhparent = at.attrelid AND ph.inhrelid = {{foid}}::oid
+ JOIN
+ pg_catalog.pg_class parent ON ph.inhparent = parent.oid
+ JOIN
+ pg_catalog.pg_namespace nmsp_parent ON nmsp_parent.oid = parent.relnamespace
+ GROUP BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ ORDER BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ )
+SELECT INH.inheritedfrom, INH.inheritedid, att.attoptions, att.atttypid, attfdwoptions,
+ att.attname as name, att.attndims, att.atttypmod, pg_catalog.format_type(t.oid,NULL) AS cltype,
+ att.attnotnull, att.attstorage, att.attstattarget, att.attnum, pg_catalog.format_type(t.oid, att.atttypmod) AS fulltype,
+ t.typstorage AS defaultstorage,
+ CASE WHEN t.typelem > 0 THEN t.typelem ELSE t.oid END as elemoid,
+ (CASE WHEN (att.attidentity in ('a', 'd')) THEN 'i' WHEN (att.attgenerated in ('s')) THEN 'g' ELSE 'n' END) AS colconstype,
+ (CASE WHEN (att.attgenerated in ('s')) THEN pg_catalog.pg_get_expr(def.adbin, def.adrelid) END) AS genexpr,
+ (SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = t.typnamespace) as typnspname,
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN length(cn.nspname::text) > 0 AND length(cl.collname::text) > 0 THEN
+ pg_catalog.concat(cn.nspname, '."', cl.collname,'"')
+ ELSE '' END AS collname,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval,
+ (SELECT COUNT(1) from pg_catalog.pg_type t2 WHERE t2.typname=t.typname) > 1 AS isdup,
+ des.description
+FROM
+ pg_catalog.pg_attribute att
+LEFT JOIN
+ INH_TABLES as INH ON att.attname = INH.name
+JOIN
+ pg_catalog.pg_type t ON t.oid=atttypid
+JOIN
+ pg_catalog.pg_namespace nsp ON t.typnamespace=nsp.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+LEFT OUTER JOIN
+ pg_catalog.pg_type b ON t.typelem=b.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_collation cl ON att.attcollation=cl.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace cn ON cl.collnamespace=cn.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.classoid='pg_class'::regclass AND des.objsubid = att.attnum)
+WHERE
+ att.attrelid={{foid}}::oid
+ AND att.attnum>0
+ ORDER BY att.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9e7bae644e421fcb3ccb85f11ca6833e88cbfd61
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/12_plus/get_constraints.sql
@@ -0,0 +1,9 @@
+SELECT
+ oid as conoid, conname, contype,
+ pg_catalog.BTRIM(substring(pg_catalog.pg_get_constraintdef(oid, true) from '\(.+\)'), '()') as consrc,
+ connoinherit, convalidated, conislocal
+FROM
+ pg_catalog.pg_constraint
+WHERE
+ conrelid={{foid}}::oid
+ORDER by conname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..22afdb7957d7dfe8beb632f7a2e2b6a2ee13e145
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.relacl) AS d FROM pg_catalog.pg_class db
+ WHERE db.oid = {{foid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9d633526a79d5db1f13862caeb15e36c7457a428
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_foreign_table ft ON c.oid=ft.ftrelid
+WHERE
+ c.relnamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..be860007743ca3cbe269a3f2a938e0b92b925e57
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/create.sql
@@ -0,0 +1,111 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% if data %}
+CREATE FOREIGN TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.basensp, data.name) }}(
+{% if data.columns %}
+{% for c in data.columns %}
+{% if (not c.inheritedfrom or c.inheritedfrom =='' or c.inheritedfrom == None or c.inheritedfrom == 'None' ) %}
+{% if is_columns.append('1') %}{% endif %}
+ {{conn|qtIdent(c.name)}} {% if is_sql %}{{ c.fulltype }}{% else %}{{c.cltype }}{% if c.attlen %}({{c.attlen}}{% if c.attprecision %}, {{c.attprecision}}{% endif %}){% endif %}{% if c.isArrayType %}[]{% endif %}{% endif %}{% if c.coloptions %}
+{% for o in c.coloptions %}{% if o.option is defined and o.value is defined %}
+{% if loop.first %} OPTIONS ({% endif %}{% if not loop.first %}, {% endif %}{{o.option}} {{o.value|qtLiteral(conn)}}{% if loop.last %}){% endif %}{% endif %}
+{% endfor %}{% endif %}
+{% if c.attnotnull %} NOT NULL{% endif %}
+{% if c.defval is defined and c.defval is not none and c.defval != '' and c.colconstype != 'g' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'g' and c.genexpr and c.genexpr != '' %}
+ GENERATED ALWAYS AS {{c.genexpr}} STORED{% endif %}
+{% if c.collname %} COLLATE {{c.collname}}{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+)
+{% if data.inherits %}
+ INHERITS ({% for i in data.inherits %}{% if i %}{{i}}{% if not loop.last %}, {% endif %}{% endif %}{% endfor %})
+{% endif %}
+ SERVER {{ conn|qtIdent(data.ftsrvname) }}{% if data.ftoptions %}
+
+{% for o in data.ftoptions %}
+{% if o.option is defined and o.value is defined %}
+{% if loop.first %} OPTIONS ({% endif %}{% if not loop.first %}, {% endif %}{{o.option}} {{o.value|qtLiteral(conn)}}{% if loop.last %}){% endif %}{% endif %}
+{% endfor %}{% endif %};
+{% if data.owner %}
+
+ALTER FOREIGN TABLE {{ conn|qtIdent(data.basensp, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif -%}
+{% if data.constraints %}
+{% for c in data.constraints %}
+
+ALTER FOREIGN TABLE {{ conn|qtIdent(data.basensp, data.name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif %};
+{% endfor %}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FOREIGN TABLE {{ conn|qtIdent(data.basensp, data.name) }}
+ IS '{{ data.description }}';
+{% endif -%}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.basensp, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.basensp) }}
+{% endfor -%}
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FOREIGN TABLE', data.name, r.provider, r.label, data.basensp) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
+
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.basensp, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.basensp, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.basensp, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if c.attstorage is defined and c.attstorage != c.defaultstorage %}
+
+ALTER FOREIGN TABLE IF EXISTS {{conn|qtIdent(data.basensp, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STORAGE {%if c.attstorage == 'p' %}
+PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}
+EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..009ade25082a3d08cbfbb33415a8f8097d0c62b3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/delete.sql
@@ -0,0 +1,15 @@
+{% if scid and foid %}
+SELECT
+ c.relname AS name, nspname as basensp
+FROM
+ pg_catalog.pg_class c
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace nsp ON (nsp.oid=c.relnamespace)
+WHERE
+ c.relnamespace = {{scid}}::oid
+ AND c.oid = {{foid}}::oid;
+{% endif %}
+
+{% if name %}
+DROP FOREIGN TABLE IF EXISTS {{ conn|qtIdent(basensp, name) }}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/edit_mode_types_multi.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/edit_mode_types_multi.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9cbd793f0990884a3078f7be6ddd97a60eaca8e1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/edit_mode_types_multi.sql
@@ -0,0 +1,13 @@
+SELECT t.main_oid, pg_catalog.ARRAY_AGG(t.typname) as edit_types
+FROM
+(SELECT pc.castsource AS main_oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+ JOIN pg_catalog.pg_cast pc ON tt.oid=pc.casttarget
+ WHERE pc.castsource IN ({{type_ids}})
+ AND pc.castcontext IN ('i', 'a')
+UNION
+SELECT tt.typbasetype AS main_oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+WHERE tt.typbasetype IN ({{type_ids}})
+) t
+GROUP BY t.main_oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/enable_disable_trigger.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/enable_disable_trigger.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ad3dcafa5cddcef1b3ef542bd96c803c3a1ecaff
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/enable_disable_trigger.sql
@@ -0,0 +1,3 @@
+{% set enable_map = {'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER FOREIGN TABLE {{ conn|qtIdent(data.basensp, data.name) }}
+ {{ enable_map[is_enable_trigger] }} TRIGGER ALL;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/foreign_table_schema_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/foreign_table_schema_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..83acb8fb8f96d4edf9c7b9d735cb6e3d4b3f2239
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/foreign_table_schema_diff.sql
@@ -0,0 +1,76 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% set is_columns = [] %}
+{% if data.columns %}{% set columns = data.columns %}{% elif o_data.columns %}{% set columns = o_data.columns %}{% endif %}
+{% if data.inherits %}{% set inherits = data.inherits %}{% elif o_data.columns %}{% set inherits = o_data.inherits %}{% endif %}
+{% if data.ftoptions %}{% set ftoptions = data.ftoptions %}{% elif o_data.ftoptions %}{% set ftoptions = o_data.ftoptions %}{% endif %}
+{% if data.constraints %}{% set constraints = data.constraints %}{% elif o_data.constraints %}{% set constraints = o_data.constraints %}{% endif %}
+{% if data.acl %}{% set acl = data.acl %}{% elif o_data.acl %}{% set acl = o_data.acl %}{% endif %}
+-- WARNING:
+-- We have found the difference in foreign server
+-- so we need to drop the existing foreign table first and re-create it.
+DROP FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }};
+
+CREATE FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }}(
+{% if columns %}
+{% for c in columns %}
+{% if (not c.inheritedfrom or c.inheritedfrom =='' or c.inheritedfrom == None or c.inheritedfrom == 'None' ) %}
+{% if is_columns.append('1') %}{% endif %}
+ {{conn|qtIdent(c.name)}} {% if is_sql %}{{ c.fulltype }}{% else %}{{c.cltype }}{% if c.attlen %}({{c.attlen}}{% if c.attprecision %}, {{c.attprecision}}{% endif %}){% endif %}{% if c.isArrayType %}[]{% endif %}{% endif %}{% if c.coloptions %}
+{% for o in c.coloptions %}{% if o.option is defined and o.value is defined %}
+{% if loop.first %} OPTIONS ({% endif %}{% if not loop.first %}, {% endif %}{{o.option}} {{o.value|qtLiteral(conn)}}{% if loop.last %}){% endif %}{% endif %}
+{% endfor %}{% endif %}
+{% if c.attnotnull %} NOT NULL{% endif %}
+{% if c.typdefault is defined and c.typdefault is not none %} DEFAULT {{c.typdefault}}{% endif %}
+{% if c.collname %} COLLATE {{c.collname}}{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+)
+{% if inherits %}
+ INHERITS ({% for i in inherits %}{% if i %}{{i}}{% if not loop.last %}, {% endif %}{% endif %}{% endfor %})
+{% endif %}
+ SERVER {{ conn|qtIdent(data.ftsrvname) }}{% if ftoptions %}
+
+{% for o in ftoptions %}
+{% if o.option is defined and o.value is defined %}
+{% if loop.first %} OPTIONS ({% endif %}{% if not loop.first %}, {% endif %}{{o.option}} {{o.value|qtLiteral(conn)}}{% if loop.last %}){% endif %}{% endif %}
+{% endfor %}{% endif %};
+{% if data.owner or o_data.owner%}
+
+ALTER FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ OWNER TO {% if data.owner %}{{ conn|qtIdent(data.owner) }}{% else %}{{ conn|qtIdent(o_data.owner) }}{% endif %};
+{% endif -%}
+{% if constraints %}
+{% for c in constraints %}
+
+ALTER FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif %};
+{% endfor %}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ IS '{{ data.description }}';
+{ % elif o_data.description %}
+
+COMMENT ON FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ IS '{{ o_data.description }}';
+{% endif -%}
+{% if acl %}
+
+{% for priv in acl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.basensp) }}
+{% endfor -%}
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FOREIGN TABLE', o_data.name, r.provider, r.label, o_data.basensp) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec6f83b5ba1b996de6384d8fb17adc5e2960eee7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_collations.sql
@@ -0,0 +1,10 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(nspname, '."', collname,'"')
+ ELSE '' END AS copy_collation
+FROM
+ pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE
+ c.collnamespace=n.oid
+ORDER BY
+ nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d0b6c5fffb25fa94f94e5f8b9bfd2953beffcf4d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_columns.sql
@@ -0,0 +1,50 @@
+WITH INH_TABLES AS
+ (SELECT
+ at.attname AS name, ph.inhparent AS inheritedid, ph.inhseqno,
+ pg_catalog.concat(nmsp_parent.nspname, '.',parent.relname ) AS inheritedfrom
+ FROM
+ pg_catalog.pg_attribute at
+ JOIN
+ pg_catalog.pg_inherits ph ON ph.inhparent = at.attrelid AND ph.inhrelid = {{foid}}::oid
+ JOIN
+ pg_catalog.pg_class parent ON ph.inhparent = parent.oid
+ JOIN
+ pg_catalog.pg_namespace nmsp_parent ON nmsp_parent.oid = parent.relnamespace
+ GROUP BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ ORDER BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ )
+SELECT INH.inheritedfrom, INH.inheritedid, att.attoptions, att.atttypid, attfdwoptions,
+ att.attname as name, att.attndims, att.atttypmod, pg_catalog.format_type(t.oid,NULL) AS cltype,
+ att.attnotnull, att.attstorage, att.attstattarget, att.attnum, pg_catalog.format_type(t.oid, att.atttypmod) AS fulltype,
+ t.typstorage AS defaultstorage,
+ CASE WHEN t.typelem > 0 THEN t.typelem ELSE t.oid END as elemoid,
+ (SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = t.typnamespace) as typnspname,
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN length(cn.nspname::text) > 0 AND length(cl.collname::text) > 0 THEN
+ pg_catalog.concat(cn.nspname, '."', cl.collname,'"')
+ ELSE '' END AS collname,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval,
+ (SELECT COUNT(1) from pg_catalog.pg_type t2 WHERE t2.typname=t.typname) > 1 AS isdup,
+ des.description
+FROM
+ pg_catalog.pg_attribute att
+LEFT JOIN
+ INH_TABLES as INH ON att.attname = INH.name
+JOIN
+ pg_catalog.pg_type t ON t.oid=atttypid
+JOIN
+ pg_catalog.pg_namespace nsp ON t.typnamespace=nsp.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+LEFT OUTER JOIN
+ pg_catalog.pg_type b ON t.typelem=b.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_collation cl ON att.attcollation=cl.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace cn ON cl.collnamespace=cn.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.classoid='pg_class'::regclass AND des.objsubid = att.attnum)
+WHERE
+ att.attrelid={{foid}}::oid
+ AND att.attnum>0
+ ORDER BY att.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4a21fcfe39ed914e54ecf9954fd944a627d3372d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_constraints.sql
@@ -0,0 +1,7 @@
+SELECT
+ oid as conoid, conname, contype, consrc, connoinherit, convalidated, conislocal
+FROM
+ pg_catalog.pg_constraint
+WHERE
+ conrelid={{foid}}::oid
+ORDER by conname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_enabled_triggers.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_enabled_triggers.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c24eda653d744b7d5041743e31743579aa2c53eb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_enabled_triggers.sql
@@ -0,0 +1 @@
+SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid={{tid}} AND tgisinternal = FALSE AND tgenabled = 'O'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_foreign_servers.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_foreign_servers.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e56aa7a28c79416d95c6fc845f24651e6fae06a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_foreign_servers.sql
@@ -0,0 +1,6 @@
+SELECT
+ srvname
+FROM
+ pg_catalog.pg_foreign_server
+ORDER
+ BY srvname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1875379750b8ccb1ebc7908093c1f916580d6319
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_oid.sql
@@ -0,0 +1,19 @@
+{% if basensp %}
+SELECT
+ c.oid, bn.oid as scid
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_namespace bn ON bn.oid=c.relnamespace
+WHERE
+ bn.nspname = {{ basensp|qtLiteral(conn) }}
+ AND c.relname={{ name|qtLiteral(conn) }};
+
+{% elif foid %}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{foid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_table_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_table_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..80626220f1848322404f61e4af48c0ca52824778
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_table_columns.sql
@@ -0,0 +1,14 @@
+{% if attrelid %}
+SELECT
+ a.attname as name, pg_catalog.format_type(a.atttypid, NULL) AS cltype,
+ pg_catalog.quote_ident(n.nspname)||'.'||quote_ident(c.relname) as inheritedfrom,
+ c.oid as inheritedid
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_namespace n ON c.relnamespace=n.oid
+JOIN
+ pg_catalog.pg_attribute a ON a.attrelid = c.oid AND NOT a.attisdropped AND a.attnum>0
+WHERE
+ c.oid = {{attrelid}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_tables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_tables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..38b4c7d1ee22023810a44abcb4fd8433f7a47e5c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/get_tables.sql
@@ -0,0 +1,26 @@
+{% import 'foreign_tables/sql/macros/db_catalogs.macro' as CATALOG %}
+{% if attrelid %}
+SELECT
+ pg_catalog.array_agg(quote_ident(n.nspname) || '.' || pg_catalog.quote_ident(c.relname)) as inherits
+FROM
+ pg_catalog.pg_class c, pg_catalog.pg_namespace n
+WHERE
+ c.relnamespace=n.oid AND c.relkind IN ('r', 'f')
+ AND c.oid in {{attrelid}};
+
+{% else %}
+SELECT
+ c.oid AS value, pg_catalog.quote_ident(n.nspname) || '.' || pg_catalog.quote_ident(c.relname) as label
+FROM
+ pg_catalog.pg_class c, pg_catalog.pg_namespace n
+WHERE
+ c.relnamespace=n.oid AND c.relkind IN ('r', 'f')
+{% if not show_system_objects %}
+{{ CATALOG.VALID_CATALOGS(server_type) }}
+{% endif %}
+{% if foid %}
+ AND c.oid <> {{foid}}::oid
+{% endif %}
+ORDER BY
+ n.nspname, c.relname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d1095dfaf53de300d4ede00480e0694ac5e7f529
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/node.sql
@@ -0,0 +1,24 @@
+SELECT
+ c.oid, c.relname AS name, pg_catalog.pg_get_userbyid(relowner) AS owner,
+ ftoptions, nspname as basensp, description,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=c.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=c.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_foreign_table ft ON c.oid=ft.ftrelid
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace nsp ON (nsp.oid=c.relnamespace)
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_class'::regclass AND des.objsubid = 0)
+WHERE c.relkind = 'f'
+{% if scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% elif foid %}
+ AND c.oid = {{foid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY c.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1ae79122a3ac3116293b87b0387066deca84b2b8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/properties.sql
@@ -0,0 +1,33 @@
+SELECT
+ c.oid, c.relname AS name, pg_catalog.pg_get_userbyid(relowner) AS owner,
+ pg_catalog.array_to_string(c.relacl::text[], ', ') as acl,
+ ftoptions, srvname AS ftsrvname, description, nspname AS basensp,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=ftrelid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=c.oid) AS seclabels
+ {% if foid %},
+ (SELECT
+ pg_catalog.array_agg(i.inhparent) FROM pg_catalog.pg_inherits i
+ WHERE
+ i.inhrelid = {{foid}}::oid GROUP BY i.inhrelid) AS inherits
+ {% endif %}
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_foreign_table ft ON c.oid=ft.ftrelid
+LEFT OUTER JOIN
+ pg_catalog.pg_foreign_server fs ON ft.ftserver=fs.oid
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND des.classoid='pg_class'::regclass AND des.objsubid = 0)
+LEFT OUTER JOIN
+ pg_catalog.pg_namespace nsp ON (nsp.oid=c.relnamespace)
+WHERE
+ c.relnamespace = {{scid}}::oid
+ {% if foid %}
+ AND c.oid = {{foid}}::oid
+ {% endif %}
+ORDER BY c.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/types_condition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/types_condition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5dfa67320d561b26c5b0bd5a2fdaddf1d389a86a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/types_condition.sql
@@ -0,0 +1,14 @@
+{% import 'foreign_tables/sql/macros/db_catalogs.macro' as CATALOG %}
+typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r')
+AND NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_class
+ WHERE relnamespace=typnamespace
+ AND relname = typname AND relkind != 'c')
+ AND (typname NOT LIKE '_%' OR NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_class
+ WHERE relnamespace=typnamespace
+ AND relname = substring(typname FROM 2)::name
+ AND relkind != 'c'))
+{% if not show_system_objects %}
+ {{ CATALOG.VALID_TYPE_CATALOGS(server_type) }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e6f9d1ae02c2b368bed4cc8c6223f0b510101fe4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/default/update.sql
@@ -0,0 +1,143 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% set name = o_data.name %}
+{% if data.name %}{% if data.name != o_data.name %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% set name = data.name %}
+{% endif %}{% endif %}
+{% if data.owner %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{% if data.inherits and data.inherits|length > 0%}
+{% if o_data.inherits == None or o_data.inherits == 'None' %}
+{% set inherits = '' %}
+{% else %}
+{% set inherits = o_data.inherits %}
+{% endif %}
+{% for i in data.inherits %}
+{% if i not in inherits %}{% if i %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }} INHERIT {{i}};
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if o_data.inherits and 'inherits' in data %}
+{% if data.inherits == None or data.inherits == 'None' %}
+{% set inherits = '' %}
+{% else %}
+{% set inherits = data.inherits %}
+{% endif %}
+{% for i in o_data.inherits %}{% if i not in inherits %}{% if i %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }} NO INHERIT {{i}};{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if data.constraints %}
+{% for c in data.constraints.deleted %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP CONSTRAINT {{conn|qtIdent(c.conname)}};
+
+{% endfor -%}
+{% for c in data.constraints.added %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif %};
+
+{% endfor %}
+{% if data.is_schema_diff is defined and data.is_schema_diff %}
+{% for c in data.constraints.changed %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ DROP CONSTRAINT {{conn|qtIdent(c.conname)}};
+
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ ADD CONSTRAINT {{ conn|qtIdent(c.conname) }} CHECK ({{ c.consrc }}){% if not c.convalidated %} NOT VALID{% endif %}{% if c.connoinherit %} NO INHERIT{% endif %};
+
+{% endfor %}
+{% else %}
+{% for c in data.constraints.changed %}
+{% if c.convalidated %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(c.conname) }};
+
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if data.ftoptions %}
+{% for o in data.ftoptions.deleted %}
+{% if o.option is defined and o.value is defined %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ OPTIONS ( DROP {{o.option}});
+
+{% endif %}
+{% endfor %}
+{% for o in data.ftoptions.added %}
+{% if o.option is defined and o.value is defined %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ OPTIONS (ADD {{o.option}} {{o.value|qtLiteral(conn)}});
+
+{% endif %}
+{% endfor %}
+{% for o in data.ftoptions.changed %}
+{% if o.option is defined and o.value is defined %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ OPTIONS (SET {{o.option}} {{o.value|qtLiteral(conn)}});
+
+{% endif %}
+{% endfor %}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FOREIGN TABLE', name, r.provider, o_data.basensp) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FOREIGN TABLE', name, r.provider, r.label, o_data.basensp) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FOREIGN TABLE', name, r.provider, r.label, o_data.basensp) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+COMMENT ON FOREIGN TABLE {{ conn|qtIdent(o_data.basensp, name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif -%}
+{% if data.relacl %}
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, name, o_data.basensp) }}
+
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, name, o_data.basensp) }}
+
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.basensp) }}
+
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.basensp) }}
+
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.basensp %}
+ALTER FOREIGN TABLE IF EXISTS {{ conn|qtIdent(o_data.basensp, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.basensp) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/macros/db_catalogs.macro b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/macros/db_catalogs.macro
new file mode 100644
index 0000000000000000000000000000000000000000..48bc3403fa0e0f74e6f1a7fd366611ff7133a1d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/templates/foreign_tables/sql/macros/db_catalogs.macro
@@ -0,0 +1,11 @@
+{% macro VALID_CATALOGS(server_type) -%}
+ AND n.nspname NOT LIKE 'pg\_%' {% if server_type == 'ppas' %}
+AND n.nspname NOT IN ('information_schema', 'pgagent', 'sys') {% else %}
+AND n.nspname NOT IN ('information_schema') {% endif %}
+{%- endmacro %}
+{### Below macro is used in types fetching sql ###}
+{% macro VALID_TYPE_CATALOGS(server_type) -%}
+{% if server_type == 'ppas' %}
+ AND nsp.nspname NOT IN ('information_schema', 'pgagent', 'sys') {% else %}
+ AND nsp.nspname NOT IN ('information_schema') {% endif %}
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..83a6a4fee3fc9db555ac6fd86a5cac136f71706f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/__init__.py
@@ -0,0 +1,1078 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Defines views for management of Fts Configuration node"""
+
+from functools import wraps
+
+import json
+from flask import render_template, make_response, current_app, request, jsonify
+from flask_babel import gettext as _
+
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class FtsConfigurationModule(SchemaChildModule):
+ """
+ class FtsConfigurationModule(SchemaChildModule)
+
+ A module class for FTS Configuration node derived from
+ SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the FtsConfigurationModule and
+ it's base module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node
+
+ * script_load()
+ - Load the module script for FTS Configuration, when any of the schema
+ node is initialized.
+
+ """
+ _NODE_TYPE = 'fts_configuration'
+ _COLLECTION_LABEL = _('FTS Configurations')
+
+ def __init__(self, *args, **kwargs):
+ self.min_ver = None
+ self.max_ver = None
+ self.manager = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ if self.has_nodes(
+ sid, did, scid,
+ base_template_path=FtsConfigurationView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Override the property to make the node as leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for fts template, when any of the schema
+ node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+
+blueprint = FtsConfigurationModule(__name__)
+
+
+class FtsConfigurationView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ class FtsConfigurationView(PGChildNodeView)
+
+ A view class for FTS Configuration node derived from PGChildNodeView.
+ This class is responsible for all the stuff related to view like
+ create/update/delete FTS Configuration,
+ showing properties of node, showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the FtsConfigurationView and it's base
+ view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the nodes within that collection.
+
+ * nodes()
+ - This function will be used to create all the child node within
+ collection.
+ Here it will create all the FTS Configuration nodes.
+
+ * node()
+ - This function will be used to create a node given its oid
+ Here it will create the FTS Template node based on its oid
+
+ * properties(gid, sid, did, scid, cfgid)
+ - This function will show the properties of the selected
+ FTS Configuration node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new FTS Configuration object
+
+ * update(gid, sid, did, scid, cfgid)
+ - This function will update the data for the selected
+ FTS Configuration node
+
+ * delete(self, gid, sid, did, scid, cfgid):
+ - This function will drop the FTS Configuration object
+
+ * msql(gid, sid, did, scid, cfgid)
+ - This function is used to return modified SQL for the selected node
+
+ * get_sql(data, cfgid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid, cfgid):
+ - This function will generate sql to show in sql pane for node.
+
+ * parsers(gid, sid, did, scid):
+ - This function will fetch all ftp parsers from the same schema
+
+ * copyConfig():
+ - This function will fetch all existed fts configurations from same
+ schema
+
+ * tokens():
+ - This function will fetch all tokens from fts parser related to node
+
+ * dictionaries():
+ - This function will fetch all dictionaries related to node
+
+ * dependents(gid, sid, did, scid, cfgid):
+ - This function get the dependents and return ajax response for the node.
+
+ * dependencies(self, gid, sid, did, scid, cfgid):
+ - This function get the dependencies and return ajax response for node.
+
+ * compare(**kwargs):
+ - This function will compare the fts configuration nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ BASE_TEMPLATE_PATH = 'fts_configurations/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'cfgid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'parsers': [{'get': 'parsers'},
+ {'get': 'parsers'}],
+ 'copyConfig': [{'get': 'copyConfig'},
+ {'get': 'copyConfig'}],
+ 'tokens': [{'get': 'tokens'}, {'get': 'tokens'}],
+ 'dictionaries': [{}, {'get': 'dictionaries'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema']
+
+ def _init_(self, **kwargs):
+ self.conn = None
+ self.template_path = None
+ self.manager = None
+ super().__init__(**kwargs)
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ List all FTS Configuration nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ Return all FTS Configurations to generate nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-fts_configuration",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, cfgid):
+ """
+ Return FTS Configuration node to generate node
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ cfgid: fts Configuration id
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ cfgid=cfgid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(
+ _("""Could not find the FTS Configuration node.""")
+ )
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ did,
+ row['name'],
+ icon="icon-fts_configuration"
+ ),
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, cfgid):
+ """
+ Show properties of FTS Configuration node
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ cfgid: fts Configuration id
+ """
+ status, res = self._fetch_properties(scid, cfgid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, cfgid):
+ """
+ This function is used to fetch property of specified object.
+ :param scid:
+ :param cfgid:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ cfgid=cfgid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(
+ _(
+ "Could not find the FTS Configuration node in the "
+ "database node.")
+ )
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ # In edit mode fetch token/dictionary list also
+ sql = render_template(
+ "/".join([self.template_path, 'tokenDictList.sql']),
+ cfgid=cfgid
+ )
+
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=rset)
+
+ res['rows'][0]['tokens'] = rset['rows']
+
+ return True, res['rows'][0]
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the FTS Configuration object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+
+ # Mandatory fields to create a new FTS Configuration
+ required_args = [
+ 'schema',
+ 'name'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ # Either copy config or parser must be present in data
+ if 'copy_config' not in data and 'prsname' not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ "Provide at least copy config or parser."
+ )
+ )
+
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ # Replace schema oid with schema name before passing to create.sql
+ # To generate proper sql query
+ new_data = data.copy()
+ new_data['schema'] = schema
+
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn,
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need cfgid to add object in tree at browser,
+ # Below sql will give the same
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ name=data['name'],
+ scid=data['schema'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ res = res['rows'][0]
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['oid'],
+ data['schema'],
+ data['name'],
+ icon="icon-fts_configuration"
+ )
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, cfgid):
+ """
+ This function will update FTS Configuration node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: fts Configuration id
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ if cfgid == 0 or cfgid is None:
+ return gone(
+ _("Could not find the FTS Configuration node to update.")
+ )
+
+ # Fetch sql query to update fts Configuration
+ sql, name = self.get_sql(gid, sid, did, scid, data, cfgid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if cfgid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ cfgid=cfgid,
+ scid=data['schema'] if 'schema' in data else scid
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ _("Could not find the FTS Configuration node to update.")
+ )
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ cfgid,
+ data['schema'] if 'schema' in data else scid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, cfgid=None, only_sql=False):
+ """
+ This function will drop the FTS Configuration object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: FTS Configuration id
+ :param only_sql: Return only sql if True
+ """
+ if cfgid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [cfgid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ try:
+ for cfgid in data['ids']:
+ # Get name for FTS Configuration from cfgid
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']),
+ cfgid=cfgid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows'] or len(res['rows']) == 0:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ 'Error: Object not found.'
+ ),
+ info=_(
+ 'The specified FTS configuration '
+ 'could not be found.\n'
+ )
+ )
+
+ # Drop FTS Configuration
+ result = res['rows'][0]
+ sql = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ name=result['name'],
+ schema=result['schema'],
+ cascade=cascade
+ )
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=_("FTS Configuration dropped")
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, cfgid=None):
+ """
+ This function returns modified SQL
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: FTS Configuration id
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Fetch sql query for modified data
+ SQL, _ = self.get_sql(gid, sid, did, scid, data, cfgid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ if SQL == '':
+ SQL = "-- No change"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ def _get_sql_for_create(self, data, schema):
+ """
+ This function is used to get the create sql.
+ :param data:
+ :param schema:
+ :return:
+ """
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ new_data['schema'] = schema
+
+ if (
+ 'name' in new_data and
+ 'schema' in new_data
+ ):
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn
+ )
+ else:
+ sql = "-- definition incomplete"
+ return sql
+
+ @staticmethod
+ def _replace_schema_oid_with_schema_name(new_schema, new_data):
+ """
+ This function is used to replace schema oid with schema name.
+ :param new_schema:
+ :param new_data:
+ :return:
+ """
+ if 'schema' in new_data:
+ new_data['schema'] = new_schema
+
+ def get_sql(self, gid, sid, did, scid, data, cfgid=None):
+ """
+ This function will return SQL for model data
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: fts Configuration id
+ """
+ # Fetch sql for update
+ if cfgid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ cfgid=cfgid,
+ scid=scid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res), ''
+ elif len(res['rows']) == 0:
+ return \
+ gone(_("Could not find the FTS Configuration node.")), ''
+
+ old_data = res['rows'][0]
+ if 'schema' not in data:
+ data['schema'] = old_data['schema']
+
+ # If user has changed the schema then fetch new schema directly
+ # using its oid otherwise fetch old schema name using its oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data)
+
+ status, new_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=new_schema), ''
+
+ new_data = data.copy()
+ # Replace schema oid with schema name
+ self._replace_schema_oid_with_schema_name(new_schema, new_data)
+
+ # Fetch old schema name using old schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=old_data
+ )
+
+ status, old_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=old_schema), ''
+
+ # Replace old schema oid with old schema name
+ old_data['schema'] = old_schema
+
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=new_data, o_data=old_data, conn=self.conn
+ )
+ # Fetch sql query for modified data
+ if 'name' in data:
+ return sql.strip('\n'), data['name']
+
+ return sql.strip('\n'), old_data['name']
+ else:
+ # Fetch schema name from schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema), ''
+
+ sql = self._get_sql_for_create(data, schema)
+ return sql.strip('\n'), data['name']
+
+ @check_precondition
+ def parsers(self, gid, sid, did, scid):
+ """
+ This function will return fts parsers list for FTS Configuration
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ # Fetch last system oid
+
+ sql = render_template(
+ "/".join([self.template_path, 'parser.sql']),
+ parser=True
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ datlastsysoid = self._DATABASE_LAST_SYSTEM_OID
+
+ # Empty set is added before actual list as initially it will be visible
+ # at parser control while creating a new FTS Configuration
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ if row['schemaoid'] > datlastsysoid:
+ row['prsname'] = row['nspname'] + '.' + row['prsname']
+
+ res.append({'label': row['prsname'],
+ 'value': row['prsname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def copyConfig(self, gid, sid, did, scid):
+ """
+ This function will return copy config list for FTS Configuration
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ # Fetch last system oid
+ sql = render_template(
+ "/".join([self.template_path, 'copy_config.sql']),
+ copy_config=True
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ datlastsysoid = self._DATABASE_LAST_SYSTEM_OID
+
+ # Empty set is added before actual list as initially it will be visible
+ # at copy_config control while creating a new FTS Configuration
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ if row['oid'] > datlastsysoid:
+ row['cfgname'] = row['nspname'] + '.' + row['cfgname']
+
+ res.append({'label': row['cfgname'],
+ 'value': row['cfgname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def tokens(self, gid, sid, did, scid, cfgid=None):
+ """
+ This function will return token list of fts parser node related to
+ current FTS Configuration node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: fts configuration id
+ """
+ try:
+ res = []
+ if cfgid is not None:
+ sql = render_template(
+ "/".join([self.template_path, 'parser.sql']),
+ cfgid=cfgid
+ )
+ status, parseroid = self.conn.execute_scalar(sql)
+
+ if not status:
+ return internal_server_error(errormsg=parseroid)
+
+ sql = render_template(
+ "/".join([self.template_path, 'tokens.sql']),
+ parseroid=parseroid
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ for row in rset['rows']:
+ res.append({'label': row['alias'],
+ 'value': row['alias']})
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dictionaries(self, gid, sid, did, scid, cfgid=None):
+ """
+ This function will return dictionary list for FTS Configuration
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template(
+ "/".join([self.template_path, 'dictionaries.sql'])
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ res = []
+ for row in rset['rows']:
+ res.append({'label': row['dictname'],
+ 'value': row['dictname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, cfgid, **kwargs):
+ """
+ This function will reverse generate sql for sql panel
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param cfgid: FTS Configuration id
+ :param json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ try:
+ sql = render_template(
+ "/".join([self.template_path, 'sql.sql']),
+ cfgid=cfgid,
+ scid=scid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(
+ _(
+ "Could not generate reversed engineered query for the "
+ "FTS Configuration.\n{0}"
+ ).format(res)
+ )
+
+ if res is None:
+ return gone(
+ _(
+ "Could not generate reversed engineered query for "
+ "FTS Configuration node.")
+ )
+
+ # Used for schema diff tool
+ if target_schema:
+ data = {'schema': scid}
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ res = res.replace(schema, target_schema)
+
+ if not json_resp:
+ return res
+
+ return ajax_response(response=res)
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, cfgid):
+ """
+ This function get the dependents and return ajax response
+ for the FTS Configuration node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ cfgid: FTS Configuration ID
+ """
+ dependents_result = self.get_dependents(self.conn, cfgid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, cfgid):
+ """
+ This function get the dependencies and return ajax response
+ for the FTS Configuration node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ cfgid: FTS Configuration ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, cfgid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the fts configurations for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, fts_cfg = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in fts_cfg['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, cfgid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, cfgid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, cfgid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, cfgid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, FtsConfigurationView)
+FtsConfigurationView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/coll-fts_configuration.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/coll-fts_configuration.svg
new file mode 100644
index 0000000000000000000000000000000000000000..dfb579ae0b0749ff4a310992fe27a6535b6a6567
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/coll-fts_configuration.svg
@@ -0,0 +1 @@
+coll-fts_configuration
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/fts_configuration.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/fts_configuration.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5cecb9ae70337113c881563210c47dbf020ea195
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/img/fts_configuration.svg
@@ -0,0 +1 @@
+fts_configuration
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js
new file mode 100644
index 0000000000000000000000000000000000000000..eebae1b646c1c642ec4963a0b476a8227cee235b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.js
@@ -0,0 +1,97 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName, getNodeListById} from '../../../../../../../static/js/node_ajax';
+import FTSConfigurationSchema from './fts_configuration.ui';
+
+define('pgadmin.node.fts_configuration', [
+ 'sources/gettext', 'sources/url_for', 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ // Extend the collection class for FTS Configuration
+ if (!pgBrowser.Nodes['coll-fts_configuration']) {
+ pgAdmin.Browser.Nodes['coll-fts_configuration'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'fts_configuration',
+ label: gettext('FTS Configurations'),
+ type: 'coll-fts_configuration',
+ columns: ['name', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the node class for FTS Configuration
+ if (!pgBrowser.Nodes['fts_configuration']) {
+ pgAdmin.Browser.Nodes['fts_configuration'] = schemaChild.SchemaChildNode.extend({
+ type: 'fts_configuration',
+ sqlAlterHelp: 'sql-altertsconfig.html',
+ sqlCreateHelp: 'sql-createtsconfig.html',
+ dialogHelp: url_for('help.static', {'filename': 'fts_configuration_dialog.html'}),
+ label: gettext('FTS Configuration'),
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+
+ // Avoid multiple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ // Add context menus for FTS Configuration
+ pgBrowser.add_menus([{
+ name: 'create_fts_configuration_on_schema', node: 'schema',
+ module: this, category: 'create', priority: 4,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ label: gettext('FTS Configuration...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_fts_configuration_on_coll', module: this, priority: 4,
+ node: 'coll-fts_configuration', applies: ['object', 'context'],
+ callback: 'show_obj_properties', category: 'create',
+ label: gettext('FTS Configuration...'), data: {action: 'create'},
+ enable: 'canCreate',
+ },{
+ name: 'create_fts_configuration', node: 'fts_configuration',
+ module: this, applies: ['object', 'context'],
+ callback: 'show_obj_properties', category: 'create', priority: 4,
+ label: gettext('FTS Configuration...'), data: {action: 'create'},
+ enable: 'canCreate',
+ }]);
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new FTSConfigurationSchema(
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData),
+ parsers: ()=>getNodeAjaxOptions('parsers', this, treeNodeInfo, itemNodeData),
+ copyConfig: ()=>getNodeAjaxOptions('copyConfig', this, treeNodeInfo, itemNodeData),
+ tokens: ()=>getNodeAjaxOptions('tokens', this, treeNodeInfo, itemNodeData, {urlWithId: true}),
+ dictionaries: ()=>getNodeAjaxOptions('dictionaries', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'fts_configuration',
+ cacheNode: 'fts_configuration'
+ }),
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: itemNodeData._id,
+ }
+ );
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['coll-fts_configuration'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..14fc2ec096b20f290cb31c1219c10b46a24773a1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/static/js/fts_configuration.ui.js
@@ -0,0 +1,182 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import DataGridViewWithHeaderForm from 'sources/helpers/DataGridViewWithHeaderForm';
+import { isEmptyString } from '../../../../../../../../static/js/validators';
+
+class TokenHeaderSchema extends BaseUISchema {
+ constructor(tokenOptions) {
+ super({
+ token: undefined,
+ });
+
+ this.tokenOptions = tokenOptions;
+ this.isNewFTSConf = true;
+ }
+
+ addDisabled() {
+ return this.isNewFTSConf;
+ }
+
+ getNewData(data) {
+ return {
+ token: data.token,
+ dictname: [],
+ };
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'token', label: gettext('Tokens'), type:'select', editable: false,
+ options: this.tokenOptions, disabled: function() { return obj.isNewFTSConf; }
+ }];
+ }
+}
+
+class TokenSchema extends BaseUISchema {
+ constructor(dictOptions) {
+ super({
+ token: undefined,
+ dictname: undefined,
+ });
+
+ this.dictOptions = dictOptions;
+ }
+
+ get baseFields() {
+ return [
+ {
+ id: 'token', label: gettext('Token'), type:'text',
+ editable: false, cell: '', minWidth: 150, noEmpty: true,
+ }, {
+ id: 'dictname', label: gettext('Dictionaries'),
+ editable: true, controlProps: {multiple: true}, cell:'select',
+ options: this.dictOptions, minWidth: 260, noEmpty: true,
+ }
+ ];
+ }
+}
+
+export default class FTSConfigurationSchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ name: undefined, // FTS Configuration name
+ owner: undefined, // FTS Configuration owner
+ is_sys_obj: undefined, // Is system object
+ description: undefined, // Comment on FTS Configuration
+ schema: undefined, // Schema name FTS Configuration belongs to
+ prsname: undefined, // FTS parser list for FTS Configuration node
+ copy_config: undefined, // FTS configuration list to copy from
+ tokens: undefined, // token/dictionary pair list for node
+ ...initValues
+ });
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ parsers: [],
+ copyConfig: [],
+ tokens: [],
+ dictionaries: [],
+ ...fieldOptions,
+ };
+
+ this.tokHeaderSchema = new TokenHeaderSchema(this.fieldOptions.tokens);
+ this.tokColumnSchema = new TokenSchema(this.fieldOptions.dictionaries);
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ initialise(data) {
+ this.tokHeaderSchema.isNewFTSConf = this.isNew(data);
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text', type: 'text',
+ noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ editable: false, type: 'text', mode:['properties'],
+ }, {
+ id: 'owner', label: gettext('Owner'), cell: 'text',
+ editable: false, type: 'select', options: this.fieldOptions.role,
+ mode: ['properties', 'edit','create'], noEmpty: true,
+ }, {
+ id: 'schema', label: gettext('Schema'),
+ editable: false, type: 'select', options: this.fieldOptions.schema,
+ mode: ['create', 'edit'], noEmpty: true,
+ }, {
+ id: 'is_sys_obj', label: gettext('System FTS configuration?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ }, {
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline',
+ }, {
+ id: 'prsname', label: gettext('Parser'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ deps: ['copy_config'],
+ options: this.fieldOptions.parsers,
+ //disable parser when user select copy_config manually and vica-versa
+ disabled: function(state) {
+ let copy_config = state.copy_config;
+ return !(_.isNull(copy_config) ||
+ _.isUndefined(copy_config) ||
+ copy_config === '');
+ },
+ readonly: function(state) { return !obj.isNew(state); },
+ }, {
+ id: 'copy_config', label: gettext('Copy config'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ mode: ['create'], deps: ['prsname'],
+ options: this.fieldOptions.copyConfig,
+ //disable copy_config when user select parser manually and vica-versa
+ disabled: function(state) {
+ let parser = state.prsname;
+ return !(_.isNull(parser) ||
+ _.isUndefined(parser) ||
+ parser === '');
+ },
+ readonly: function(state) { return !obj.isNew(state); },
+ }, {
+ id: 'tokens', label: '', type: 'collection',
+ group: gettext('Tokens'), mode: ['create','edit'],
+ editable: false, schema: this.tokColumnSchema,
+ headerSchema: this.tokHeaderSchema,
+ headerVisible: function() { return true;},
+ CustomControl: DataGridViewWithHeaderForm,
+ uniqueCol : ['token'],
+ canAdd: true, canEdit: false, canDelete: true,
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null,
+ parser = state.prsname,
+ config = state.copy_config;
+
+ let copy_config_or_parser = !(parser === '' || _.isUndefined(parser)
+ || _.isNull(parser)) ? parser : config;
+
+ if(isEmptyString(copy_config_or_parser)) {
+ errmsg = gettext('Select parser or configuration to copy.');
+ setError('prsname', errmsg);
+ return true;
+ } else {
+ setError('prsname', null);
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/copy_config.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/copy_config.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3ac7f0cf5b18c5806643f6c2dae24a492a34b638
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/copy_config.sql
@@ -0,0 +1,15 @@
+{# FETCH copy config for FTS CONFIGURATION #}
+{% if copy_config %}
+SELECT
+ cfg.oid,
+ cfgname,
+ nspname,
+ n.oid as schemaoid
+FROM
+ pg_catalog.pg_ts_config cfg
+ JOIN pg_catalog.pg_namespace n
+ ON n.oid=cfgnamespace
+ORDER BY
+ nspname,
+ cfgname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ae467001e4afaf1a0ffcdb44629cc2a3d8bd1cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_ts_config cfg
+WHERE
+{% if scid %}
+ cfg.cfgnamespace = {{scid}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..547b8fda18d2680dced704c9deaa85cb8631f2b2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/create.sql
@@ -0,0 +1,19 @@
+{# CREATE FTS CONFIGURATION Statement #}
+{% if data and data.schema and data.name %}
+CREATE TEXT SEARCH CONFIGURATION {{ conn|qtIdent(data.schema, data.name) }} (
+{% if 'copy_config' in data and data.copy_config != '' %}
+ COPY={{ data.copy_config }}
+{% elif 'prsname' in data and data.prsname != '' %}
+ PARSER = {{ data.prsname }}
+{% endif %}
+);
+
+{% if 'owner' in data and data.owner != '' %}
+ALTER TEXT SEARCH CONFIGURATION {{ conn|qtIdent(data.schema, data.name) }} OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+
+{# Description for FTS_CONFIGURATION #}
+{% if data.description %}
+COMMENT ON TEXT SEARCH CONFIGURATION {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2108ce9c5aec8370e54a50f169162ef770de85bf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/delete.sql
@@ -0,0 +1,4 @@
+{# DROP FTS CONFIGURATION Statement #}
+{% if schema and name %}
+DROP TEXT SEARCH CONFIGURATION IF EXISTS {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}} {% if cascade %}CASCADE{%endif%};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/dictionaries.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/dictionaries.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3d1f93bd61b9d13a34872df0eff0524db7212e92
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/dictionaries.sql
@@ -0,0 +1,8 @@
+{# FETCH DICTIONARIES statement #}
+SELECT
+ CASE WHEN (pg_ns.nspname != 'pg_catalog') THEN
+ pg_catalog.CONCAT(pg_ns.nspname, '.', pg_td.dictname)
+ ELSE pg_td.dictname END AS dictname
+FROM pg_catalog.pg_ts_dict pg_td
+LEFT OUTER JOIN pg_catalog.pg_namespace pg_ns
+ON pg_td.dictnamespace = pg_ns.oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2298f7793d19aed585ef98b1958e57c85a9f3137
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/get_name.sql
@@ -0,0 +1,17 @@
+{# GET FTS CONFIGURATION name #}
+{% if cfgid %}
+SELECT
+ cfg.cfgname as name,
+ (
+ SELECT
+ nspname
+ FROM
+ pg_catalog.pg_namespace
+ WHERE
+ oid = cfg.cfgnamespace
+ ) as schema
+FROM
+ pg_catalog.pg_ts_config cfg
+WHERE
+ cfg.oid = {{cfgid}}::OID;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..739c56d1365094cd93e9949eee3c90f79bc740c4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/nodes.sql
@@ -0,0 +1,19 @@
+{# FETCH FTS CONFIGURATION NAME statement #}
+SELECT
+ cfg.oid, cfgname as name, des.description
+FROM
+ pg_catalog.pg_ts_config cfg
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ ON (des.objoid=cfg.oid AND des.classoid='pg_ts_config'::regclass)
+WHERE
+{% if scid %}
+ cfg.cfgnamespace = {{scid}}::OID
+{% elif cfgid %}
+ cfg.oid = {{cfgid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = cfg.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+
+ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/parser.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/parser.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b9cb1c1f9d03f88e28111403b7016c8a75180f73
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/parser.sql
@@ -0,0 +1,24 @@
+{# PARSER name from FTS CONFIGURATION OID #}
+{% if cfgid %}
+SELECT
+ cfgparser
+FROM
+ pg_catalog.pg_ts_config
+where
+ oid = {{cfgid}}::OID
+{% endif %}
+
+
+{# PARSER list #}
+{% if parser %}
+SELECT
+ prsname,
+ nspname,
+ n.oid as schemaoid
+FROM
+ pg_catalog.pg_ts_parser
+ JOIN pg_catalog.pg_namespace n
+ ON n.oid=prsnamespace
+ORDER BY
+ prsname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a7a55846f3d4292526cf4966e5239ff1ec6385e3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/properties.sql
@@ -0,0 +1,30 @@
+{# FETCH properties for FTS CONFIGURATION #}
+SELECT
+ cfg.oid,
+ cfg.cfgname as name,
+ pg_catalog.pg_get_userbyid(cfg.cfgowner) as owner,
+ cfg.cfgparser as parser,
+ cfg.cfgnamespace as schema,
+ CASE WHEN (np.nspname not in ('public', 'pg_catalog') AND length(parser.prsname::text) > 0
+ AND parser.prsname != 'default') THEN
+ pg_catalog.concat(pg_catalog.quote_ident(np.nspname), '.', pg_catalog.quote_ident(parser.prsname))
+ ELSE parser.prsname END AS prsname,
+ description
+FROM
+ pg_catalog.pg_ts_config cfg
+ LEFT OUTER JOIN pg_catalog.pg_ts_parser parser
+ ON parser.oid=cfg.cfgparser
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ ON (des.objoid=cfg.oid AND des.classoid='pg_ts_config'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_namespace np ON np.oid=parser.prsnamespace
+WHERE
+{% if scid %}
+ cfg.cfgnamespace = {{scid}}::OID
+{% endif %}
+{% if name %}
+ {% if scid %}AND {% endif %}cfg.cfgname = {{name|qtLiteral(conn)}}
+{% endif %}
+{% if cfgid %}
+ {% if scid %}AND {% else %}{% if name %}AND {% endif %}{% endif %}cfg.oid = {{cfgid}}::OID
+{% endif %}
+ORDER BY cfg.cfgname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fbbc98630570317bf464090c8aa352015eb93a9f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/schema.sql
@@ -0,0 +1,19 @@
+{# FETCH statement for SCHEMA name #}
+{% if data.schema %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{data.schema}}::OID
+
+{% elif data.id %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT JOIN pg_catalog.pg_ts_config cfg
+ ON cfg.cfgnamespace = nsp.oid
+WHERE
+ cfg.oid = {{data.id}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/sql.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/sql.sql
new file mode 100644
index 0000000000000000000000000000000000000000..929e9e3feb3c9054bd0611ef9822ce8dde3626e7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/sql.sql
@@ -0,0 +1,81 @@
+{# REVERSED ENGINEERED SQL FOR FTS CONFIGURATION #}
+{% if cfgid and scid %}
+SELECT
+ pg_catalog.array_to_string(array_agg(sql), E'\n\n') as sql
+FROM
+ (
+ SELECT
+ E'-- Text Search CONFIGURATION: ' || pg_catalog.quote_ident(nspname) || E'.'
+ || (cfg.cfgname) ||
+ E'\n\n-- DROP TEXT SEARCH CONFIGURATION ' || pg_catalog.quote_ident(nspname) ||
+ E'.' || pg_catalog.quote_ident(cfg.cfgname) ||
+ E'\n\nCREATE TEXT SEARCH CONFIGURATION ' || pg_catalog.quote_ident(nspname) ||
+ E'.' || pg_catalog.quote_ident(cfg.cfgname) || E' (\n' ||
+ E'\tPARSER = ' || parsername ||
+ E'\n);' ||
+ CASE
+ WHEN description IS NOT NULL THEN
+ E'\n\nCOMMENT ON TEXT SEARCH CONFIGURATION ' ||
+ pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(cfg.cfgname) ||
+ E' IS ' || pg_catalog.quote_literal(description) || E';'
+ ELSE ''
+ END || E'\n' ||
+
+ pg_catalog.array_to_string(
+ array(
+ SELECT
+ 'ALTER TEXT SEARCH CONFIGURATION ' || pg_catalog.quote_ident(b.nspname) ||
+ E'.' || pg_catalog.quote_ident(cfg.cfgname) || ' ADD MAPPING FOR ' ||
+ t.alias || ' WITH ' ||
+ pg_catalog.array_to_string(array_agg(
+ CASE WHEN (pg_ns.nspname != 'pg_catalog') THEN
+ pg_catalog.CONCAT(pg_ns.nspname, '.', dict.dictname)
+ ELSE
+ dict.dictname END), ', ') || ';'
+ FROM
+ pg_catalog.pg_ts_config_map map
+ LEFT JOIN (
+ SELECT
+ tokid,
+ alias
+ FROM
+ pg_catalog.ts_token_type(cfg.cfgparser)
+ ) t ON (t.tokid = map.maptokentype)
+ LEFT OUTER JOIN pg_catalog.pg_ts_dict dict ON (map.mapdict = dict.oid)
+ LEFT OUTER JOIN pg_catalog.pg_namespace pg_ns ON (pg_ns.oid = dict.dictnamespace)
+ WHERE
+ map.mapcfg = cfg.oid
+ GROUP BY t.alias
+ ORDER BY t.alias)
+ , E'\n') as sql
+ FROM
+ pg_catalog.pg_ts_config cfg
+ LEFT JOIN (
+ SELECT
+ des.description as description,
+ des.objoid as descoid
+ FROM
+ pg_catalog.pg_description des
+ WHERE
+ des.objoid={{cfgid}}::OID AND des.classoid='pg_ts_config'::regclass
+ ) a ON (a.descoid = cfg.oid)
+ LEFT JOIN (
+ SELECT
+ nspname,
+ nsp.oid as noid
+ FROM
+ pg_catalog.pg_namespace nsp
+ WHERE
+ oid = {{scid}}::OID
+ ) b ON (b.noid = cfg.cfgnamespace)
+ LEFT JOIN(
+ SELECT
+ prs.prsname as parsername,
+ prs.oid as oid
+ FROM
+ pg_catalog.pg_ts_parser prs
+ )c ON (c.oid = cfg.cfgparser)
+ WHERE
+ cfg.oid={{cfgid}}::OID
+ ) e;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokenDictList.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokenDictList.sql
new file mode 100644
index 0000000000000000000000000000000000000000..40315a98bcba41f836fdc6f5a4342568548c4e96
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokenDictList.sql
@@ -0,0 +1,28 @@
+{# Fetch token/dictionary list for FTS CONFIGURATION #}
+{% if cfgid %}
+SELECT
+ (
+ SELECT
+ t.alias
+ FROM
+ pg_catalog.ts_token_type(cfgparser) AS t
+ WHERE
+ t.tokid = maptokentype
+ ) AS token,
+ pg_catalog.array_agg(
+ CASE WHEN (pg_ns.nspname != 'pg_catalog') THEN
+ pg_catalog.CONCAT(pg_ns.nspname, '.', pg_ts_dict.dictname)
+ ELSE
+ pg_catalog.pg_ts_dict.dictname END) AS dictname
+FROM
+ pg_catalog.pg_ts_config_map
+ LEFT OUTER JOIN pg_catalog.pg_ts_config ON mapcfg = pg_ts_config.oid
+ LEFT OUTER JOIN pg_catalog.pg_ts_dict ON mapdict = pg_ts_dict.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace pg_ns ON pg_ns.oid = pg_ts_dict.dictnamespace
+WHERE
+ mapcfg={{cfgid}}::OID
+GROUP BY
+ token
+ORDER BY
+ 1
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokens.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokens.sql
new file mode 100644
index 0000000000000000000000000000000000000000..216ec58acd9d37b85f4465413e3760de39709e0f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/tokens.sql
@@ -0,0 +1,10 @@
+{# Tokens for FTS CONFIGURATION node #}
+
+{% if parseroid %}
+SELECT
+ alias
+FROM
+ pg_catalog.ts_token_type({{parseroid}}::OID)
+ORDER BY
+ alias
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..93327153646de83ed8694f0e45791a20db2948c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_configurations/templates/fts_configurations/sql/default/update.sql
@@ -0,0 +1,51 @@
+{# UPDATE statement for FTS CONFIGURATION #}
+{% if data %}
+{% set name = o_data.name %}
+{% set schema = o_data.schema %}
+{% if data.name and data.name != o_data.name %}
+{% set name = data.name %}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{% if 'tokens' in data %}
+{% if'changed' in data.tokens %}
+{% for tok in data.tokens.changed %}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ ALTER MAPPING FOR {{tok.token}}
+ WITH {% for dict in tok.dictname %}{{dict}}{% if not loop.last %}, {% endif %}{% endfor %};
+
+{% endfor %}
+{% endif %}
+{% if'added' in data.tokens %}
+{% for tok in data.tokens.added %}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ ADD MAPPING FOR {{tok.token}}
+ WITH {% for dict in tok.dictname %}{{dict}}{% if not loop.last %}, {% endif %}{% endfor %};
+
+{% endfor %}
+{% endif %}
+{% if'deleted' in data.tokens %}
+{% for tok in data.tokens.deleted %}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ DROP MAPPING FOR {{tok.token}};
+
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if 'owner' in data and data.owner != '' and data.owner != o_data.owner %}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ OWNER TO {{data.owner}};
+
+{% endif %}
+{% if 'schema' in data and data.schema != o_data.schema %}
+{% set schema = data.schema%}
+ALTER TEXT SEARCH CONFIGURATION {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+
+{% endif %}
+{% if 'description' in data and data.description != o_data.description %}
+COMMENT ON TEXT SEARCH CONFIGURATION {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..872d14df28a8961b5bc01309905c56895f09e6a8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/__init__.py
@@ -0,0 +1,982 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Defines views for management of Fts Dictionary node"""
+
+from functools import wraps
+
+import json
+from flask import render_template, make_response, current_app, request, jsonify
+from flask_babel import gettext as _
+
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class FtsDictionaryModule(SchemaChildModule):
+ """
+ class FtsDictionaryModule(SchemaChildModule)
+
+ A module class for FTS Dictionary node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the FtsDictionaryModule and
+ it's base module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node
+
+ * script_load()
+ - Load the module script for FTS Dictionary, when any of the schema
+ node is initialized.
+ """
+ _NODE_TYPE = 'fts_dictionary'
+ _COLLECTION_LABEL = _('FTS Dictionaries')
+
+ def __init__(self, *args, **kwargs):
+ self.min_ver = None
+ self.max_ver = None
+ self.manager = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ if self.has_nodes(
+ sid, did, scid,
+ base_template_path=FtsDictionaryView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Override the property to make the node as leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for fts template, when any of the schema
+ node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+
+blueprint = FtsDictionaryModule(__name__)
+
+
+class FtsDictionaryView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ class FtsDictionaryView(PGChildNodeView)
+
+ A view class for FTS Dictionary node derived from PGChildNodeView.
+ This class is responsible for all the stuff related to view like
+ create/update/delete FTS Dictionary,
+ showing properties of node, showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the FtsDictionaryView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * tokenize_options(self, option_value):
+ - This function will tokenize the string stored in database
+ e.g. database store the value as below
+ key1=value1, key2=value2, key3=value3, ....
+ This function will extract key and value from above string
+
+ * list()
+ - This function is used to list all the nodes within that collection.
+
+ * nodes()
+ - This function will be used to create all the child node within
+ collection.
+ Here it will create all the FTS Dictionary nodes.
+
+ * node()
+ - This function will be used to create a node given its oid
+ Here it will create the FTS Template node based on its oid
+
+ * properties(gid, sid, did, scid, dcid)
+ - This function will show the properties of the selected FTS Dictionary
+ node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new FTS Dictionary object
+
+ * update(gid, sid, did, scid, dcid)
+ - This function will update the data for the selected FTS Dictionary node
+
+ * delete(self, gid, sid, did, scid, dcid):
+ - This function will drop the FTS Dictionary object
+
+ * msql(gid, sid, did, scid, dcid)
+ - This function is used to return modified SQL for the selected node
+
+ * get_sql(data, dcid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid, dcid):
+ - This function will generate sql to show in sql pane for node.
+
+ * fetch_templates():
+ - This function will fetch all templates related to node
+
+ * dependents(gid, sid, did, scid, dcid):
+ - This function get the dependents and return ajax response for the node.
+
+ * dependencies(self, gid, sid, did, scid, dcid):
+ - This function get the dependencies and return ajax response for node.
+
+ * compare(**kwargs):
+ - This function will compare the fts dictionaries nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ BASE_TEMPLATE_PATH = 'fts_dictionaries/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'dcid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'fetch_templates': [{'get': 'fetch_templates'},
+ {'get': 'fetch_templates'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema']
+
+ def _init_(self, **kwargs):
+ self.conn = None
+ self.template_path = None
+ self.manager = None
+ super().__init__(**kwargs)
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.qtIdent = driver.qtIdent
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ def tokenize_options(self, option_value):
+ """
+ This function will tokenize the string stored in database
+ e.g. database store the value as below
+ key1=value1, key2=value2, key3=value3, ....
+ This function will extract key and value from above string
+
+ Args:
+ option_value: key value option/value pair read from database
+ """
+ if option_value is not None:
+ option_str = option_value.split(',')
+ options = []
+ for fdw_option in option_str:
+ k, v = fdw_option.split('=', 1)
+ options.append({'option': k.strip(),
+ 'value': v.strip().strip("'")})
+ return options
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ List all FTS Dictionary nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in res['rows']:
+ if row['options'] is not None:
+ row['options'] = self.tokenize_options(row['options'])
+
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ Return all FTS Dictionaries to generate nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-fts_dictionary",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, dcid):
+ """
+ Return FTS Dictionary node to generate node
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ dcid: fts dictionary id
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ dcid=dcid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(_("Could not find the FTS Dictionary node."))
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ dcid,
+ row['schema'],
+ row['name'],
+ icon="icon-fts_dictionary"
+ ),
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, dcid):
+ """
+ Show properties of FTS Dictionary node
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ dcid: fts dictionary id
+ """
+ status, res = self._fetch_properties(scid, dcid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, dcid):
+ """
+ This function is used to fetch the properties of specified object.
+
+ :param scid:
+ :param dcid:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ dcid=dcid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(_(
+ "Could not find the FTS Dictionary node in the database node."
+ ))
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ # Handle templates and its schema name properly
+ if res['rows'][0]['template_schema'] is not None and \
+ res['rows'][0]['template_schema'] != "pg_catalog":
+ res['rows'][0]['template'] = self.qtIdent(
+ self.conn, res['rows'][0]['template_schema'],
+ res['rows'][0]['template']
+ )
+
+ if res['rows'][0]['options'] is not None:
+ res['rows'][0]['options'] = self.tokenize_options(
+ res['rows'][0]['options']
+ )
+
+ return True, res['rows'][0]
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the FTS Dictionary object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+
+ # Mandatory fields to create a new FTS Dictionary
+ required_args = [
+ 'template',
+ 'schema',
+ 'name'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ # Fetch schema name from schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ # Replace schema oid with schema name before passing to create.sql
+ # To generate proper sql query
+ new_data = data.copy()
+ new_data['schema'] = schema
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn,
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need dcid to add object in tree at browser,
+ # Below sql will give the same
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ name=data['name'],
+ scid=data['schema'],
+ conn=self.conn
+ )
+ status, dcid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=dcid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ dcid,
+ data['schema'],
+ data['name'],
+ icon="icon-fts_dictionary"
+ )
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, dcid):
+ """
+ This function will update FTS Dictionary object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param dcid: fts dictionary id
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ # Fetch sql query to update fts dictionary
+ sql, name = self.get_sql(gid, sid, did, scid, data, dcid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if dcid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ dcid=dcid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ _("Could not find the FTS Dictionary node to update.")
+ )
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ dcid,
+ res['rows'][0]['schema'],
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, dcid=None, only_sql=False):
+ """
+ This function will drop the FTS Dictionary object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param dcid: FTS Dictionary id
+ :param only_sql: Return only sql if True
+ """
+ if dcid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [dcid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for dcid in data['ids']:
+ # Get name for FTS Dictionary from dcid
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ dcid=dcid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ 'Error: Object not found.'
+ ),
+ info=_(
+ 'The specified FTS dictionary '
+ 'could not be found.\n'
+ )
+ )
+
+ # Drop FTS Dictionary
+ result = res['rows'][0]
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=result['name'],
+ schema=result['schema'],
+ cascade=cascade
+ )
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=_("FTS Dictionary dropped")
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, dcid=None):
+ """
+ This function returns modified SQL
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param dcid: FTS Dictionary id
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Fetch sql query for modified data
+ SQL, _ = self.get_sql(gid, sid, did, scid, data, dcid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ def _get_sql_for_create(self, data, schema):
+ """
+ This function is used to get the create sql.
+ :param data:
+ :param schema:
+ :return:
+ """
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ new_data['schema'] = schema
+
+ if (
+ 'template' in new_data and
+ 'name' in new_data and
+ 'schema' in new_data
+ ):
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn
+ )
+ else:
+ sql = "-- definition incomplete"
+ return sql
+
+ def _check_template_name_and_schema_name(self, data, old_data):
+ """
+ This function is used to check the template and schema name.
+ :param data:
+ :param old_data:
+ :return:
+ """
+ if 'schema' not in data:
+ data['schema'] = old_data['schema']
+
+ # Handle templates and its schema name properly
+ if old_data['template_schema'] is not None and \
+ old_data['template_schema'] != "pg_catalog":
+ old_data['template'] = self.qtIdent(
+ self.conn, old_data['template_schema'],
+ old_data['template']
+ )
+
+ def get_sql(self, gid, sid, did, scid, data, dcid=None):
+ """
+ This function will return SQL for model data
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param dcid: fts dictionary id
+ """
+
+ # Fetch sql for update
+ if dcid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ dcid=dcid,
+ scid=scid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res), ''
+ elif len(res['rows']) == 0:
+ return gone(_("Could not find the FTS Dictionary node.")), ''
+
+ old_data = res['rows'][0]
+ self._check_template_name_and_schema_name(data, old_data)
+
+ # If user has changed the schema then fetch new schema directly
+ # using its oid otherwise fetch old schema name using its oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data)
+
+ status, new_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=new_schema), ''
+
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ if 'schema' in new_data:
+ new_data['schema'] = new_schema
+
+ # Fetch old schema name using old schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=old_data)
+
+ status, old_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=old_schema), ''
+
+ # Replace old schema oid with old schema name
+ old_data['schema'] = old_schema
+
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=new_data, o_data=old_data, conn=self.conn
+ )
+ # Fetch sql query for modified data
+ if 'name' in data:
+ return sql.strip('\n'), data['name']
+
+ return sql.strip('\n'), old_data['name']
+ else:
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]), data=data)
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema), ''
+
+ sql = self._get_sql_for_create(data, schema)
+ return sql.strip('\n'), data['name']
+
+ @check_precondition
+ def fetch_templates(self, gid, sid, did, scid):
+ """
+ This function will return templates list for FTS Dictionary
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ # Fetch last system oid
+ sql = render_template("/".join([self.template_path, 'templates.sql']),
+ template=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ res = []
+ for row in rset['rows']:
+ if row['nspname'] != "pg_catalog":
+ row['tmplname'] = self.qtIdent(
+ self.conn, row['nspname'], row['tmplname']
+ )
+
+ res.append({'label': row['tmplname'],
+ 'value': row['tmplname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, dcid, **kwargs):
+ """
+ This function will reverse generate sql for sql panel
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param dcid: FTS Dictionary id
+ :param json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ dcid=dcid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(_(
+ "Could not find the FTS Dictionary node in the database node."
+ ))
+
+ # Handle templates and its schema name properly
+ if res['rows'][0]['template_schema'] is not None and \
+ res['rows'][0]['template_schema'] != "pg_catalog":
+ res['rows'][0]['template'] = self.qtIdent(
+ self.conn, res['rows'][0]['template_schema'],
+ res['rows'][0]['template']
+ )
+
+ if res['rows'][0]['options'] is not None:
+ res['rows'][0]['options'] = self.tokenize_options(
+ res['rows'][0]['options']
+ )
+ else:
+ # Make it iterable
+ res['rows'][0]['options'] = []
+
+ # Fetch schema name from schema oid
+ sql = render_template("/".join(
+ [self.template_path, self._SCHEMA_SQL]), data=res['rows'][0])
+
+ status, schema = self.conn.execute_scalar(sql)
+
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ # Replace schema oid with schema name
+ res['rows'][0]['schema'] = schema
+ if target_schema:
+ res['rows'][0]['schema'] = target_schema
+
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=res['rows'][0],
+ conn=self.conn, is_displaying=True)
+
+ sql_header = """-- Text Search Dictionary: {0}.{1}\n\n""".format(
+ res['rows'][0]['schema'], res['rows'][0]['name'])
+ sql_header += """-- DROP TEXT SEARCH DICTIONARY IF EXISTS {0};\n
+""".format(self.qtIdent(self.conn, res['rows'][0]['schema'],
+ res['rows'][0]['name']))
+
+ sql = sql_header + sql
+
+ if not json_resp:
+ return sql
+
+ return ajax_response(response=sql.strip('\n'))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, dcid):
+ """
+ This function get the dependents and return ajax response
+ for the FTS Dictionary node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ dcid: FTS Dictionary ID
+ """
+ dependents_result = self.get_dependents(self.conn, dcid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, dcid):
+ """
+ This function get the dependencies and return ajax response
+ for the FTS Dictionary node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ dcid: FTS Dictionary ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, dcid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the fts dictionaries for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, dcid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, dcid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, dcid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, dcid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, FtsDictionaryView)
+FtsDictionaryView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/coll-fts_dictionary.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/coll-fts_dictionary.svg
new file mode 100644
index 0000000000000000000000000000000000000000..873f31c2e2f944844ade278bfbb0a9ad7d4b623f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/coll-fts_dictionary.svg
@@ -0,0 +1 @@
+coll-fts_dictionary
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/fts_dictionary.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/fts_dictionary.svg
new file mode 100644
index 0000000000000000000000000000000000000000..94c2fb96f77ce1d8f81f72909180f4c32f1f3077
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/img/fts_dictionary.svg
@@ -0,0 +1 @@
+fts_dictionary a
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.js
new file mode 100644
index 0000000000000000000000000000000000000000..8f684ea1f9e6024297a66633d70b8f78d884e3bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.js
@@ -0,0 +1,93 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName, getNodeListById} from '../../../../../../../static/js/node_ajax';
+import FTSDictionarySchema from './fts_dictionary.ui';
+
+define('pgadmin.node.fts_dictionary', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ // Extend the collection class for FTS Dictionary
+ if (!pgBrowser.Nodes['coll-fts_dictionary']) {
+ pgAdmin.Browser.Nodes['coll-fts_dictionary'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'fts_dictionary',
+ label: gettext('FTS Dictionaries'),
+ type: 'coll-fts_dictionary',
+ columns: ['name', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the node class for FTS Dictionary
+ if (!pgBrowser.Nodes['fts_dictionary']) {
+ pgAdmin.Browser.Nodes['fts_dictionary'] = schemaChild.SchemaChildNode.extend({
+ type: 'fts_dictionary',
+ sqlAlterHelp: 'sql-altertsdictionary.html',
+ sqlCreateHelp: 'sql-createtsdictionary.html',
+ dialogHelp: url_for('help.static', {'filename': 'fts_dictionary_dialog.html'}),
+ label: gettext('FTS Dictionary'),
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+
+ // Avoid multiple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ // Add context menus for FTS Dictionary
+ pgBrowser.add_menus([{
+ name: 'create_fts_dictionary_on_schema', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Dictionary...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_fts_dictionary_on_coll', node: 'coll-fts_dictionary',
+ module: this, applies: ['object', 'context'], priority: 4,
+ callback: 'show_obj_properties', category: 'create',
+ label: gettext('FTS Dictionary...'), data: {action: 'create'},
+ enable: 'canCreate',
+ },{
+ name: 'create_fts_dictionary', node: 'fts_dictionary', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Dictionary...'),
+ data: {action: 'create'},
+ enable: 'canCreate',
+ }]);
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new FTSDictionarySchema(
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData),
+ fts_template: ()=>getNodeAjaxOptions('fetch_templates', this, treeNodeInfo, itemNodeData, {
+ cacheNode: 'fts_template'
+ })
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: itemNodeData._id,
+ }
+ );
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['fts_dictionary'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..5bb72ce5b64db4a6fafe42442893ca2d99b57579
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/static/js/fts_dictionary.ui.js
@@ -0,0 +1,76 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import OptionsSchema from '../../../../../static/js/options.ui';
+
+export default class FTSDictionarySchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ name: undefined, // FTS Dictionary name
+ owner: undefined, // FTS Dictionary owner
+ is_sys_obj: undefined, // Is system object
+ description: undefined, // Comment on FTS Dictionary
+ schema: undefined, // Schema name FTS dictionary belongs to
+ template: undefined, // Template list for FTS dictionary node
+ options: undefined, // option/value pair list for FTS Dictionary
+ ...initValues
+ });
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ fts_template: [],
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text', type: 'text',
+ noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ editable: false, type: 'text', mode:['properties'],
+ }, {
+ id: 'owner', label: gettext('Owner'), cell: 'text',
+ editable: false, type: 'select', options: this.fieldOptions.role,
+ mode: ['properties', 'edit','create'], noEmpty: true,
+ }, {
+ id: 'schema', label: gettext('Schema'),
+ editable: false, type: 'select', options: this.fieldOptions.schema,
+ mode: ['create', 'edit'], noEmpty: true,
+ }, {
+ id: 'is_sys_obj', label: gettext('System FTS dictionary?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ }, {
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline',
+ }, {
+ id: 'template', label: gettext('Template'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.fts_template, noEmpty: true,
+ mode: ['edit', 'create', 'properties'],
+ readonly: function(state) { return !obj.isNew(state); },
+ }, {
+ id: 'options', label: gettext('Options'), type: 'collection',
+ schema: new OptionsSchema('option', 'value'),
+ group: gettext('Options'),
+ mode: ['edit', 'create'], uniqueCol : ['option'],
+ canAdd: true, canEdit: false, canDelete: true,
+ }
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ea5b405f7faf54c9af77d9f1e199339ead87f488
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_ts_dict dict
+WHERE
+{% if scid %}
+ dict.dictnamespace = {{scid}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8418a3dbe84b0d79f448757bf375c2e38ddfcb75
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/create.sql
@@ -0,0 +1,13 @@
+{# CREATE FTS DICTIONARY Statement #}
+{% if data and data.schema and data.name and data.template %}
+CREATE TEXT SEARCH DICTIONARY {{ conn|qtIdent(data.schema, data.name) }} (
+ TEMPLATE = {{ data.template }}{% for variable in data.options %}{% if "option" in variable and variable.option != '' %},
+ {{ conn|qtIdent(variable.option) }} = {% if is_displaying %}{{ variable.value }}{% else %}{{ variable.value|qtLiteral(conn) }}{% endif %}{% endif %}{% endfor %}
+
+);
+{# Description for FTS_DICTIONARY #}
+
+{% if data.description %}
+COMMENT ON TEXT SEARCH DICTIONARY {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e90273ce652a5c1de746822bc070bb22a77c1b24
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/delete.sql
@@ -0,0 +1,23 @@
+{# FETCH FTS DICTIONARY NAME Statement #}
+{% if dcid %}
+SELECT
+ dict.dictname as name,
+ (
+ SELECT
+ nspname
+ FROM
+ pg_catalog.pg_namespace
+ WHERE
+ oid = dict.dictnamespace
+ ) as schema
+FROM
+ pg_catalog.pg_ts_dict dict LEFT OUTER JOIN pg_catalog.pg_description des
+ ON (des.objoid=dict.oid AND des.classoid='pg_ts_dict'::regclass)
+WHERE
+ dict.oid = {{dcid}}::OID;
+{% endif %}
+
+{# DROP FTS DICTIOANRY Statement #}
+{% if schema and name %}
+DROP TEXT SEARCH DICTIONARY IF EXISTS {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}} {% if cascade %}CASCADE{%endif%};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..10e9abf4aac7716460ee11f4e3131a54ca81d509
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/nodes.sql
@@ -0,0 +1,19 @@
+{# Fetch FTS DICTIONARY name statement #}
+SELECT
+ dict.oid, dictname as name,
+ dictnamespace as schema,
+ des.description
+FROM
+ pg_catalog.pg_ts_dict dict
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=dict.oid AND des.classoid='pg_ts_dict'::regclass)
+WHERE
+{% if scid %}
+ dict.dictnamespace = {{scid}}::OID
+{% elif dcid %}
+ dict.oid = {{dcid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = dict.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..91a017aae0e8213f73677fa7f252cd2cfa57264a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/properties.sql
@@ -0,0 +1,26 @@
+{# FETCH properties for FTS DICTIONARY #}
+SELECT
+ dict.oid,
+ dict.dictname as name,
+ pg_catalog.pg_get_userbyid(dict.dictowner) as owner,
+ t.tmplname as template,
+ (SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = t.tmplnamespace) as template_schema,
+ dict.dictinitoption as options,
+ dict.dictnamespace as schema,
+ des.description
+FROM
+ pg_catalog.pg_ts_dict dict
+ LEFT OUTER JOIN pg_catalog.pg_ts_template t ON t.oid=dict.dicttemplate
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=dict.oid AND des.classoid='pg_ts_dict'::regclass)
+WHERE
+{% if scid is defined %}
+ dict.dictnamespace = {{scid}}::OID
+{% endif %}
+{% if name is defined %}
+ {% if scid is defined %}AND {% endif %}dict.dictname = {{name|qtLiteral(conn)}}
+{% endif %}
+{% if dcid is defined %}
+ {% if scid is defined %}AND {% else %}{% if name is defined %}AND {% endif %}{% endif %}dict.oid = {{dcid}}::OID
+{% endif %}
+ORDER BY
+ dict.dictname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8a7b35713c51ed8a7c25e8c17333370edfbf672c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/schema.sql
@@ -0,0 +1,19 @@
+{# FETCH statement for SCHEMA name #}
+{% if data.schema %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{data.schema}}::OID
+
+{% elif data.id %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT JOIN pg_catalog.pg_ts_dict dict
+ ON dict.dictnamespace = nsp.oid
+WHERE
+ dict.oid = {{data.id}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/templates.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/templates.sql
new file mode 100644
index 0000000000000000000000000000000000000000..04233c3f10a39b198d2bb365f6eb2c12a2239932
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/templates.sql
@@ -0,0 +1,11 @@
+{# FETCH templates for FTS DICTIONARY #}
+{% if template %}
+SELECT
+ tmplname,
+ nspname,
+ n.oid as schemaoid
+FROM
+ pg_catalog.pg_ts_template JOIN pg_catalog.pg_namespace n ON n.oid=tmplnamespace
+ORDER BY
+ tmplname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ff846cb01d54dcf25de08f38123188d886d47d8c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_dictionaries/templates/fts_dictionaries/sql/default/update.sql
@@ -0,0 +1,49 @@
+{# UPDATE statement for FTS DICTIONARY #}
+{% if data %}
+{% set name = o_data.name %}
+{% set schema = o_data.schema %}
+{% if data.name and data.name != o_data.name %}
+{% set name = data.name %}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(o_data.name)}}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if 'options' in data %}
+{% if'changed' in data.options %}
+{% for opt in data.options.changed %}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ ({{opt.option}}={{opt.value}});
+
+{% endfor %}
+{% endif %}
+{% if'added' in data.options%}
+{% for opt in data.options.added %}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ ({{opt.option}}={{opt.value}});
+
+{% endfor %}
+{% endif %}
+{% if'deleted' in data.options%}
+{% for opt in data.options.deleted %}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ ({{opt.option}});
+
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if 'owner' in data and data.owner != o_data.owner %}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ OWNER TO {{data.owner}};
+
+{% endif %}
+{% if 'schema' in data and data.schema != o_data.schema %}
+{% set schema = data.schema%}
+ALTER TEXT SEARCH DICTIONARY {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ SET SCHEMA {{data.schema}};
+
+{% endif %}
+{% if 'description' in data and data.description != o_data.description %}
+COMMENT ON TEXT SEARCH DICTIONARY {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cea1c80dcf1737756daf2c7e5c341e917222335
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/__init__.py
@@ -0,0 +1,1020 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Defines views for management of FTS Parser node"""
+
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext as _
+
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases import DatabaseModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class FtsParserModule(SchemaChildModule):
+ """
+ class FtsParserModule(SchemaChildModule)
+
+ A module class for FTS Parser node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * get_nodes(gid, sid, did, scid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for FTS Parser, when any of the schema node is
+ initialized.
+ """
+ _NODE_TYPE = 'fts_parser'
+ _COLLECTION_LABEL = _('FTS Parsers')
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=FtsParserView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Override the property to make the node as leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for fts template, when any of the schema node is
+ initialized.
+ """
+ return DatabaseModule.node_type
+
+
+blueprint = FtsParserModule(__name__)
+
+
+class FtsParserView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ class FtsParserView(PGChildNodeView)
+
+ A view class for FTS Parser node derived from PGChildNodeView.
+ This class is responsible for all the stuff related to view
+ like create/update/delete FTS Parser, showing properties of node,
+ showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the FtsParserView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the nodes within that collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection.
+ - Here it will create all the FTS Parser nodes.
+
+ * properties(gid, sid, did, scid, pid)
+ - This function will show the properties of the selected FTS Parser node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new FTS Parser object
+
+ * update(gid, sid, did, scid, pid)
+ - This function will update the data for the selected FTS Parser node
+
+ * delete(self, gid, sid, did, scid, pid):
+ - This function will drop the FTS Parser object
+
+ * msql(gid, sid, did, scid, pid)
+ - This function is used to return modified SQL for
+ selected FTS Parser node
+
+ * get_sql(data, pid)
+ - This function will generate sql from model data
+
+ * get_start(self, gid, sid, did, scid, pid)
+ - This function will fetch start functions list for ftp parser
+
+ * get_token(self, gid, sid, did, scid, pid)
+ - This function will fetch token functions list for ftp parser
+
+ * get_end(self, gid, sid, did, scid, pid)
+ - This function will fetch end functions list for ftp parser
+
+ * get_lextype(self, gid, sid, did, scid, pid)
+ - This function will fetch lextype functions list for ftp parser
+
+ * get_headline(self, gid, sid, did, scid, pid)
+ - This function will fetch headline functions list for ftp parser
+
+ * sql(gid, sid, did, scid, pid):
+ - This function will generate sql to show it in sql pane for the selected
+ FTS Parser node.
+
+ * get_type():
+ - This function will fetch all the types for source and
+ target types select control.
+
+ * dependents(gid, sid, did, scid, pid):
+ - This function get the dependents and return ajax response for
+ Fts Parser node.
+
+ * dependencies(self, gid, sid, did, scid, pid):
+ - This function get the dependencies and return ajax response for
+ FTS Parser node.
+
+ * compare(**kwargs):
+ - This function will compare the fts parser nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ BASE_TEMPLATE_PATH = 'fts_parsers/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'pid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'start_functions': [{'get': 'start_functions'},
+ {'get': 'start_functions'}],
+ 'token_functions': [{'get': 'token_functions'},
+ {'get': 'token_functions'}],
+ 'end_functions': [{'get': 'end_functions'}, {'get': 'end_functions'}],
+ 'lextype_functions': [{'get': 'lextype_functions'},
+ {'get': 'lextype_functions'}],
+ 'headline_functions': [{'get': 'headline_functions'},
+ {'get': 'headline_functions'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema']
+
+ def _init_(self, **kwargs):
+ """
+ Method is used to initialize the FtsParserView and it's base view.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ self.conn = None
+ self.template_path = None
+ self.manager = None
+ super().__init__(**kwargs)
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+ # Set the template path for the SQL scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-fts_parser",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, pid):
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ pid=pid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(_("Could not find the FTS Parser node."))
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ row['schema'],
+ row['name'],
+ icon="icon-fts_parser"
+ ),
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, pid):
+ """
+
+ :param gid:
+ :param sid:
+ :param did:
+ :param scid:
+ :param pid:
+ :return:
+ """
+ status, res = self._fetch_properties(scid, pid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, pid):
+ """
+ This function is used to fetch the properties of specified object.
+
+ :param scid:
+ :param pid:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ pid=pid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(
+ _("Could not find the FTS Parser node in the database node."))
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+ return True, res['rows'][0]
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the fts_parser object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+
+ # Mandatory fields to create a new fts parser
+ required_args = [
+ 'prsstart',
+ 'prstoken',
+ 'prsend',
+ 'prslextype',
+ 'schema',
+ 'name'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ # Fetch schema name from schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ # replace schema oid with schema name before passing to create.sql
+ # to generate proper sql query
+ new_data = data.copy()
+ new_data['schema'] = schema
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn,
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need fts_parser id to add object in tree at browser,
+ # below sql will give the same
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ name=data['name'],
+ scid=data['schema'] if 'schema' in data else scid,
+ conn=self.conn
+ )
+ status, pid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=pid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ pid,
+ data['schema'] if 'schema' in data else scid,
+ data['name'],
+ icon="icon-fts_parser"
+ )
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, pid):
+ """
+ This function will update text search parser object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param pid: fts parser id
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ # Fetch sql query to update fts parser
+ sql, name = self.get_sql(gid, sid, did, scid, data, pid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if pid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ pid=pid,
+ scid=data['schema'] if 'schema' in data else scid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ _("Could not find the FTS Parser node to update.")
+ )
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ pid,
+ data['schema'] if 'schema' in data else scid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, pid=None, only_sql=False):
+ """
+ This function will drop the fts_parser object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param pid: fts tempate id
+ :param only_sql: Return only sql if True
+ """
+ if pid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [pid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ try:
+ for pid in data['ids']:
+ # Get name for Parser from pid
+ sql = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ pid=pid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=_(
+ 'Error: Object not found.'
+ ),
+ info=_(
+ 'The specified FTS parser could not be found.\n'
+ )
+ )
+
+ # Drop fts Parser
+ result = res['rows'][0]
+ sql = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ name=result['name'],
+ schema=result['schema'],
+ cascade=cascade
+ )
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=_("FTS Parser dropped")
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, pid=None):
+ """
+ This function returns modified SQL
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param pid: fts tempate id
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Fetch sql query for modified data
+ SQL, _ = self.get_sql(gid, sid, did, scid, data, pid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ @staticmethod
+ def _replace_schema_oid_with_name(new_data, new_schema):
+ """
+ This function is used to replace schema oid with schema name.
+ :param new_data:
+ :param new_schema:
+ :return:
+ """
+ if 'schema' in new_data:
+ new_data['schema'] = new_schema
+
+ def _get_sql_for_create(self, data, schema):
+ """
+ This function is used to get the create sql.
+ :param data:
+ :param schema:
+ :return:
+ """
+ new_data = data.copy()
+ new_data['schema'] = schema
+
+ if (
+ 'prsstart' in new_data and
+ 'prstoken' in new_data and
+ 'prsend' in new_data and
+ 'prslextype' in new_data and
+ 'name' in new_data and
+ 'schema' in new_data
+ ):
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn
+ )
+ else:
+ sql = "-- definition incomplete"
+ return sql
+
+ def get_sql(self, gid, sid, did, scid, data, pid=None):
+ """
+ This function will return SQL for model data
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param pid: fts tempate id
+ """
+
+ # Fetch sql for update
+ if pid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ pid=pid,
+ scid=scid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return gone(_("Could not find the FTS Parser node."))
+
+ old_data = res['rows'][0]
+ if 'schema' not in data:
+ data['schema'] = old_data['schema']
+
+ # If user has changed the schema then fetch new schema directly
+ # using its oid otherwise fetch old schema name with parser oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data)
+
+ status, new_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=new_schema)
+
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ FtsParserView._replace_schema_oid_with_name(new_data, new_schema)
+
+ # Fetch old schema name using old schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=old_data
+ )
+
+ status, old_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=old_schema)
+
+ # Replace old schema oid with old schema name
+ old_data['schema'] = old_schema
+
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=new_data,
+ o_data=old_data,
+ conn=self.conn
+ )
+ # Fetch sql query for modified data
+ if 'name' in data:
+ return sql.strip('\n'), data['name']
+ return sql.strip('\n'), old_data['name']
+ else:
+ # Fetch schema name from schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ sql = self._get_sql_for_create(data, schema)
+ return sql.strip('\n'), data['name']
+
+ @check_precondition
+ def start_functions(self, gid, sid, did, scid):
+ """
+ This function will return start functions list for fts Parser
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template("/".join([self.template_path,
+ self._FUNCTIONS_SQL]),
+ start=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at start select control while creating a new fts parser
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def token_functions(self, gid, sid, did, scid):
+ """
+ This function will return token functions list for fts Parser
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template("/".join([self.template_path,
+ self._FUNCTIONS_SQL]),
+ token=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at token select control while creating a new fts parser
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def end_functions(self, gid, sid, did, scid):
+ """
+ This function will return end functions list for fts Parser
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template("/".join([self.template_path,
+ self._FUNCTIONS_SQL]),
+ end=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at end select control while creating a new fts parser
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def lextype_functions(self, gid, sid, did, scid):
+ """
+ This function will return lextype functions list for fts Parser
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template("/".join([self.template_path,
+ self._FUNCTIONS_SQL]),
+ lextype=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at lextype select control while creating a new fts parser
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def headline_functions(self, gid, sid, did, scid):
+ """
+ This function will return headline functions list for fts Parser
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ sql = render_template("/".join([self.template_path,
+ self._FUNCTIONS_SQL]),
+ headline=True)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at headline select control while creating a new fts parser
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, pid, **kwargs):
+ """
+ This function will reverse generate sql for sql panel
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param pid: fts tempate id
+ :param json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ try:
+ sql = render_template(
+ "/".join([self.template_path, 'sql.sql']),
+ pid=pid,
+ scid=scid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(
+ _(
+ "Could not generate reversed engineered query for the "
+ "FTS Parser.\n{0}"
+ ).format(res)
+ )
+
+ if res is None:
+ return gone(
+ _(
+ "Could not generate reversed engineered query for "
+ "FTS Parser node."
+ )
+ )
+
+ # Used for schema diff tool
+ if target_schema:
+ data = {'schema': scid}
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ res = res.replace(schema, target_schema)
+
+ if not json_resp:
+ return res
+
+ return ajax_response(response=res)
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, pid):
+ """
+ This function get the dependents and return ajax response
+ for the FTS Parser node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pid: FTS Parser ID
+ """
+ dependents_result = self.get_dependents(self.conn, pid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, pid):
+ """
+ This function get the dependencies and return ajax response
+ for the FTS Parser node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pid: FTS Tempalte ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, pid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the fts parsers for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, pid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, pid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, pid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, pid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, FtsParserView)
+FtsParserView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/coll-fts_parser.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/coll-fts_parser.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f1c9e7caf011bde6eef57cb9f473cd8f6d10e06b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/coll-fts_parser.svg
@@ -0,0 +1 @@
+coll-fts_parser Aa
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/fts_parser.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/fts_parser.svg
new file mode 100644
index 0000000000000000000000000000000000000000..720f4484cdefff155ddc93098d3f701446a22bb7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/img/fts_parser.svg
@@ -0,0 +1 @@
+fts_parser Aa
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.js
new file mode 100644
index 0000000000000000000000000000000000000000..e391367c01218152f297c1225d28def5c769deab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.js
@@ -0,0 +1,102 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import FTSParserSchema from './fts_parser.ui';
+import { getNodeAjaxOptions, getNodeListById } from '../../../../../../../static/js/node_ajax';
+
+define('pgadmin.node.fts_parser', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.node.schema.dir/child',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode) {
+
+ // Extend the collection class for fts parser
+ if (!pgBrowser.Nodes['coll-fts_parser']) {
+ pgAdmin.Browser.Nodes['coll-fts_parser'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'fts_parser',
+ label: gettext('FTS Parsers'),
+ type: 'coll-fts_parser',
+ columns: ['name', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the node class for fts parser
+ if (!pgBrowser.Nodes['fts_parser']) {
+ pgAdmin.Browser.Nodes['fts_parser'] = schemaChild.SchemaChildNode.extend({
+ type: 'fts_parser',
+ sqlAlterHelp: 'sql-altertsparser.html',
+ sqlCreateHelp: 'sql-createtsparser.html',
+ dialogHelp: url_for('help.static', {'filename': 'fts_parser_dialog.html'}),
+ label: gettext('FTS Parser'),
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+
+ // Avoid multiple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ // Add context menus for fts parser
+ pgBrowser.add_menus([{
+ name: 'create_fts_parser_on_schema', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Parser...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_fts_parser_on_coll', node: 'coll-fts_parser',
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Parser...'),
+ data: {action: 'create'}, module: this, enable: 'canCreate',
+ },{
+ name: 'create_fts_parser', node: 'fts_parser', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Parser...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ }]);
+
+ },
+
+ getSchema: (treeNodeInfo, itemNodeData) => {
+ let nodeObj = pgAdmin.Browser.Nodes['fts_parser'];
+ return new FTSParserSchema(
+ {
+ prsstartList: () => getNodeAjaxOptions('start_functions', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ }),
+ prstokenList: () => getNodeAjaxOptions('token_functions', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ }),
+ prsendList: () => getNodeAjaxOptions('end_functions', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ }),
+ prslextypeList: () => getNodeAjaxOptions('lextype_functions', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ }),
+ prsheadlineList: () => getNodeAjaxOptions('headline_functions', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database',
+ }),
+ schemaList:() => getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ })
+ },
+ {
+ schema: itemNodeData._id,
+ }
+ );
+ }
+ });
+ }
+
+ return pgBrowser.Nodes['coll-fts_parser'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..598436f355d5af7b0282e761b0d52701527e7338
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/static/js/fts_parser.ui.js
@@ -0,0 +1,140 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class FTSParserSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ name: null,
+ oid: undefined,
+ version: '',
+ schema: undefined,
+ description: '',
+ is_sys_obj: false,
+ ...initValues
+ });
+ this.fieldOptions = {
+ prsstartList: [],
+ prstokenList: [],
+ prsendList: [],
+ prslextypeList: [],
+ prsheadlineList: [],
+ schemaList: [],
+ ...fieldOptions
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', cellHeaderClasses: 'width_percent_50', noEmpty: true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ editable: false, type: 'text', mode:['properties'],
+ },{
+ id: 'schema', label: gettext('Schema'), cell: 'string',
+ type: 'select', mode: ['create','edit'], node: 'schema',
+ noEmpty: true, options: this.fieldOptions.schemaList
+ },{
+ id: 'is_sys_obj', label: gettext('System FTS parser?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', cellHeaderClasses: 'width_percent_50',
+ },{
+ id: 'prsstart', label: gettext('Start function'),
+ group: gettext('Definition'), noEmpty: true,
+ readonly: function(state) { return !obj.isNew(state); },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.prsstartList,
+ optionsLoaded: (options) => { obj.fieldOptions.prsstartList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ },{
+ id: 'prstoken', label: gettext('Get next token function'), group: gettext('Definition'),
+ noEmpty: true, readonly: function(state) { return !obj.isNew(state); },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.prstokenList,
+ optionsLoaded: (options) => { obj.fieldOptions.prstokenList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ },{
+ id: 'prsend', label: gettext('End function'), group: gettext('Definition'),
+ noEmpty: true, readonly: function(state) { return !obj.isNew(state); },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.prsendList,
+ optionsLoaded: (options) => { obj.fieldOptions.prsendList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ },{
+ id: 'prslextype', label: gettext('Lextypes function'), group: gettext('Definition'),
+ noEmpty: true, readonly: function(state) { return !obj.isNew(state); },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.prslextypeList,
+ optionsLoaded: (options) => { obj.fieldOptions.prslextypeList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ },{
+ id: 'prsheadline', label: gettext('Headline function'), group: gettext('Definition'),
+ readonly: function(state) { return !obj.isNew(state); },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.prsheadlineList,
+ optionsLoaded: (options) => { obj.fieldOptions.prsheadlineList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ }];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5d51911f0eb9ec9c040ada86fafcd89ce24f76db
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_ts_parser prs
+WHERE
+{% if scid %}
+ prs.prsnamespace = {{scid}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c38088ba28c8dbaec8aabcb782fedd56ee8b4c6b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/create.sql
@@ -0,0 +1,15 @@
+{# CREATE FTS PARSER Statement #}
+{% if data and data.schema and data.name and data.prsstart and data.prstoken and data.prsend and data.prslextype %}
+CREATE TEXT SEARCH PARSER {{ conn|qtIdent(data.schema, data.name) }} (
+ START = {{data.prsstart}},
+ GETTOKEN = {{data.prstoken}},
+ END = {{data.prsend}},
+ LEXTYPES = {{data.prslextype}}{% if data.prsheadline and data.prsheadline != '-'%},
+ HEADLINE = {{data.prsheadline}}{% endif %}
+);
+
+{# Description for FTS_PARSER #}
+{% if data.description %}
+COMMENT ON TEXT SEARCH PARSER {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9918bdd909cef8dd0d967da1e331d700318ddbb8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/delete.sql
@@ -0,0 +1,23 @@
+{# FETCH FTS PARSER NAME Statement #}
+{% if pid %}
+SELECT
+ p.prsname AS name,
+ (
+ SELECT
+ nspname
+ FROM
+ pg_catalog.pg_namespace
+ WHERE
+ oid = p.prsnamespace
+ ) as schema
+FROM
+ pg_catalog.pg_ts_parser p LEFT JOIN pg_catalog.pg_description d
+ ON d.objoid=p.oid AND d.classoid='pg_ts_parser'::regclass
+WHERE
+ p.oid = {{pid}}::OID;
+{% endif %}
+
+{# DROP FTS PARSER Statement #}
+{% if schema and name %}
+DROP TEXT SEARCH PARSER IF EXISTS {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}} {% if cascade %}CASCADE{%endif%};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2c3c6a52361304e35e8bf632f9221d93e91e5365
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/functions.sql
@@ -0,0 +1,58 @@
+{# FETCH start functions for FTS_PARSER #}
+{% if start %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ proargtypes='2281 23'
+ORDER BY proname;
+{% endif %}
+
+{# FETCH token functions for FTS_PARSER #}
+{% if token %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ proargtypes='2281 2281 2281'
+ORDER BY
+ proname;
+{% endif %}
+
+{# FETCH end functions for FTS_PARSER #}
+{% if end %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ prorettype=2278 and proargtypes='2281'
+ORDER BY
+ proname;
+{% endif %}
+
+{# FETCH lextype functions for FTS_PARSER #}
+{% if lextype %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ prorettype=2281 and proargtypes='2281'
+ORDER BY
+ proname;
+{% endif %}
+
+{# FETCH headline functions for FTS_PARSER #}
+{% if headline %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ proargtypes='2281 2281 3615'
+ORDER BY
+ proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d547baeaf39da81d8cbc0306dce521197e9b6f16
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/nodes.sql
@@ -0,0 +1,22 @@
+{# FETCH FTS PARSER name statement #}
+SELECT
+ prs.oid, prsname as name, prs.prsnamespace AS schema, des.description
+FROM
+ pg_catalog.pg_ts_parser prs
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ON
+ (
+ des.objoid=prs.oid
+ AND des.classoid='pg_ts_parser'::regclass
+ )
+WHERE
+{% if scid %}
+ prs.prsnamespace = {{scid}}::OID
+{% elif pid %}
+ prs.oid = {{pid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = prs.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..91832480054b9efe1061d586b95a23c71cd86395
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/properties.sql
@@ -0,0 +1,30 @@
+{# FETCH properties for FTS PARSER #}
+SELECT
+ prs.oid,
+ prs.prsname as name,
+ prs.prsstart,
+ prs.prstoken,
+ prs.prsend,
+ prs.prslextype,
+ prs.prsheadline,
+ description,
+ prs.prsnamespace AS schema
+FROM
+ pg_catalog.pg_ts_parser prs
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ON
+ (
+ des.objoid=prs.oid
+ AND des.classoid='pg_ts_parser'::regclass
+ )
+WHERE
+{% if scid %}
+ prs.prsnamespace = {{scid}}::OID
+{% endif %}
+{% if name %}
+ {% if scid %}AND {% endif %}prs.prsname = {{name|qtLiteral(conn)}}
+{% endif %}
+{% if pid %}
+ {% if name %}AND {% else %}{% if scid %}AND {% endif %}{% endif %}prs.oid = {{pid}}::OID
+{% endif %}
+ORDER BY prs.prsname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..880efa95ed1f717ed8d24376a842fed973ab3575
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/schema.sql
@@ -0,0 +1,19 @@
+{# FETCH statement for SCHEMA name #}
+{% if data.schema %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{data.schema}}::OID
+
+{% elif data.id %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT JOIN pg_catalog.pg_ts_parser prs
+ ON prs.prsnamespace = nsp.oid
+WHERE
+ prs.oid = {{data.id}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/sql.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/sql.sql
new file mode 100644
index 0000000000000000000000000000000000000000..85fc82588c514bc8c77444e601c98b047e7e528d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/sql.sql
@@ -0,0 +1,46 @@
+{# Reverse engineered sql for FTS PARSER #}
+{% if pid and scid %}
+SELECT
+ pg_catalog.array_to_string(array_agg(sql), E'\n\n') as sql
+FROM
+ (
+ SELECT
+ E'-- Text Search Parser: ' || pg_catalog.quote_ident(nspname) || E'.' || prs.prsname ||
+ E'\n\n-- DROP TEXT SEARCH PARSER ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(prs.prsname) ||
+ E'\n\nCREATE TEXT SEARCH PARSER ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(prs.prsname) || E' (\n' ||
+ E' START = ' || prs.prsstart || E',\n' ||
+ E' GETTOKEN = ' || prs.prstoken || E',\n' ||
+ E' END = ' || prs.prsend || E',\n' ||
+ E' LEXTYPES = ' || prs.prslextype ||
+ CASE
+ WHEN prs.prsheadline != '-'::regclass THEN E',\n HEADLINE = ' || prs.prsheadline
+ ELSE '' END || E'\n);' ||
+ CASE
+ WHEN description IS NOT NULL THEN
+ E'\n\nCOMMENT ON TEXT SEARCH PARSER ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(prs.prsname) ||
+ E' IS ' || pg_catalog.quote_literal(description) || E';'
+ ELSE '' END as sql
+ FROM
+ pg_catalog.pg_ts_parser prs
+ LEFT JOIN (
+ SELECT
+ des.description as description,
+ des.objoid as descoid
+ FROM
+ pg_catalog.pg_description des
+ WHERE
+ des.objoid={{pid}}::OID AND des.classoid='pg_ts_parser'::regclass
+ ) a ON (a.descoid = prs.oid)
+ LEFT JOIN (
+ SELECT
+ nspname,
+ nsp.oid as noid
+ FROM
+ pg_catalog.pg_namespace nsp
+ WHERE
+ oid = {{scid}}::OID
+ ) b ON (b.noid = prs.prsnamespace)
+WHERE
+ prs.oid={{pid}}::OID
+) as c;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fbb108518418bf55e72ff046568ae97b3bc78d05
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_parsers/templates/fts_parsers/sql/default/update.sql
@@ -0,0 +1,39 @@
+{# UPDATE statement for FTS PARSER #}
+{% if data %}
+{% if data.name and data.name != o_data.name %}
+ALTER TEXT SEARCH PARSER {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+{% endif %}
+
+{#in case of rename, use new fts template name #}
+{% if data.name and data.name != o_data.name %}
+{% set name = data.name %}
+{% else %}
+{% set name = o_data.name %}
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TEXT SEARCH PARSER {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ SET SCHEMA {{data.schema}};
+{% endif %}
+{# Schema Diff SQL for FTS PARSER #}
+{% if data.prsstart or data.prstoken or data.prsend or data.prslextype or data.prsheadline %}
+-- WARNING:
+-- We have found the difference in either of START or GETTOKEN or END or
+-- LEXTYPES or HEADLINE, so we need to drop the existing parser first
+-- and re-create it.
+DROP TEXT SEARCH PARSER {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}};
+
+CREATE TEXT SEARCH PARSER {{ conn|qtIdent(o_data.schema, name) }} (
+ START = {% if data.prsstart is defined %}{{data.prsstart}}{% else %}{{o_data.prsstart}}{% endif %},
+ GETTOKEN = {% if data.prstoken is defined %}{{data.prstoken}}{% else %}{{o_data.prstoken}}{% endif %},
+ END = {% if data.prsend is defined %}{{data.prsend}}{% else %}{{o_data.prsend}}{% endif %},
+ LEXTYPES = {% if data.prslextype is defined %}{{data.prslextype}}{% else %}{{o_data.prslextype}}{% endif %}{% if (data.prsheadline and data.prsheadline != '-') or (o_data.prsheadline and o_data.prsheadline != '-') %},
+ HEADLINE = {% if data.prsheadline is defined %}{{data.prsheadline}}{% else %}{{o_data.prsheadline}}{% endif %}{% endif %}
+
+);
+{% endif %}
+{% if "description" in data and data.description != o_data.description %}
+COMMENT ON TEXT SEARCH PARSER {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fb9a8ade74c78d9f164fe84e24475d9306b8f61
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/__init__.py
@@ -0,0 +1,886 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Defines views for management of Fts Template node"""
+
+from functools import wraps
+
+import json
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext
+
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases import DatabaseModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class FtsTemplateModule(SchemaChildModule):
+ """
+ class FtsTemplateModule(SchemaChildModule)
+
+ A module class for FTS Template node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the FtsTemplateModule and it's base
+ module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for FTS Template, when any of the schema node is
+ initialized.
+ """
+ _NODE_TYPE = 'fts_template'
+ _COLLECTION_LABEL = gettext('FTS Templates')
+
+ def __init__(self, *args, **kwargs):
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+ if self.has_nodes(
+ sid, did, scid,
+ base_template_path=FtsTemplateView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Override the property to make the node as leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for fts template, when any of the schema node is
+ initialized.
+ """
+ return DatabaseModule.node_type
+
+
+blueprint = FtsTemplateModule(__name__)
+
+
+class FtsTemplateView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ class FtsTemplateView(PGChildNodeView)
+
+ A view class for FTS Tempalte node derived from PGChildNodeView. This
+ class is responsible for all the stuff related to view like
+ create/update/delete responsible for all the stuff related to view
+ like create/update/delete FTS template, showing properties of node,
+ showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the FtsTemplateView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the nodes within that collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection.
+ Here it will create all the FTS Template nodes.
+
+ * properties(gid, sid, did, scid, tid)
+ - This function will show the properties of the selected FTS Template
+ node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new FTS Template object
+
+ * update(gid, sid, did, scid, tid)
+ - This function will update the data for the selected FTS Template node
+
+ * delete(self, gid, sid, did, scid, tid):
+ - This function will drop the FTS Template object
+
+ * msql(gid, sid, did, scid, tid)
+ - This function is used to return modified SQL for the selected FTS
+ Template node
+
+ * get_sql(data, tid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid, tid):
+ - This function will generate sql to show it in sql pane for the selected
+ FTS Template node.
+
+ * get_type():
+ - This function will fetch all the types for source and target types
+ select control.
+
+ * dependents(gid, sid, did, scid, tid):
+ - This function get the dependents and return ajax response for the
+ Fts Template node.
+
+ * dependencies(self, gid, sid, did, scid, tid):
+ - This function get the dependencies and return ajax response for the
+ FTS Template node.
+
+ * compare(**kwargs):
+ - This function will compare the fts template nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "FTS Template"
+ BASE_TEMPLATE_PATH = 'fts_templates/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'tid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_lexize': [{'get': 'get_lexize'}, {'get': 'get_lexize'}],
+ 'get_init': [{'get': 'get_init'}, {'get': 'get_init'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema']
+
+ def _init_(self, **kwargs):
+ self.conn = None
+ self.template_path = None
+ self.manager = None
+ super().__init__(**kwargs)
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-fts_template",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid):
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ tid=tid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ row['schema'],
+ row['name'],
+ icon="icon-fts_template"
+ ),
+ status=200
+ )
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid):
+ """
+
+ :param gid:
+ :param sid:
+ :param did:
+ :param scid:
+ :param tid:
+ :return:
+ """
+ status, res = self._fetch_properties(scid, tid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, tid):
+ """
+ This function is used to fetch the properties of specified object.
+
+ :param scid:
+ :param pid:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ tid=tid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+ return True, res['rows'][0]
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the fts_template object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ """
+
+ # Mandatory fields to create a new fts template
+ required_args = [
+ 'tmpllexize',
+ 'schema',
+ 'name'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ # replace schema oid with schema name before passing to create.sql
+ # to generate proper sql query
+ new_data = data.copy()
+ new_data['schema'] = schema
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn,
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need fts_template id to add object in tree at browser,
+ # below sql will give the same
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ name=data['name'],
+ scid=data['schema'] if 'schema' in data else scid,
+ conn=self.conn
+ )
+ status, tid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ data['schema'] if 'schema' in data else scid,
+ data['name'],
+ icon="icon-fts_template"
+ )
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid):
+ """
+ This function will update text search template object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ # Fetch sql query to update fts template
+ sql, _ = self.get_sql(gid, sid, did, scid, data, tid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ tid=tid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ rset = rset['rows'][0]
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ rset['schema'],
+ rset['name'],
+ icon="icon-%s" % self.node_type,
+ description=rset['description']
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid=None, only_sql=False):
+ """
+ This function will drop the fts_template object
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ :param only_sql: Return only sql if True
+ """
+ if tid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [tid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ for tid in data['ids']:
+ # Get name for template from tid
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ tid=tid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ # Drop fts template
+ result = res['rows'][0]
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=result['name'],
+ schema=result['schema'],
+ cascade=cascade
+ )
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("FTS Template dropped")
+ )
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid=None):
+ """
+ This function returns modified SQL
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Fetch sql query for modified data
+ SQL, _ = self.get_sql(gid, sid, did, scid, data, tid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ def _replace_schema_oid_with_name(self, new_schema, old_data, new_data):
+ """
+ This function is used to Replace schema oid with schema name
+ :param new_schema:
+ :param old_data:
+ :param new_data:
+ :return:
+ """
+ if 'schema' in new_data:
+ new_data['schema'] = new_schema
+
+ # Fetch old schema name using old schema oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=old_data)
+
+ status, old_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return True, old_schema
+
+ # Replace old schema oid with old schema name
+ old_data['schema'] = old_schema
+ return False, ''
+
+ def _get_sql_for_create(self, data, schema):
+ """
+ This function is used to get the create sql.
+ :param data:
+ :param schema:
+ :return:
+ """
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ new_data['schema'] = schema
+
+ if (
+ 'tmpllexize' in new_data and
+ 'name' in new_data and
+ 'schema' in new_data
+ ):
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=new_data,
+ conn=self.conn
+ )
+ else:
+ sql = "-- definition incomplete"
+ return sql
+
+ def get_sql(self, gid, sid, did, scid, data, tid=None):
+ """
+ This function will return SQL for model data
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param data: sql data
+ :param tid: fts tempate id
+ """
+
+ # Fetch sql for update
+ if tid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid,
+ scid=scid,
+ conn=self.conn
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res), ''
+ elif len(res['rows']) == 0:
+ return gone(self.not_found_error_msg()), ''
+
+ old_data = res['rows'][0]
+ if 'schema' not in data:
+ data['schema'] = old_data['schema']
+
+ # If user has changed the schema then fetch new schema directly
+ # using its oid otherwise fetch old schema name using
+ # fts template oid
+ sql = render_template(
+ "/".join([self.template_path, self._SCHEMA_SQL]),
+ data=data)
+
+ status, new_schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=new_schema), ''
+
+ # Replace schema oid with schema name
+ new_data = data.copy()
+ error, errmsg = self._replace_schema_oid_with_name(new_schema,
+ old_data,
+ new_data)
+ if error:
+ print('ERROR INSIDE UPDATE:: {0}'.format(errmsg))
+ return internal_server_error(errormsg=errmsg), ''
+
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=new_data, o_data=old_data, conn=self.conn
+ )
+
+ # Fetch sql query for modified data
+ if 'name' in data:
+ return sql.strip('\n'), data['name']
+ return sql.strip('\n'), old_data['name']
+ else:
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data)
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema), ''
+
+ sql = self._get_sql_for_create(data, schema)
+ return sql.strip('\n'), data['name']
+
+ @check_precondition
+ def get_lexize(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return lexize functions list for fts template
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._FUNCTIONS_SQL]), lexize=True
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Empty set is added before actual list as initially it will be visible
+ # at lexize select control while creating a new fts template
+ res = [{'label': '', 'value': ''}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def get_init(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return init functions list for fts template
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ """
+ sql = render_template(
+ "/".join([self.template_path, self._FUNCTIONS_SQL]), init=True
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # We have added this to map against '-' which is coming from server
+ res = [{'label': '', 'value': '-'}]
+ for row in rset['rows']:
+ res.append({'label': row['proname'],
+ 'value': row['proname']})
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will reverse generate sql for sql panel
+ :param gid: group id
+ :param sid: server id
+ :param did: database id
+ :param scid: schema id
+ :param tid: fts tempate id
+ :param json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ sql = render_template(
+ "/".join([self.template_path, 'sql.sql']),
+ tid=tid,
+ scid=scid,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(
+ gettext(
+ "Could not generate reversed engineered query for the "
+ "FTS Template.\n{0}").format(res)
+ )
+
+ if res is None:
+ return gone(
+ gettext(
+ "Could not generate reversed engineered query for "
+ "FTS Template node.")
+ )
+
+ # Used for schema diff tool
+ if target_schema:
+ data = {'schema': scid}
+ # Fetch schema name from schema oid
+ sql = render_template("/".join([self.template_path,
+ self._SCHEMA_SQL]),
+ data=data,
+ conn=self.conn,
+ )
+
+ status, schema = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=schema)
+
+ res = res.replace(schema, target_schema)
+
+ if not json_resp:
+ return res
+
+ return ajax_response(response=res)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependents and return ajax response
+ for the FTS Template node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: FTS Template ID
+ """
+ dependents_result = self.get_dependents(self.conn, tid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependencies and return ajax response
+ for the FTS Template node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: FTS Tempalte ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, tid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the fts templates for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = self.get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, tid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, tid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, tid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, tid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, FtsTemplateView)
+FtsTemplateView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/coll-fts_template.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/coll-fts_template.svg
new file mode 100644
index 0000000000000000000000000000000000000000..10774268a85b2910e2cf91338465d2cf29a4ccfc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/coll-fts_template.svg
@@ -0,0 +1 @@
+coll-fts_template
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/fts_template.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/fts_template.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f00f549f760dd3af95f0121f36381827b1ae0828
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/img/fts_template.svg
@@ -0,0 +1 @@
+fts_template
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.js
new file mode 100644
index 0000000000000000000000000000000000000000..02fe0e89425b5a3172b5b7ed1f6ea36429626de8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.js
@@ -0,0 +1,91 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import FTSTemplateSchema from './fts_template.ui';
+import { getNodeAjaxOptions, getNodeListById } from '../../../../../../../static/js/node_ajax';
+
+define('pgadmin.node.fts_template', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.node.schema.dir/child',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode) {
+
+ // Extend the collection class for fts template
+ if (!pgBrowser.Nodes['coll-fts_template']) {
+ pgAdmin.Browser.Nodes['coll-fts_template'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'fts_template',
+ label: gettext('FTS Templates'),
+ type: 'coll-fts_template',
+ columns: ['name', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the node class for fts template
+ if (!pgBrowser.Nodes['fts_template']) {
+ pgAdmin.Browser.Nodes['fts_template'] = schemaChild.SchemaChildNode.extend({
+ type: 'fts_template',
+ sqlAlterHelp: 'sql-altertstemplate.html',
+ sqlCreateHelp: 'sql-createtstemplate.html',
+ dialogHelp: url_for('help.static', {'filename': 'fts_template_dialog.html'}),
+ label: gettext('FTS Template'),
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+
+ // Avoid multiple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ // Add context menus for fts template
+ pgBrowser.add_menus([{
+ name: 'create_fts_template_on_schema', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Template...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_fts_template_on_coll', node: 'coll-fts_template', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Template...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ },{
+ name: 'create_fts_template', node: 'fts_template', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('FTS Template...'),
+ data: {action: 'create'}, enable: 'canCreate',
+ }]);
+
+ },
+
+ getSchema: (treeNodeInfo, itemNodeData) => {
+ let nodeObj = pgAdmin.Browser.Nodes['fts_template'];
+ return new FTSTemplateSchema(
+ {
+ initFunctionList:()=>getNodeAjaxOptions('get_init', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ lexisFunctionList:()=>getNodeAjaxOptions('get_lexize', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ schemaList:()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData),
+ },
+ {
+ schema: itemNodeData._id,
+ }
+ );
+ }
+ });
+ }
+
+ return pgBrowser.Nodes['fts_template'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..e2e74281abb41f296fb3a37fc3b31702a666e446
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/static/js/fts_template.ui.js
@@ -0,0 +1,95 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class FTSTemplateSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ name: null,
+ oid: undefined,
+ version: '',
+ schema: undefined,
+ description: '',
+ is_sys_obj: false,
+ tmplinit: undefined,
+ tmpllexize: undefined, // Lexize function for fts template
+ ...initValues
+ });
+ this.fieldOptions = {
+ schemaList: [],
+ initFunctionList: [],
+ lexisFunctionList: [],
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string', type: 'text',
+ cellHeaderClasses: 'width_percent_50', noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ editable: false, type: 'text', mode: ['properties'],
+ }, {
+ id: 'schema', label: gettext('Schema'), mode: ['create', 'edit'], node: 'schema',
+ type: 'select', editable: false, noEmpty: true, options: this.fieldOptions.schemaList,
+ }, {
+ id: 'is_sys_obj', label: gettext('System FTS template?'),
+ cell: 'boolean', type: 'switch', mode: ['properties'],
+ }, {
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', cellHeaderClasses: 'width_percent_50',
+ }, {
+ id: 'tmplinit', label: gettext('Init function'), group: gettext('Definition'),
+ cache_level: 'database', cache_node: 'schema',
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.initFunctionList,
+ optionsLoaded: (options) => { obj.fieldOptions.initFunctionData = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ }, {
+ id: 'tmpllexize', label: gettext('Lexize function'), group: gettext('Definition'),
+ noEmpty: true, cache_level: 'database', cache_node: 'schema',
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.lexisFunctionList,
+ optionsLoaded: (options) => { obj.fieldOptions.lexisFunctionData = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ }];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..03298feae3ad390934bb6c233a2b42a98c67ebb2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_ts_template tmpl
+WHERE
+{% if scid %}
+ tmpl.tmplnamespace = {{scid}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..17b357297d2caed2241c923e369160a8f20d1c29
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/create.sql
@@ -0,0 +1,11 @@
+{# CREATE TEXT SEARCH TEMPLATE Statement #}
+{% if data and data.schema and data.name and data.tmpllexize %}
+CREATE TEXT SEARCH TEMPLATE {{ conn|qtIdent(data.schema, data.name) }} (
+{% if data.tmplinit and data.tmplinit != '-'%} INIT = {{data.tmplinit}},{% endif %}
+ LEXIZE = {{data.tmpllexize}}
+);
+{# Description for TEXT SEARCH TEMPLATE #}
+{% if data.description %}
+COMMENT ON TEXT SEARCH TEMPLATE {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6c4bdb119f1afe451cf4ec91f43b756ce8f5f4c1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/delete.sql
@@ -0,0 +1,23 @@
+{# FETCH TEXT SEARCH TEMPLATE NAME Statement #}
+{% if tid %}
+SELECT
+ t.tmplname AS name,
+ (
+ SELECT
+ nspname
+ FROM
+ pg_catalog.pg_namespace
+ WHERE
+ oid = t.tmplnamespace
+ ) as schema
+FROM
+ pg_catalog.pg_ts_template t LEFT JOIN pg_catalog.pg_description d
+ ON d.objoid=t.oid AND d.classoid='pg_ts_template'::regclass
+WHERE
+ t.oid = {{tid}}::OID;
+{% endif %}
+
+{# DROP TEXT SEARCH TEMPLATE Statement #}
+{% if schema and name %}
+DROP TEXT SEARCH TEMPLATE IF EXISTS {{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}} {% if cascade %}CASCADE{%endif%};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c2098ae0810cc54389129a98e7adb30ab6af7cfa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/functions.sql
@@ -0,0 +1,23 @@
+{# FETCH lexize functions for TEXT SEARCH TEMPLATE #}
+{% if lexize %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ prorettype=2281
+ AND proargtypes='2281 2281 2281 2281'
+ORDER BY proname;
+{% endif %}
+
+{# FETCH init functions for TEXT SEARCH TEMPLATE #}
+{% if init %}
+SELECT
+ proname, nspname
+FROM
+ pg_catalog.pg_proc JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE
+ prorettype=2281 and proargtypes='2281'
+ORDER BY
+ proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f7b2bf61b99103b63dfb61ce75d74984cf30340c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/nodes.sql
@@ -0,0 +1,21 @@
+SELECT
+ tmpl.oid, tmplname as name, tmpl.tmplnamespace AS schema, des.description
+FROM
+ pg_catalog.pg_ts_template tmpl
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ON
+ (
+ des.objoid=tmpl.oid
+ AND des.classoid='pg_ts_template'::regclass
+ )
+WHERE
+{% if scid %}
+ tmpl.tmplnamespace = {{scid}}::OID
+{% elif tid %}
+ tmpl.oid = {{tid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = tmpl.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a161c7fc7b4d025881ce75221f5e454eb2a8b3a8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/properties.sql
@@ -0,0 +1,28 @@
+{# Get properties for FTS TEMPLATE #}
+SELECT
+ tmpl.oid,
+ tmpl.tmplname as name,
+ tmpl.tmplinit,
+ tmpl.tmpllexize,
+ description,
+ tmpl.tmplnamespace AS schema
+FROM
+ pg_catalog.pg_ts_template tmpl
+ LEFT OUTER JOIN pg_catalog.pg_description des
+ON
+ (
+ des.objoid=tmpl.oid
+ AND des.classoid='pg_ts_template'::regclass
+ )
+WHERE
+{% if scid is defined %}
+ tmpl.tmplnamespace = {{scid}}::OID
+{% endif %}
+{% if name is defined %}
+ {% if scid is defined %}AND {% endif %}tmpl.tmplname = {{name|qtLiteral(conn)}}
+{% endif %}
+{% if tid is defined %}
+ {% if name is defined %}AND {% else %}{% if scid is defined %}AND {% endif %}{% endif %}tmpl.oid = {{tid}}::OID
+{% endif %}
+ORDER BY
+ tmpl.tmplname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..21d6f4df9c3e8f9c5355298c1ebdb807c1ddc63b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/schema.sql
@@ -0,0 +1,19 @@
+{# SCHEMA name FETCH statement #}
+{% if data.schema %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{data.schema}}::OID
+
+{% elif data.id %}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT JOIN pg_catalog.pg_ts_template ts
+ ON ts.tmplnamespace = nsp.oid
+WHERE
+ ts.oid = {{data.id}}::OID
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/sql.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/sql.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e06cc141c560f230087dc79f305a3e47bc0e336e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/sql.sql
@@ -0,0 +1,41 @@
+{# Reverse engineered sql for FTS TEMPLATE #}
+SELECT
+ pg_catalog.array_to_string(array_agg(sql), E'\n\n') as sql
+FROM
+ (
+ SELECT
+ E'-- Text Search Template: ' || pg_catalog.quote_ident(nspname) || E'.' || tmpl.tmplname ||
+ E'\n\n-- DROP TEXT SEARCH TEMPLATE ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(tmpl.tmplname) ||
+ E'\n\nCREATE TEXT SEARCH TEMPLATE ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(tmpl.tmplname) || E' (\n' ||
+ CASE
+ WHEN tmpl.tmplinit != '-'::regclass THEN E' INIT = ' || tmpl.tmplinit || E',\n'
+ ELSE '' END ||
+ E' LEXIZE = ' || tmpl.tmpllexize || E'\n);' ||
+ CASE
+ WHEN a.description IS NOT NULL THEN
+ E'\n\nCOMMENT ON TEXT SEARCH TEMPLATE ' || pg_catalog.quote_ident(nspname) || E'.' || pg_catalog.quote_ident(tmpl.tmplname) ||
+ E' IS ' || pg_catalog.quote_literal(description) || E';'
+ ELSE '' END as sql
+FROM
+ pg_catalog.pg_ts_template tmpl
+ LEFT JOIN (
+ SELECT
+ des.description as description,
+ des.objoid as descoid
+ FROM
+ pg_catalog.pg_description des
+ WHERE
+ des.objoid={{tid}}::OID AND des.classoid='pg_ts_template'::regclass
+ ) a ON (a.descoid = tmpl.oid)
+ LEFT JOIN (
+ SELECT
+ nspname,
+ nsp.oid as noid
+ FROM
+ pg_catalog.pg_namespace nsp
+ WHERE
+ oid = {{scid}}::OID
+ ) b ON (b.noid = tmpl.tmplnamespace)
+WHERE
+ tmpl.oid={{tid}}::OID
+) as c;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ff8c52c5055650b62d9e69d425dc02328c0c283e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/fts_templates/templates/fts_templates/sql/default/update.sql
@@ -0,0 +1,37 @@
+{# UPDATE statement for TEXT SEARCH TEMPLATE #}
+{% if data %}
+{% if data.name and data.name != o_data.name %}
+ALTER TEXT SEARCH TEMPLATE {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(o_data.name)}}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+
+{#in case of rename, use new fts template name #}
+{% if data.name and data.name != o_data.name %}
+{% set name = data.name %}
+{% else %}
+{% set name = o_data.name %}
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TEXT SEARCH TEMPLATE {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+{% endif %}
+{# Schema Diff SQL for FTS PARSER #}
+{% if data.tmplinit or data.tmpllexize %}
+-- WARNING:
+-- We have found the difference in either of INIT or LEXIZE,
+-- so we need to drop the existing template first and re-create it.
+DROP TEXT SEARCH TEMPLATE {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}};
+
+CREATE TEXT SEARCH TEMPLATE {{ conn|qtIdent(o_data.schema, name) }} (
+{% if data.tmplinit and data.tmplinit != '-'%}
+ INIT = {{data.tmplinit}},
+{% endif %}
+ LEXIZE = {% if data.tmpllexize is defined %}{{data.tmpllexize}}{% else %}{{o_data.tmpllexize}}{% endif %}
+
+);
+{% endif %}
+{% if 'description' in data and data.description != o_data.description %}
+COMMENT ON TEXT SEARCH TEMPLATE {{conn|qtIdent(o_data.schema)}}.{{conn|qtIdent(name)}}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e06124408fe8e5e5311671afd111019ad0b328b2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/__init__.py
@@ -0,0 +1,1988 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Functions/Procedures Node."""
+
+import re
+import sys
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule, DataTypeReader
+from pgadmin.browser.server_groups.servers.databases.utils import \
+ parse_sec_labels_from_db, parse_variables_from_db
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.browser.server_groups.servers.databases.schemas.functions.utils \
+ import format_arguments_from_db
+
+
+class FunctionModule(SchemaChildModule):
+ """
+ class FunctionModule(SchemaChildModule):
+
+ This class represents The Functions Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Functions Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Functions collection node.
+
+ * node_inode():
+ - Returns Functions node as leaf node.
+
+ * script_load()
+ - Load the module script for Functions, when schema node is
+ initialized.
+
+ * csssnippets()
+ - Returns a snippet of css.
+ """
+
+ _NODE_TYPE = 'function'
+ _COLLECTION_LABEL = gettext("Functions")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Function Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = None
+ self.max_ver = None
+ self.server_type = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate Functions collection node.
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=FunctionView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Functions, when the
+ schema node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css
+ """
+ snippets = []
+ snippets.extend(
+ super().csssnippets
+ )
+
+ return snippets
+
+
+blueprint = FunctionModule(__name__)
+
+
+class FunctionView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
+ """
+ class FunctionView(PGChildNodeView)
+
+ This class inherits PGChildNodeView to get the different routes for
+ the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Functions.
+
+ Methods:
+ -------
+ * validate_request(f):
+ - Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid):
+ - List the Functions.
+
+ * nodes(gid, sid, did, scid):
+ - Returns all the Functions to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, fnid):
+ - Returns the Functions properties.
+
+ * create(gid, sid, did, scid):
+ - Creates a new Functions object.
+
+ * update(gid, sid, did, scid, fnid):
+ - Updates the Functions object.
+
+ * delete(gid, sid, did, scid, fnid):
+ - Drops the Functions object.
+
+ * sql(gid, sid, did, scid, fnid):
+ - Returns the SQL for the Functions object.
+
+ * msql(gid, sid, did, scid, fnid=None):
+ - Returns the modified SQL.
+
+ * dependents(gid, sid, did, scid, fnid):
+ - Returns the dependents for the Functions object.
+
+ * dependencies(gid, sid, did, scid, fnid):
+ - Returns the dependencies for the Functions object.
+
+ * get_languages(gid, sid, did, scid, fnid=None):
+ - Returns languages.
+
+ * types(gid, sid, did, scid, fnid=None):
+ - Returns Data Types.
+
+ * select_sql(gid, sid, did, scid, fnid):
+ - Returns sql for Script
+
+ * exec_sql(gid, sid, did, scid, fnid):
+ - Returns sql for Script
+
+ * compare(**kwargs):
+ - This function will compare the function nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ BASE_TEMPLATE_PATH = 'functions/{0}/sql/#{1}#'
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'fnid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
+ 'get_languages': [{'get': 'get_languages'}, {'get': 'get_languages'}],
+ 'vopts': [{}, {'get': 'variable_options'}],
+ 'select_sql': [{'get': 'select_sql'}],
+ 'exec_sql': [{'get': 'exec_sql'}],
+ 'get_support_functions': [{'get': 'get_support_functions'},
+ {'get': 'get_support_functions'}]
+ })
+
+ keys_to_ignore = ['oid', 'proowner', 'typnsp', 'xmin', 'prokind',
+ 'proisagg', 'pronamespace', 'proargdefaults',
+ 'prorettype', 'proallargtypes', 'proacl', 'oid-2',
+ 'prolang']
+
+ @property
+ def required_args(self):
+ """
+ Returns Required arguments for functions node.
+ Where
+ Required Args:
+ name: Name of the Function
+ funcowner: Function Owner
+ pronamespace: Function Namespace
+ prorettypename: Function Return Type
+ lanname: Function Language Name
+ prosrc: Function Code
+ probin: Function Object File
+ """
+ return [
+ 'name',
+ 'funcowner',
+ 'pronamespace',
+ 'prorettypename',
+ 'lanname',
+ 'prosrc',
+ 'probin'
+ ]
+
+ @staticmethod
+ def _create_wrap_data(req, key, data):
+ """
+ This function is used to create data required by validate_request().
+ :param req:
+ :param key:
+ :param data:
+ :return:
+ """
+ list_params = []
+ if request.method == 'GET':
+ list_params = ['arguments', 'variables', 'proacl',
+ 'seclabels', 'acl', 'args']
+
+ if key in list_params and req[key] != '' and req[key] is not None:
+ # Coverts string into python list as expected.
+ data[key] = json.loads(req[key])
+ elif (key == 'proretset' or key == 'proisstrict' or
+ key == 'prosecdef' or key == 'proiswindow' or
+ key == 'proleakproof'):
+ if req[key] == 'true' or req[key] is True:
+ data[key] = True
+ else:
+ data[key] = False if (
+ req[key] == 'false' or req[key] is False) else ''
+ else:
+ data[key] = req[key]
+
+ @staticmethod
+ def _remove_parameters_for_c_lang(req, req_args):
+ """
+ This function is used to remove 'prosrc' from the required
+ arguments list if language is 'c'.
+ :param req:
+ :param req_args:
+ :return:
+ """
+ if req['lanname'] == 'c' and 'prosrc' in req_args:
+ req_args.remove('prosrc')
+
+ @staticmethod
+ def _get_request_data():
+ """
+ This function is used to get the request data.
+ :return:
+ """
+ if request.data:
+ req = json.loads(request.data)
+ else:
+ req = request.args or request.form
+ return req
+
+ def validate_request(f):
+ """
+ Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+ """
+
+ @wraps(f)
+ def wrap(self, **kwargs):
+ req = FunctionView._get_request_data()
+
+ if 'fnid' not in kwargs:
+ req_args = self.required_args
+ FunctionView._remove_parameters_for_c_lang(req, req_args)
+ for arg in req_args:
+ if (arg not in req or req[arg] == '') or \
+ (arg == 'probin' and req['lanname'] == 'c' and
+ (arg not in req or req[arg] == '')):
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ data = {}
+ for key in req:
+ FunctionView._create_wrap_data(req, key, data)
+
+ self.request = data
+ return f(self, **kwargs)
+
+ return wrap
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks the database connection status.
+ Attaches the connection object and template path to the class object.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+
+ # Get database connection
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.qtLiteral = driver.qtLiteral
+
+ # Set the template path for the SQL scripts
+ self.sql_template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.server_type, self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ List all the Functions.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ sql = render_template("/".join([self.sql_template_path,
+ self._NODE_SQL]),
+ scid=scid, conn=self.conn)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns all the Functions to generate the Nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ sql = render_template(
+ "/".join([self.sql_template_path, self._NODE_SQL]),
+ scid=scid,
+ fnid=fnid,
+ conn=self.conn
+ )
+ status, rset = self.conn.execute_2darray(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if fnid is not None:
+ if len(rset['rows']) == 0:
+ return gone(
+ gettext("Could not find the specified %s.").format(
+ self.node_type
+ )
+ )
+
+ row = rset['rows'][0]
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-" + self.node_type,
+ funcowner=row['funcowner'],
+ language=row['lanname'],
+ description=row['description']
+ )
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-" + self.node_type,
+ funcowner=row['funcowner'],
+ language=row['lanname'],
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns the Function properties.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ resp_data = self._fetch_properties(gid, sid, did, scid, fnid)
+ # Most probably this is due to error
+ if not isinstance(resp_data, dict):
+ return resp_data
+
+ if len(resp_data) == 0:
+ return gone(
+ gettext("Could not find the function node in the database.")
+ )
+
+ return ajax_response(
+ response=resp_data,
+ status=200
+ )
+
+ def _format_proacl_from_db(self, proacl):
+ """
+ Returns privileges.
+ Args:
+ proacl: Privileges Dict
+ """
+ privileges = []
+ for row in proacl:
+ priv = parse_priv_from_db(row)
+ privileges.append(priv)
+
+ return {"acl": privileges}
+
+ @check_precondition
+ def types(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns the Data Types.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ condition = "(typtype IN ('b', 'c', 'd', 'e', 'p', 'r') AND " \
+ "typname NOT IN ('any', 'trigger', 'language_handler', " \
+ "'event_trigger'))"
+ if not self.blueprint.show_system_objects:
+ condition += " AND nspname NOT LIKE E'pg\\\\_toast%' AND " \
+ "nspname NOT LIKE E'pg\\\\_temp%' AND "\
+ "nspname != 'information_schema'"
+
+ # Get Types
+ status, types = self.get_types(self.conn, condition, False, scid)
+
+ if not status:
+ return internal_server_error(errormsg=types)
+
+ return make_json_response(
+ data=types,
+ status=200
+ )
+
+ @check_precondition
+ def get_languages(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns the Languages list.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ res = []
+ try:
+ sql = render_template("/".join([self.sql_template_path,
+ 'get_languages.sql'])
+ )
+ status, rows = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ res = res + rows['rows']
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+ except Exception:
+ _, exc_value, _ = sys.exc_info()
+ return internal_server_error(errormsg=str(exc_value))
+
+ @check_precondition
+ def variable_options(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns the variables.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+
+ Returns:
+ This function will return list of variables available for
+ table spaces.
+ """
+ sql = render_template(
+ "/".join([self.sql_template_path, 'variables.sql'])
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ return make_json_response(
+ data=rset['rows'],
+ status=200
+ )
+
+ @check_precondition
+ @validate_request
+ def create(self, gid, sid, did, scid):
+ """
+ Create a new Function object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+
+ Returns:
+ Function object in json format.
+ """
+
+ # Get SQL to create Function
+ status, sql = self._get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=self.request,
+ allow_code_formatting=False)
+ if not status:
+ return internal_server_error(errormsg=sql)
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join(
+ [self.sql_template_path, self._OID_SQL]
+ ),
+ nspname=self.request['pronamespace'],
+ name=self.request['name'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ res = res['rows'][0]
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['oid'],
+ res['nsp'],
+ res['name'],
+ icon="icon-" + self.node_type,
+ language=res['lanname'],
+ funcowner=res['funcowner']
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, fnid=None, only_sql=False):
+ """
+ Drop the Function.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ if fnid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [fnid]}
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for fnid in data['ids']:
+ # Fetch Name and Schema Name to delete the Function.
+ sql = render_template("/".join([self.sql_template_path,
+ self._DELETE_SQL]), scid=scid,
+ fnid=fnid)
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified function could not be found.\n'
+ )
+ )
+
+ sql = render_template("/".join([self.sql_template_path,
+ self._DELETE_SQL]),
+ name=res['rows'][0]['name'],
+ func_args=res['rows'][0]['func_args'],
+ nspname=res['rows'][0]['nspname'],
+ cascade=cascade)
+ if only_sql:
+ return sql
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Function dropped.")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ @validate_request
+ def update(self, gid, sid, did, scid, fnid):
+ """
+ Update the Function.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ status, sql = self._get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=self.request, fnid=fnid,
+ allow_code_formatting=False)
+ if not status:
+ return internal_server_error(errormsg=sql)
+
+ if sql and sql.strip('\n') and sql.strip(' '):
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ resp_data = self._fetch_properties(gid, sid, did, scid, fnid)
+ # Most probably this is due to error
+ if not isinstance(resp_data, dict):
+ return resp_data
+
+ if self.node_type == 'procedure':
+ obj_name = resp_data['name_with_args']
+ elif self.node_type == 'function':
+ args = resp_data['proargs'] if resp_data['proargs'] else ''
+ obj_name = resp_data['name'] + '({0})'.format(args)
+ else:
+ obj_name = resp_data['name'] + '()'
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ fnid,
+ resp_data['pronamespace'],
+ obj_name,
+ icon="icon-" + self.node_type,
+ language=resp_data['lanname'],
+ funcowner=resp_data['funcowner'],
+ description=resp_data['description']
+ )
+ )
+ else:
+ return make_json_response(
+ success=1,
+ info="Nothing to update.",
+ data={
+ 'id': fnid,
+ 'scid': scid,
+ 'sid': sid,
+ 'gid': gid,
+ 'did': did
+ }
+ )
+
+ @staticmethod
+ def _check_argtype(args, args_without_name, a):
+ """
+ This function is used to check the arg type.
+ :param args:
+ :param args_without_name:
+ :param a:
+ :return:
+ """
+ if 'argtype' in a:
+ args += a['argtype']
+ args_without_name.append(a['argtype'])
+ return args, args_without_name
+
+ def _get_arguments(self, args_list, args, args_without_name):
+ """
+ This function is used to get the arguments.
+ :param args_list:
+ :param args:
+ :param args_without_name:
+ :return:
+ """
+ cnt = 1
+ for a in args_list:
+ if (
+ (
+ 'argmode' in a and a['argmode'] != 'OUT' and
+ a['argmode'] is not None
+ ) or 'argmode' not in a
+ ):
+ if 'argmode' in a:
+ args += a['argmode'] + " "
+ if (
+ 'argname' in a and a['argname'] != '' and
+ a['argname'] is not None
+ ):
+ args += self.qtIdent(
+ self.conn, a['argname']) + " "
+
+ args, args_without_name = FunctionView._check_argtype(
+ args,
+ args_without_name,
+ a
+ )
+
+ if cnt < len(args_list):
+ args += ', '
+ cnt += 1
+
+ def _parse_privilege_data(self, resp_data):
+ """
+ This function is used to parse the privilege data.
+ :param resp_data:
+ :return:
+ """
+ # Parse privilege data
+ if 'acl' in resp_data:
+ resp_data['acl'] = parse_priv_to_db(resp_data['acl'], ['X'])
+
+ # Check Revoke all for public
+ resp_data['revoke_all'] = self._set_revoke_all(
+ resp_data['acl'])
+
+ def _get_schema_name_from_oid(self, resp_data):
+ """
+ This function is used to get te schema name from OID.
+ :param resp_data:
+ :return:
+ """
+ if 'pronamespace' in resp_data:
+ resp_data['pronamespace'] = self._get_schema(
+ resp_data['pronamespace'])
+
+ def _get_function_definition(self, scid, fnid, resp_data, target_schema):
+
+ sql = render_template("/".join([self.sql_template_path,
+ self._GET_DEFINITION_SQL]
+ ), data=resp_data,
+ fnid=fnid, scid=scid)
+
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif target_schema:
+ res['rows'][0]['nspname'] = target_schema
+ resp_data['pronamespace'] = target_schema
+
+ # Add newline and tab before each argument to format
+ name_with_default_args = self.qtIdent(
+ self.conn,
+ res['rows'][0]['nspname'],
+ res['rows'][0]['proname']
+ ) + '(\n\t' + res['rows'][0]['func_args']. \
+ replace(', ', ',\n\t') + ')'
+
+ # Generate sql for "SQL panel"
+ # func_def is function signature with default arguments
+ # query_for - To distinguish the type of call
+ func_def = render_template("/".join([self.sql_template_path,
+ self._CREATE_SQL]),
+ data=resp_data, query_type="create",
+ func_def=name_with_default_args,
+ query_for="sql_panel",
+ add_replace_clause=True,
+ conn=self.conn
+ )
+
+ return func_def
+
+ def _get_procedure_definition(self, scid, fnid, resp_data, target_schema):
+
+ sql = render_template("/".join([self.sql_template_path,
+ self._GET_DEFINITION_SQL]
+ ), data=resp_data,
+ fnid=fnid, scid=scid)
+
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif target_schema:
+ res['rows'][0]['nspname'] = target_schema
+
+ # Add newline and tab before each argument to format
+ name_with_default_args = self.qtIdent(
+ self.conn,
+ res['rows'][0]['nspname'],
+ res['rows'][0]['proname']
+ ) + '(\n\t' + res['rows'][0]['func_args'].\
+ replace(', ', ',\n\t') + ')'
+
+ # Generate sql for "SQL panel"
+ # func_def is procedure signature with default arguments
+ # query_for - To distinguish the type of call
+ func_def = render_template("/".join([self.sql_template_path,
+ self._CREATE_SQL]),
+ data=resp_data, query_type="create",
+ func_def=name_with_default_args,
+ query_for="sql_panel",
+ conn=self.conn)
+
+ return func_def
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, fnid=None, **kwargs):
+ """
+ Returns the SQL for the Function object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ json_resp:
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ resp_data = self._fetch_properties(gid, sid, did, scid, fnid)
+ # Most probably this is due to error
+ if not isinstance(resp_data, dict):
+ return resp_data
+
+ # Fetch the function definition.
+ args = ''
+ args_without_name = []
+
+ args_list = []
+ vol_dict = {'v': 'VOLATILE', 's': 'STABLE', 'i': 'IMMUTABLE'}
+
+ if 'arguments' in resp_data and len(resp_data['arguments']) > 0:
+ args_list = resp_data['arguments']
+ resp_data['args'] = resp_data['arguments']
+
+ self._get_arguments(args_list, args, args_without_name)
+
+ resp_data['func_args'] = args.strip(' ')
+
+ resp_data['func_args_without'] = ', '.join(args_without_name)
+
+ self.reformat_prosrc_code(resp_data)
+
+ if self.node_type == 'procedure':
+ object_type = 'procedure'
+
+ if 'provolatile' in resp_data:
+ resp_data['provolatile'] = vol_dict.get(
+ resp_data['provolatile'], ''
+ )
+
+ # Get Schema Name from its OID.
+ self._get_schema_name_from_oid(resp_data)
+
+ # Parse privilege data
+ self._parse_privilege_data(resp_data)
+
+ func_def = self._get_procedure_definition(scid, fnid, resp_data,
+ target_schema)
+ else:
+ object_type = 'function'
+
+ # We are showing trigger functions under the trigger node.
+ # It may possible that trigger is in one schema and trigger
+ # function is in another schema, so to show the SQL we need to
+ # change the schema id i.e scid.
+ if self.node_type == 'trigger_function' and \
+ scid != resp_data['pronamespace']:
+ scid = resp_data['pronamespace']
+
+ # Get Schema Name from its OID.
+ self._get_schema_name_from_oid(resp_data)
+
+ # Parse privilege data
+ self._parse_privilege_data(resp_data)
+
+ func_def = self._get_function_definition(scid, fnid, resp_data,
+ target_schema)
+
+ # This is to check whether any exception occurred, if yes, then return
+ if not isinstance(func_def, str) and func_def.status_code is not None:
+ return func_def
+
+ sql_header = """-- {0}: {1}.{2}({3})\n\n""".format(
+ object_type.upper(), resp_data['pronamespace'],
+ resp_data['proname'],
+ resp_data['proargtypenames'].lstrip('(').rstrip(')'))
+ sql_header += """-- DROP {0} IF EXISTS {1}({2});\n\n""".format(
+ object_type.upper(), self.qtIdent(
+ self.conn, resp_data['pronamespace'], resp_data['proname']),
+ resp_data['proargtypenames'].lstrip('(').rstrip(')'))
+
+ pattern = '\n{2,}'
+ repl = '\n\n'
+ if not json_resp:
+ return re.sub(pattern, repl, func_def)
+
+ sql = sql_header + func_def
+ sql = re.sub(pattern, repl, sql)
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ @validate_request
+ def msql(self, gid, sid, did, scid, fnid=None):
+ """
+ Returns the modified SQL.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ Returns:
+ SQL statements to create/update the Domain.
+ """
+
+ status, sql = self._get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=self.request, fnid=fnid)
+
+ if not status:
+ return internal_server_error(errormsg=sql)
+
+ sql = re.sub('\n{2,}', '\n\n', sql)
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ @staticmethod
+ def _update_arguments_for_get_sql(data, old_data):
+ """
+ If Function Definition/Arguments are changed then merge old
+ Arguments with changed ones for Create/Replace Function SQL statement
+ :param data:
+ :param old_data:
+ :return:
+ """
+ if 'arguments' in data and len(data['arguments']) > 0:
+ for arg in data['arguments']['changed']:
+ for old_arg in old_data['arguments']:
+ if arg['argid'] == old_arg['argid']:
+ old_arg.update(arg)
+ break
+ data['arguments'] = old_data['arguments']
+ elif data['change_func']:
+ data['arguments'] = old_data['arguments']
+
+ @staticmethod
+ def _delete_variable_in_edit_mode(data, del_variables):
+ """
+ This function is used to create variables that marked for delete.
+ :param data:
+ :param del_variables:
+ :return:
+ """
+ if 'variables' in data and 'deleted' in data['variables']:
+ for v in data['variables']['deleted']:
+ del_variables[v['name']] = v['value']
+
+ @staticmethod
+ def _prepare_final_dict(data, old_data, chngd_variables, del_variables,
+ all_ids_dict):
+ """
+ This function is used to prepare the final dict.
+ :param data:
+ :param old_data:
+ :param chngd_variables:
+ :param del_variables:
+ :param all_ids_dict:
+ :return:
+ """
+ # In case of schema diff we don't want variables from
+ # old data
+ if not all_ids_dict['is_schema_diff']:
+ for v in old_data['variables']:
+ old_data['chngd_variables'][v['name']] = v['value']
+
+ # Prepare final dict of new and old variables
+ for name, val in old_data['chngd_variables'].items():
+ if (
+ name not in chngd_variables and
+ name not in del_variables
+ ):
+ chngd_variables[name] = val
+
+ # Prepare dict in [{'name': var_name, 'value': var_val},..]
+ # format
+ for name, val in chngd_variables.items():
+ data['merged_variables'].append({'name': name,
+ 'value': val})
+
+ @staticmethod
+ def _parser_privilege(data):
+ """
+ This function is used to parse the privilege data.
+ :param data:
+ :return:
+ """
+ if 'acl' in data:
+ for key in ['added', 'deleted', 'changed']:
+ if key in data['acl']:
+ data['acl'][key] = parse_priv_to_db(
+ data['acl'][key], ["X"])
+
+ @staticmethod
+ def _merge_variable_changes(data, chngd_variables):
+ """
+ This function is used to merge the changed variables.
+ :param data:
+ :param chngd_variables:
+ :return:
+ """
+ if 'variables' in data and 'changed' in data['variables']:
+ for v in data['variables']['changed']:
+ chngd_variables[v['name']] = v['value']
+
+ if 'variables' in data and 'added' in data['variables']:
+ for v in data['variables']['added']:
+ chngd_variables[v['name']] = v['value']
+
+ @staticmethod
+ def _merge_variables(data):
+ """
+ This function is used to prepare the merged variables.
+ :param data:
+ :return:
+ """
+ if 'variables' in data and 'changed' in data['variables']:
+ for v in data['variables']['changed']:
+ data['merged_variables'].append(v)
+
+ if 'variables' in data and 'added' in data['variables']:
+ for v in data['variables']['added']:
+ data['merged_variables'].append(v)
+
+ def _get_sql_for_edit_mode(self, data, parallel_dict, all_ids_dict,
+ vol_dict, allow_code_formatting=True):
+ """
+ This function is used to get the sql for edit mode.
+ :param data:
+ :param parallel_dict:
+ :param all_ids_dict:
+ :param vol_dict:
+ :return:
+ """
+ if 'proparallel' in data and data['proparallel']:
+ data['proparallel'] = parallel_dict[data['proparallel']]
+
+ # Fetch Old Data from database.
+ old_data = self._fetch_properties(all_ids_dict['gid'],
+ all_ids_dict['sid'],
+ all_ids_dict['did'],
+ all_ids_dict['scid'],
+ all_ids_dict['fnid'])
+ # Most probably this is due to error
+ if not isinstance(old_data, dict):
+ return False, gettext(
+ "Could not find the function in the database."
+ ), ''
+
+ # Get Schema Name
+ old_data['pronamespace'] = self._get_schema(
+ old_data['pronamespace']
+ )
+
+ if 'provolatile' in old_data and \
+ old_data['provolatile'] is not None:
+ old_data['provolatile'] = vol_dict[old_data['provolatile']]
+
+ if 'proparallel' in old_data and \
+ old_data['proparallel'] is not None:
+ old_data['proparallel'] = \
+ parallel_dict[old_data['proparallel']]
+
+ # If any of the below argument is changed,
+ # then CREATE OR REPLACE SQL statement should be called
+ fun_change_args = ['lanname', 'prosrc', 'probin', 'prosrc_c',
+ 'provolatile', 'proisstrict', 'prosecdef',
+ 'proparallel', 'procost', 'proleakproof',
+ 'arguments', 'prorows', 'prosupportfunc',
+ 'prorettypename']
+
+ data['change_func'] = False
+ for arg in fun_change_args:
+ if (arg == 'arguments' and arg in data and len(
+ data[arg]) > 0) or arg in data:
+ data['change_func'] = True
+
+ # If Function Definition/Arguments are changed then merge old
+ # Arguments with changed ones for Create/Replace Function
+ # SQL statement
+ FunctionView._update_arguments_for_get_sql(data, old_data)
+
+ # Parse Privileges
+ FunctionView._parser_privilege(data)
+
+ # Parse Variables
+ chngd_variables = {}
+ data['merged_variables'] = []
+ old_data['chngd_variables'] = {}
+ del_variables = {}
+
+ # If Function Definition/Arguments are changed then,
+ # Merge old, new (added, changed, deleted) variables,
+ # which will be used in the CREATE or REPLACE Function sql
+ # statement
+ if data['change_func']:
+ # Deleted Variables
+ FunctionView._delete_variable_in_edit_mode(data, del_variables)
+ FunctionView._merge_variable_changes(data, chngd_variables)
+
+ # Prepare final dict
+ FunctionView._prepare_final_dict(data, old_data, chngd_variables,
+ del_variables, all_ids_dict)
+ else:
+ FunctionView._merge_variables(data)
+
+ self._format_prosrc_for_pure_sql(data, False, old_data['lanname'])
+
+ if allow_code_formatting:
+ self.reformat_prosrc_code(data)
+
+ sql = render_template(
+ "/".join([self.sql_template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ return True, '', sql
+
+ def _format_prosrc_for_pure_sql(self, data, view_only=True, lanname='sql'):
+
+ if self.manager.sversion < 140000:
+ return
+
+ # no need to test whether function/procedure definition is pure sql
+ # or not, the parameter from 'is_pure_sql' is sufficient.
+ if view_only:
+ if 'is_pure_sql' in data and data['is_pure_sql'] is True:
+ data['prosrc'] = data['prosrc_sql']
+ if data['prosrc'].endswith(';') is False:
+ data['prosrc'] = ''.join((data['prosrc'], ';'))
+ else:
+ data['is_pure_sql'] = False
+ else:
+ # when function/procedure definition is changed, we need to find
+ # whether definition is of pure or have std sql definition.
+ if lanname == 'sql' and self._is_function_def_sql_standard(data):
+ data['is_pure_sql'] = True
+ if data['prosrc'].endswith(';') is False:
+ data['prosrc'] = ''.join((data['prosrc'], ';'))
+
+ def _get_sql(self, **kwargs):
+ """
+ Generates the SQL statements to create/update the Function.
+
+ Args:
+ kwargs:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ data = kwargs.get('data')
+ fnid = kwargs.get('fnid', None)
+ is_sql = kwargs.get('is_sql', False)
+ is_schema_diff = kwargs.get('is_schema_diff', False)
+ allow_code_formatting = kwargs.get('allow_code_formatting', True)
+
+ vol_dict = {'v': 'VOLATILE', 's': 'STABLE', 'i': 'IMMUTABLE'}
+ parallel_dict = {'u': 'UNSAFE', 's': 'SAFE', 'r': 'RESTRICTED'}
+
+ # Get Schema Name from its OID.
+ self._get_schema_name_from_oid(data)
+
+ if fnid is not None:
+ # Edit Mode
+ if 'provolatile' in data:
+ data['provolatile'] = vol_dict[data['provolatile']] \
+ if data['provolatile'] else ''
+
+ all_ids_dict = {
+ 'gid': gid,
+ 'sid': sid,
+ 'did': did,
+ 'scid': scid,
+ 'data': data,
+ 'fnid': fnid,
+ 'is_sql': is_sql,
+ 'is_schema_diff': is_schema_diff,
+ }
+ status, errmsg, sql = self._get_sql_for_edit_mode(
+ data, parallel_dict, all_ids_dict, vol_dict,
+ allow_code_formatting=allow_code_formatting)
+
+ if not status:
+ return False, errmsg
+
+ else:
+ # Parse Privileges
+ self._parse_privilege_data(data)
+
+ args = ''
+ args_without_name = []
+
+ args_list = []
+ if 'arguments' in data and len(data['arguments']) > 0:
+ args_list = data['arguments']
+ elif 'args' in data and len(data['args']) > 0:
+ args_list = data['args']
+
+ self._get_arguments(args_list, args, args_without_name)
+
+ data['func_args'] = args.strip(' ')
+
+ data['func_args_without'] = ', '.join(args_without_name)
+
+ self._format_prosrc_for_pure_sql(data, False)
+
+ if allow_code_formatting:
+ self.reformat_prosrc_code(data)
+
+ # Create mode
+ sql = render_template("/".join([self.sql_template_path,
+ self._CREATE_SQL]),
+ data=data, is_sql=is_sql, conn=self.conn)
+ return True, sql.strip('\n')
+
+ def _fetch_properties(self, gid, sid, did, scid, fnid=None):
+ """
+ Return Function Properties which will be used in properties,
+ msql function.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+
+ sql = render_template("/".join([self.sql_template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, fnid=fnid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the function in the database.")
+ )
+
+ resp_data = res['rows'][0]
+
+ # Get formatted Arguments
+ frmtd_params, frmtd_proargs = (
+ format_arguments_from_db(self.sql_template_path, self.conn,
+ resp_data))
+ resp_data.update(frmtd_params)
+ resp_data.update(frmtd_proargs)
+
+ # Fetch privileges
+ sql = render_template("/".join([self.sql_template_path,
+ self._ACL_SQL]),
+ fnid=fnid)
+ status, proaclres = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Get Formatted Privileges
+ resp_data.update(self._format_proacl_from_db(proaclres['rows']))
+
+ # Set System Functions Status
+ resp_data['sysfunc'] = False
+ if fnid <= self._DATABASE_LAST_SYSTEM_OID:
+ resp_data['sysfunc'] = True
+
+ # Set System Functions Status
+ resp_data['sysproc'] = False
+ if fnid <= self._DATABASE_LAST_SYSTEM_OID:
+ resp_data['sysproc'] = True
+
+ # Get formatted Security Labels
+ if 'seclabels' in resp_data:
+ resp_data.update(parse_sec_labels_from_db(resp_data['seclabels']))
+
+ # Get formatted Variable
+ resp_data.update(parse_variables_from_db([
+ {"setconfig": resp_data['proconfig']}]))
+
+ # Reset Volatile, Cost and Parallel parameter for Procedures
+ # if language is not 'edbspl' and database server version is
+ # greater than 10.
+ if self.manager.sversion >= 110000 \
+ and ('prokind' in resp_data and resp_data['prokind'] == 'p') \
+ and ('lanname' in resp_data and
+ resp_data['lanname'] != 'edbspl'):
+ resp_data['procost'] = None
+ resp_data['provolatile'] = None
+ resp_data['proparallel'] = None
+
+ self._format_prosrc_for_pure_sql(resp_data)
+
+ return resp_data
+
+ def _get_schema(self, scid):
+ """
+ Returns Schema Name from its OID.
+
+ Args:
+ scid: Schema Id
+ """
+ sql = render_template("/".join([self.sql_template_path,
+ 'get_schema.sql']), scid=scid)
+
+ status, schema_name = self.conn.execute_scalar(sql)
+
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ return schema_name
+
+ def _set_revoke_all(self, privileges):
+ """
+ Check whether the function requires REVOKE statement
+ for PUBLIC or not.
+ """
+ revoke_all = True if len(privileges) > 0 else False
+ for p in privileges:
+ if p['grantee'] == 'PUBLIC':
+ revoke_all = False
+ break
+
+ return revoke_all
+
+ @check_precondition
+ def get_support_functions(self, gid, sid, did, scid):
+ """
+ This function will return list of available support functions.
+ """
+ res = [{'label': '', 'value': ''}]
+
+ try:
+ sql = render_template(
+ "/".join([self.sql_template_path,
+ 'get_support_functions.sql']),
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['sfunctions'],
+ 'value': row['sfunctions']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, fnid):
+ """
+ This function get the dependents and return ajax response
+ for the Function node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ dependents_result = self.get_dependents(self.conn, fnid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, fnid):
+ """
+ This function get the dependencies and return ajax response
+ for the Function node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, fnid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def select_sql(self, gid, sid, did, scid, fnid):
+ """
+ This function returns sql for select script call.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ # Fetch the function definition.
+ sql = render_template("/".join([self.sql_template_path,
+ self._GET_DEFINITION_SQL]), fnid=fnid,
+ scid=scid)
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(gettext("The specified function could not be found."))
+
+ # Fetch only arguments
+ arg_string = res['rows'][0]['func_with_identity_arguments']
+ # Split argument by comma, Remove unwanted spaces and,
+ # format argument like "\n\t "
+ args = ','.join(
+ ['\n\t<' + arg.strip(' ') + '>' for arg in arg_string.split(',')]
+ ) + '\n' if len(arg_string) > 0 else ''
+
+ name = self.qtIdent(
+ self.conn, res['rows'][0]['nspname'],
+ res['rows'][0]['proname']
+ ) + '(' + args + ')'
+
+ sql = "SELECT {0}".format(name)
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def exec_sql(self, gid, sid, did, scid, fnid):
+ """
+ This function returns sql for exec script call.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ resp_data = self._fetch_properties(gid, sid, did, scid, fnid)
+ # Most probably this is due to error
+ if not isinstance(resp_data, dict):
+ return resp_data
+
+ # Fetch the schema name from OID
+ if 'pronamespace' in resp_data:
+ resp_data['pronamespace'] = self._get_schema(
+ resp_data['pronamespace']
+ )
+
+ # Fetch only arguments
+ arg_string = resp_data['proargs']
+ # Split argument by comma, Remove unwanted spaces and,
+ # format argument like "\n\t "
+ args = ','.join(
+ ['\n\t<' + arg.strip(' ') + '>' for arg in arg_string.split(',')]
+ ) + '\n' if len(arg_string) > 0 else ''
+
+ name = self.qtIdent(
+ self.conn, resp_data['pronamespace'],
+ resp_data['proname']
+ ) + '(' + args + ')'
+
+ if self.manager.server_type == 'pg':
+ sql = "CALL {0}".format(name)
+ else:
+ sql = "EXEC {0}".format(name)
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, fnid=None):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Function/Procedure/Trigger Function Id
+
+ Returns the statistics for a particular object if fnid is specified
+ """
+
+ if fnid is not None:
+ sql = 'stats.sql'
+ schema_name = None
+ else:
+ sql = 'coll_stats.sql'
+ # Get schema name
+ status, schema_name = self.conn.execute_scalar(
+ render_template(
+ 'schemas/pg/#{0}#/sql/get_name.sql'.format(
+ self.manager.version),
+ scid=scid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.sql_template_path, sql]),
+ conn=self.conn, fnid=fnid,
+ scid=scid, schema_name=schema_name
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ _, sql = self._get_sql(gid=gid, sid=sid, did=did, scid=scid,
+ data=data, fnid=oid, is_sql=False,
+ is_schema_diff=True,
+ allow_code_formatting=False)
+ # Check if return type is changed then we need to drop the
+ # function first and then recreate it.
+ if 'prorettypename' in data:
+ drop_fun_sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, fnid=oid, only_sql=True)
+ sql = drop_fun_sql + '\n' + sql
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, fnid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, fnid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, fnid=oid,
+ json_resp=False)
+ return sql
+
+ def reformat_prosrc_code(self, data):
+ """
+ :param data:
+ :return:
+ """
+ if 'prosrc' in data and data['prosrc'] is not None:
+
+ is_prc_version_lesser_than_11 = \
+ self.node_type == 'procedure' and\
+ self.manager.sversion <= 110000
+
+ if not is_prc_version_lesser_than_11:
+ if data['prosrc'].startswith('\n') is False:
+ data['prosrc'] = ''.join(
+ ('\n', data['prosrc']))
+
+ if data['prosrc'].endswith('\n') is False:
+ data['prosrc'] = ''.join(
+ (data['prosrc'], '\n'))
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, oid=None):
+ """
+ This function will fetch the list of all the functions for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ server_type = self.manager.server_type
+ server_version = self.manager.sversion
+
+ if server_type == 'pg' and self.blueprint.min_ver is not None and \
+ server_version < self.blueprint.min_ver:
+ return res
+ if server_type == 'ppas' and self.blueprint.min_ppasver is not None \
+ and server_version < self.blueprint.min_ppasver:
+ return res
+
+ if not oid:
+ sql = render_template("/".join([self.sql_template_path,
+ self._NODE_SQL]), scid=scid,
+ schema_diff=True, conn=self.conn)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ data = self._fetch_properties(0, sid, did, scid, row['oid'])
+ if isinstance(data, dict):
+ res[row['name']] = data
+ else:
+ data = self._fetch_properties(0, sid, did, scid, oid)
+ res = data
+
+ return res
+
+ @staticmethod
+ def _is_function_def_sql_standard(resp_data):
+
+ """
+ This function is responsible for checking the sql to determine
+ whether it is as per SQL-standard or not. In fact, the function
+ is mainly utilised for the sql language with the newly added
+ ATOMIC in the version v14 of Postgres for functions & procedures
+ respectively.
+
+ :param resp_data:
+ :return: boolean
+ """
+ # if language is other than 'sql', return False
+ if 'lanname' in resp_data and resp_data['lanname'] != 'sql':
+ return False
+
+ # invalid regex, these combination should not be present in the sql
+ invalid_match = [r"^.*(?:\'|\")?.*(?=.*?atomic).*(?:\'|\").*$",
+ r"^.*(?:\"|\')(?=.*(atomic)).*$"]
+
+ # valid regex, these combination a must in definition to detect a
+ # standard sql or pure sql
+ valid_match = [
+ r"(?=.*begin)(.+?(\n)+)(?=.*atomic)|(?=.*begin)(?=.*atomic)",
+ r"(?=return)"
+ ]
+
+ is_func_def_sql_std = False
+
+ if 'prosrc' in resp_data and resp_data['prosrc'] is not None \
+ and resp_data['prosrc'] != '':
+
+ prosrc = str(resp_data['prosrc']).lower().strip('\n').strip('\t')
+
+ for invalid in invalid_match:
+ for match in enumerate(
+ re.finditer(invalid, prosrc, re.MULTILINE), start=1):
+ if match:
+ return is_func_def_sql_std
+
+ for valid in valid_match:
+ for match in enumerate(
+ re.finditer(valid, prosrc, re.MULTILINE), start=1):
+ if match:
+ is_func_def_sql_std = True
+ return is_func_def_sql_std
+
+ return is_func_def_sql_std
+
+
+SchemaDiffRegistry(blueprint.node_type, FunctionView)
+FunctionView.register_node_view(blueprint)
+
+
+class ProcedureModule(SchemaChildModule):
+ """
+ class ProcedureModule(SchemaChildModule):
+
+ This class represents The Procedures Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Procedures Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Procedures collection node.
+
+ * node_inode():
+ - Returns Procedures node as leaf node.
+
+ * script_load()
+ - Load the module script for Procedures, when schema node is
+ initialized.
+
+ """
+
+ _NODE_TYPE = 'procedure'
+ _COLLECTION_LABEL = gettext("Procedures")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Procedure Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = 110000
+ self.max_ver = None
+ self.min_ppasver = 90100
+ self.server_type = ['pg', 'ppas']
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate Procedures collection node.
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=ProcedureView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Procedures, when the
+ database node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+
+procedure_blueprint = ProcedureModule(__name__)
+
+
+class ProcedureView(FunctionView):
+ node_type = procedure_blueprint.node_type
+ BASE_TEMPLATE_PATH = 'procedures/{0}/sql/#{1}#'
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Function Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ @property
+ def required_args(self):
+ """
+ Returns Required arguments for procedures node.
+ Where
+ Required Args:
+ name: Name of the Function
+ pronamespace: Function Namespace
+ lanname: Function Language Name
+ prosrc: Function Code
+ """
+ return ['name',
+ 'pronamespace',
+ 'lanname',
+ 'prosrc']
+
+
+SchemaDiffRegistry(procedure_blueprint.node_type, ProcedureView)
+ProcedureView.register_node_view(procedure_blueprint)
+
+
+class TriggerFunctionModule(SchemaChildModule):
+ """
+ class TriggerFunctionModule(SchemaChildModule):
+
+ This class represents The Trigger function Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Trigger function Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Trigger function collection node.
+
+ * node_inode():
+ - Returns Trigger function node as leaf node.
+
+ * script_load()
+ - Load the module script for Trigger function, when schema node is
+ initialized.
+
+ """
+
+ _NODE_TYPE = 'trigger_function'
+ _COLLECTION_LABEL = gettext("Trigger Functions")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Trigger function Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = 90100
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate Trigger function collection node.
+ """
+ if self.has_nodes(
+ sid, did, scid,
+ base_template_path=TriggerFunctionView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Trigger function, when the
+ schema node is initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+
+trigger_function_blueprint = TriggerFunctionModule(__name__)
+
+
+class TriggerFunctionView(FunctionView):
+ node_type = trigger_function_blueprint.node_type
+ BASE_TEMPLATE_PATH = 'trigger_functions/{0}/sql/#{1}#'
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Function Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ @property
+ def required_args(self):
+ """
+ Returns Required arguments for trigger function node.
+ Where
+ Required Args:
+ name: Name of the Trigger function
+ pronamespace: Trigger function Namespace
+ lanname: Trigger function Language Name
+ prosrc: Trigger function Code
+ """
+ return ['name',
+ 'pronamespace',
+ 'lanname',
+ 'prosrc']
+
+
+SchemaDiffRegistry(trigger_function_blueprint.node_type, TriggerFunctionView)
+TriggerFunctionView.register_node_view(trigger_function_blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/css/function.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/css/function.css
new file mode 100644
index 0000000000000000000000000000000000000000..16b2e71987106c57a2ba59e1f8aaa3b2df9a8eb3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/css/function.css
@@ -0,0 +1,3 @@
+.functions_code {
+ height: 130px !important;
+}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-function.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-function.svg
new file mode 100644
index 0000000000000000000000000000000000000000..e41b6cfbc99da90bd6c12b18fa1b60c9ecd393ed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-function.svg
@@ -0,0 +1 @@
+coll-function
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-procedure.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-procedure.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d2c684753371d22237a0c3bd5936219099e96e69
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-procedure.svg
@@ -0,0 +1 @@
+coll-procedure
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-trigger_function.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-trigger_function.svg
new file mode 100644
index 0000000000000000000000000000000000000000..6a57f0d2c9bc5b1d50e7ff0da3114168e8780c66
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/coll-trigger_function.svg
@@ -0,0 +1 @@
+coll-trigger_function
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/function.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/function.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3002261ef28e503f671ff9592e214b8f27e5554a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/function.svg
@@ -0,0 +1 @@
+function
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/procedure.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/procedure.svg
new file mode 100644
index 0000000000000000000000000000000000000000..6a58d4320ef420f5b0e274a0c321967939322ccc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/procedure.svg
@@ -0,0 +1 @@
+procedure
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/trigger_function.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/trigger_function.svg
new file mode 100644
index 0000000000000000000000000000000000000000..0c7b7c3c1bb40e58598449ab69640d26f72b6606
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/img/trigger_function.svg
@@ -0,0 +1 @@
+trigger_function
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js
new file mode 100644
index 0000000000000000000000000000000000000000..23c1c4459a5959db3c15cc9957ba613f1fab5cd1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.js
@@ -0,0 +1,109 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName, getNodeListById} from '../../../../../../../static/js/node_ajax';
+import FunctionSchema from './function.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import { getNodeVariableSchema } from '../../../../../static/js/variable.ui';
+
+/* Create and Register Function Collection and Node. */
+define('pgadmin.node.function', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-function']) {
+ pgBrowser.Nodes['coll-function'] =
+ pgBrowser.Collection.extend({
+ node: 'function',
+ label: gettext('Functions'),
+ type: 'coll-function',
+ columns: ['name', 'funcowner', 'description'],
+ hasStatistics: true,
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+ if (!pgBrowser.Nodes['function']) {
+
+ pgBrowser.Nodes['function'] = schemaChild.SchemaChildNode.extend({
+ type: 'function',
+ sqlAlterHelp: 'sql-alterfunction.html',
+ sqlCreateHelp: 'sql-createfunction.html',
+ dialogHelp: url_for('help.static', {'filename': 'function_dialog.html'}),
+ label: gettext('Function'),
+ collection_type: 'coll-function',
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.md + 'px',
+ hasStatistics: true,
+ hasScriptTypes: ['create', 'select'],
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_function_on_coll', node: 'coll-function', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Function...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_function', node: 'function', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Function...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_function', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Function...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },
+ ]);
+
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new FunctionSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ ()=>getNodeVariableSchema(this, treeNodeInfo, itemNodeData, false, false),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }
+ ),
+ getTypes: ()=>getNodeAjaxOptions('get_types', this, treeNodeInfo, itemNodeData),
+ getLanguage: ()=>getNodeAjaxOptions('get_languages', this, treeNodeInfo, itemNodeData),
+ getSupportFunctions: ()=>getNodeAjaxOptions('get_support_functions', this, treeNodeInfo, itemNodeData, {
+ cacheNode: 'function'
+ }),
+
+ },
+ {
+ node_info: treeNodeInfo,
+ },
+ {
+ type: pgBrowser.Nodes['function'].type,
+ },
+ {
+ funcowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ pronamespace: treeNodeInfo.schema ? treeNodeInfo.schema._id : null,
+ lanname: 'sql',
+ }
+ );
+ },
+ });
+ }
+ return pgBrowser.Nodes['function'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..2168d5b7c1a333bb7a99c927d6d327b388acd20e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/function.ui.js
@@ -0,0 +1,461 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import { isEmptyString } from 'sources/validators';
+import _ from 'lodash';
+
+export class DefaultArgumentSchema extends BaseUISchema {
+ constructor(node_info, getTypes) {
+ super();
+ this.node_info = node_info;
+ this.getTypes = getTypes;
+ this.type_options = {};
+ }
+ setTypeOptions(options) {
+ options.forEach((option)=>{
+ this.type_options[option.value] = {
+ ...option,
+ };
+ });
+ }
+
+ get baseFields() {
+ return[{
+ id: 'argid', visible: false, type: 'text',
+ mode: ['properties', 'edit','create'],
+ },{
+ id: 'argtype', label: gettext('Data type'),
+ options: this.getTypes,
+ type: 'text',
+ cell: ()=>({
+ cell: 'select', options: this.getTypes,
+ optionsLoaded: (options)=>{this.setTypeOptions(options);},
+ controlProps: {
+ allowClear: false,
+ }
+ }),
+ editable: this.isEditable, first_empty: true,
+ },{
+ id: 'argmode', label: gettext('Mode'),
+ type: 'text',
+ cell: ()=>({
+ cell: 'select',
+ options:[
+ {'label': 'IN', 'value': 'IN'},
+ {'label': 'OUT', 'value': 'OUT'},
+ {'label': 'INOUT', 'value': 'INOUT'},
+ {'label': 'VARIADIC', 'value': 'VARIADIC'},
+ ],
+ optionsLoaded: (options)=>{this.setTypeOptions(options);},
+ controlProps: {
+ allowClear: false,
+ }
+ }),
+ editable: this.isEditable,
+ },{
+ id: 'argname', label: gettext('Argument name'), type: 'text',
+ editable: this.isInCatalog, cell: ()=>({cell: 'text'})
+ },{
+ id: 'argdefval', label: gettext('Default'), type: 'text',
+ cell: ()=>({cell: 'text'}), editable: this.isInCatalog,
+ }];
+ }
+
+ isEditable() {
+ let node_info = this.node_info;
+ if(node_info && 'catalog' in node_info) {
+ return false;
+ }
+ return _.isUndefined(this.isNew) ? true : this.isNew();
+ }
+ isInCatalog(state){
+ let node_info = this.node_info;
+ if(node_info && 'catalog' in node_info) {
+ return false;
+ }
+ // Below will disable default value cell if argument mode is 'INOUT' or 'OUT' as
+ // user cannot set default value for out parameters.
+ return !(!_.isUndefined(state.argmode) && !_.isUndefined(state.name) &&
+ state.name == 'argdefval' &&
+ (state.argmode == 'INOUT' || state.argmode == 'OUT'));
+ }
+}
+
+export default class FunctionSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, getNodeVariableSchema, fieldOptions={}, node_info={}, type='function', initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ xmin: undefined,
+ funcowner: undefined,
+ pronamespace: undefined,
+ description: undefined,
+ pronargs: undefined, /* Argument Count */
+ proargs: undefined, /* Arguments */
+ proargtypenames: undefined, /* Argument Signature */
+ prorettypename: undefined, /* Return Type */
+ lanname: undefined, /* Language Name in which function is being written */
+ provolatile: undefined, /* Volatility */
+ proretset: undefined, /* Return Set */
+ proisstrict: undefined,
+ prosecdef: undefined, /* Security of definer */
+ proiswindow: undefined, /* Window Function ? */
+ proparallel: undefined, /* Parallel mode */
+ procost: undefined, /* Estimated execution Cost */
+ prorows: 0, /* Estimated number of rows */
+ proleakproof: undefined,
+ prosupportfunc: undefined, /* Support function */
+ arguments: [],
+ prosrc: undefined,
+ prosrc_c: undefined,
+ probin: '$libdir/',
+ options: [],
+ variables: [],
+ proacl: undefined,
+ seclabels: [],
+ acl: [],
+ sysfunc: undefined,
+ sysproc: undefined,
+ customreturn: false,
+ ...initValues
+ });
+
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.getNodeVariableSchema = getNodeVariableSchema;
+ this.node_info = node_info;
+ this.type = type.type;
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ getTypes: [],
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ isVisible(state) {
+ if(this.type !== 'procedure'){
+ return !state.sysproc;
+ }else{
+ if (state.sysfunc) {
+ return false;
+ } else if (state.sysproc) {
+ return true;
+ }
+
+ return false;
+ }
+ }
+
+ isGreaterThan95(state){
+ if (
+ this.node_info['node_info'].server.version < 90500 ||
+ this.node_info['node_info']['server'].server_type != 'ppas' ||
+ state.lanname != 'edbspl'
+ ) {
+ state.provolatile = null;
+ state.proisstrict = false;
+ state.procost = null;
+ state.proleakproof = false;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ isGreaterThan96(state){
+ if (
+ this.node_info['node_info'].server.version < 90600 ||
+ this.node_info['node_info']['server'].server_type != 'ppas' ||
+ state.lanname != 'edbspl'
+ ) {
+ state.proparallel = null;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+
+ isReadonly() {
+ return !this.isNew();
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ disabled: obj.inCatalog(),
+ noEmpty: true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'funcowner', label: gettext('Owner'), cell: 'string',
+ options: this.fieldOptions.role, type: 'select',
+ disabled: (state) => {
+ if (this.type !== 'procedure') {
+ obj.inCatalog(state);
+ } else {
+ obj.isGreaterThan95(state);
+ }
+ },
+ noEmpty: true,
+ },{
+ id: 'pronamespace', label: gettext('Schema'), cell: 'string',
+ type: 'select', disabled: obj.inCatalog(),
+ mode: ['create', 'edit'],
+ controlProps: {
+ allowClear: false,
+ first_empty: false,
+ },
+ options: obj.fieldOptions.schema, noEmpty: true,
+ },{
+ id: 'sysfunc', label: gettext('System function?'),
+ cell:'boolean', type: 'switch',
+ mode: ['properties'], visible: obj.isVisible,
+ },{
+ id: 'sysproc', label: gettext('System procedure?'),
+ cell:'boolean', type: 'switch',
+ mode: ['properties'], visible: () => {
+ return this.type === 'procedure';
+ },
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', disabled: obj.inCatalog(),
+ },{
+ id: 'pronargs', label: gettext('Argument count'), cell: 'string',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'proargs', label: gettext('Arguments'), cell: 'string',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'proargtypenames', label: gettext('Signature arguments'), cell:
+ 'string', type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'customreturn', label: gettext('Custom return type?'), type: 'switch',
+ mode: ['create'], group: gettext('Definition'), readonly: obj.isReadonly,
+ visible: obj.isVisible,
+ },{
+ id: 'prorettypename', label: gettext('Return type'), cell: 'string',
+ type: state => {
+ if(state.customreturn) {
+ return {
+ type: 'text',
+ };
+ } else {
+ return {
+ type: 'select',
+ options: this.fieldOptions.getTypes,
+ };
+ }
+ }, group: gettext('Definition'), deps:['customreturn'],
+ readonly: obj.isReadonly, first_empty: true,
+ mode: ['create'], visible: obj.isVisible,
+ depChange: (state, source) => {
+ if(source[0] === 'customreturn') {
+ return {
+ prorettypename: undefined
+ };
+ }
+ },
+ },{
+ id: 'prorettypename', label: gettext('Return type'), cell: 'string',
+ type: 'text', group: gettext('Definition'),
+ mode: ['properties', 'edit'], readonly: obj.isReadonly, visible: obj.isVisible,
+ },{
+ id: 'lanname', label: gettext('Language'), cell: 'string', noEmpty: true,
+ options: this.fieldOptions.getLanguage, type: 'select', group: gettext('Definition'),
+ disabled: function() {
+ if(this.type === 'procedure'){
+ return this.node_info['node_info'].server.version < 110000;
+ }
+
+ return this.node_info && 'catalog' in this.node_info;
+ }
+ },
+ {
+ id: 'probin', label: gettext('Object file'), cell: 'string',
+ type: 'text', group: gettext('Definition'), deps: ['lanname'], visible:
+ function(state) {
+ return state.lanname == 'c';
+ }, disabled: obj.inCatalog(),
+ },{
+ id: 'prosrc_c', label: gettext('Link symbol'), cell: 'string',
+ type: 'text', group: gettext('Definition'), deps: ['lanname'], visible:
+ function(state) {
+ return state.lanname == 'c';
+ }, disabled: obj.inCatalog(),
+ },
+ {
+ id: 'arguments', label: gettext('Arguments'), cell: 'string',
+ group: gettext('Definition'), type: 'collection', canAdd: function(){
+ return obj.isNew();
+ },
+ canDelete: true, mode: ['create', 'edit'],
+ columns: ['argtype', 'argmode', 'argname', 'argdefval'],
+ schema : new DefaultArgumentSchema(this.node_info, this.fieldOptions.getTypes),
+ disabled: obj.inCatalog(),
+ canDeleteRow: function() {
+ return obj.isNew();
+ },
+ },{
+ id: 'prosrc', label: gettext('Code'), cell: 'text',
+ type: 'sql', mode: ['properties', 'create', 'edit'],
+ group: gettext('Code'), deps: ['lanname'],
+ isFullTab: true,
+ visible: function(state) {
+ return state.lanname !== 'c';
+ }, disabled: obj.inCatalog(),
+ },{
+ id: 'provolatile', label: gettext('Volatility'), cell: 'text',
+ type: 'select', group: gettext('Options'),
+ deps: ['lanname'],
+ options:[
+ {'label': 'VOLATILE', 'value': 'v'},
+ {'label': 'STABLE', 'value': 's'},
+ {'label': 'IMMUTABLE', 'value': 'i'},
+ ], disabled: (this.type !== 'procedure') ? obj.inCatalog() : obj.isGreaterThan95,
+ controlProps: {allowClear: false},
+ },{
+ id: 'proretset', label: gettext('Returns a set?'), type: 'switch',
+ disabled: ()=>{return !obj.isNew();}, group: gettext('Options'),
+ visible: obj.isVisible, readonly: obj.isReadonly,
+ },{
+ id: 'proisstrict', label: gettext('Strict?'), type: 'switch',
+ group: gettext('Options'), disabled: obj.inCatalog(),
+ deps: ['lanname'],
+ },{
+ id: 'prosecdef', label: gettext('Security of definer?'),
+ group: gettext('Options'), type: 'switch',
+ disabled: (this.type !== 'procedure') ? obj.inCatalog(): ()=>{
+ return obj.node_info['node_info'].server.version < 90500;
+ },
+ },{
+ id: 'proiswindow', label: gettext('Window?'),
+ group: gettext('Options'), cell:'boolean', type: 'switch',
+ disabled: ()=>{return !obj.isNew();}, visible: obj.isVisible, readonly: obj.isReadonly,
+ },{
+ id: 'proparallel', label: gettext('Parallel'), cell: 'string',
+ type: 'select', group: gettext('Options'),
+ deps: ['lanname'],
+ options:[
+ {'label': 'UNSAFE', 'value': 'u'},
+ {'label': 'RESTRICTED', 'value': 'r'},
+ {'label': 'SAFE', 'value': 's'},
+ ],
+ disabled: (this.type !== 'procedure') ? obj.inCatalog(): obj.isGreaterThan96,
+ min_version: 90600,
+ controlProps: {allowClear: false},
+ },{
+ id: 'procost', label: gettext('Estimated cost'), group: gettext('Options'),
+ cell:'string', type: 'text', deps: ['lanname'],
+ disabled: (this.type !== 'procedure') ? obj.isDisabled: obj.isGreaterThan95,
+ },{
+ id: 'prorows', label: gettext('Estimated rows'), type: 'text',
+ deps: ['proretset'], visible: obj.isVisible,
+ readonly: (state) => {
+ let isReadonly = true;
+ if(state.proretset) {
+ isReadonly = false;
+ }
+ return isReadonly;
+ },
+ group: gettext('Options'),
+ },{
+ id: 'proleakproof', label: gettext('Leak proof?'),
+ group: gettext('Options'), cell:'boolean', type: 'switch', min_version: 90200,
+ disabled: (this.type !== 'procedure') ? obj.inCatalog(): obj.isGreaterThan95,
+ deps: ['lanname'],
+ },{
+ id: 'prosupportfunc', label: gettext('Support function'),
+ type: 'select',
+ disabled: ()=>{
+ if (obj.node_info && 'catalog' in obj.node_info) {
+ return true;
+ }
+
+ return !(obj.node_info['node_info'].server.user.is_superuser);
+ },
+ group: gettext('Options'), visible: obj.isVisible,
+ options: this.fieldOptions.getSupportFunctions, min_version: 120000,
+ },{
+ id: 'proacl', label: gettext('Privileges'), type: 'text',
+ mode: ['properties'], group: gettext('Security'),
+ },
+ {
+ id: 'variables', label: '', type: 'collection',
+ group: gettext('Parameters'),
+ schema: this.getNodeVariableSchema(),
+ mode: ['edit', 'create'], canAdd: true, canEdit: false,
+ canDelete: true,
+ },
+ {
+ id: 'acl', label: gettext('Privileges'), editable: false,
+ schema: this.getPrivilegeRoleSchema(['X']),
+ uniqueCol : ['grantee', 'grantor'], type: 'collection',
+ group: 'Security', mode: ['edit', 'create'], canAdd: true,
+ canDelete: true,
+ disabled: obj.inCatalog(),
+ },{
+ id: 'seclabels', label: gettext('Security labels'), canAdd: true,
+ schema: new SecLabelSchema(), type: 'collection',
+ min_version: 90100, group: 'Security', mode: ['edit', 'create'],
+ canEdit: false, canDelete: true, uniqueCol : ['provider'],
+ disabled: obj.inCatalog(),
+ visible: function() {
+ return this.node_info && this.type !== 'procedure';
+ },
+ },
+ ];
+ }
+ validate(state, setError) {
+ let errmsg = null;
+ if (this.type !== 'procedure' &&(isEmptyString(state.prorettypename))) {
+ errmsg = gettext('Return type cannot be empty.');
+ setError('prorettypename', errmsg);
+ return true;
+ } else {
+ setError('prorettypename', null);
+ }
+
+ if ((String(state.lanname) == 'c')) {
+ if (isEmptyString(state.probin)){
+ errmsg = gettext('Object File cannot be empty.');
+ setError('probin', errmsg);
+ return true;
+ }else {
+ setError('probin', null);
+ }
+
+ if (isEmptyString(state.prosrc_c)) {
+ errmsg = gettext('Link Symbol cannot be empty.');
+ setError('prosrc_c', errmsg);
+ return true;
+ }else {
+ setError('prosrc_c', null);
+ }
+
+ }else if (isEmptyString(state.prosrc)) {
+ /* code validation*/
+ errmsg = gettext('Code cannot be empty.');
+ setError('prosrc', errmsg);
+ return true;
+ } else {
+ setError('prosrc', null);
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/procedure.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/procedure.js
new file mode 100644
index 0000000000000000000000000000000000000000..a31ff6479d3acb1a06732fa95150dbeefcde1add
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/procedure.js
@@ -0,0 +1,128 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName, getNodeListById} from '../../../../../../../static/js/node_ajax';
+import FunctionSchema from './function.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import { getNodeVariableSchema } from '../../../../../static/js/variable.ui';
+
+/* Create and Register Procedure Collection and Node. */
+define('pgadmin.node.procedure', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.node.schema.dir/child',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode) {
+
+ if (!pgBrowser.Nodes['coll-procedure']) {
+ pgAdmin.Browser.Nodes['coll-procedure'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'procedure',
+ label: gettext('Procedures'),
+ type: 'coll-procedure',
+ columns: ['name', 'funcowner', 'description'],
+ hasStatistics: true,
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Inherit Functions Node
+ if (!pgBrowser.Nodes['procedure']) {
+ pgAdmin.Browser.Nodes['procedure'] = schemaChild.SchemaChildNode.extend({
+ type: 'procedure',
+ sqlAlterHelp: 'sql-alterprocedure.html',
+ sqlCreateHelp: 'sql-createprocedure.html',
+ dialogHelp: url_for('help.static', {'filename': 'procedure_dialog.html'}),
+ label: gettext('Procedure'),
+ collection_type: 'coll-procedure',
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ hasScriptTypes: ['create', 'exec'],
+ width: pgBrowser.stdW.md + 'px',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.proc_initialized)
+ return;
+
+ this.proc_initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_procedure_on_coll', node: 'coll-procedure', module:
+ this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Procedure...'),
+ data: {action: 'create', check: false}, enable: 'canCreateProc',
+ },{
+ name: 'create_procedure', node: 'procedure', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Procedure...'),
+ data: {action: 'create', check: true}, enable: 'canCreateProc',
+ },{
+ name: 'create_procedure', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Procedure...'),
+ data: {action: 'create', check: true}, enable: 'canCreateProc',
+ },
+ ]);
+ },
+ canCreateProc: function(itemData, item) {
+ let node_hierarchy = pgBrowser.tree.getTreeNodeHierarchy(item);
+
+ // Do not provide Create option in catalog
+ if ('catalog' in node_hierarchy)
+ return false;
+
+ // Procedures supported only in PPAS and PG >= 11
+ return (
+ 'server' in node_hierarchy && (
+ node_hierarchy['server'].server_type == 'ppas' ||
+ (node_hierarchy['server'].server_type == 'pg' &&
+ node_hierarchy['server'].version >= 110000)
+ )
+ );
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new FunctionSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ ()=>getNodeVariableSchema(this, treeNodeInfo, itemNodeData, false, false),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }
+ ),
+ getTypes: ()=>getNodeAjaxOptions('get_types', this, treeNodeInfo, itemNodeData),
+ getLanguage: ()=>getNodeAjaxOptions('get_languages', this, treeNodeInfo, itemNodeData),
+ getSupportFunctions: ()=>getNodeAjaxOptions('get_support_functions', this, treeNodeInfo, itemNodeData, {
+ cacheNode: 'function'
+ }),
+
+ },
+ {
+ node_info: treeNodeInfo,
+ },
+ {
+ type: pgBrowser.Nodes['procedure'].type,
+ },
+ {
+ funcowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ pronamespace: treeNodeInfo.schema ? treeNodeInfo.schema._id : null,
+ lanname: treeNodeInfo.server.server_type != 'ppas' ? 'sql' : 'edbspl',
+ }
+ );
+ },
+
+ });
+
+ }
+
+ return pgBrowser.Nodes['procedure'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js
new file mode 100644
index 0000000000000000000000000000000000000000..8528101db06fb2b3c097a518d181fbcf7b1da1ed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.js
@@ -0,0 +1,109 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import TriggerFunctionSchema from './trigger_function.ui';
+import { getNodeListByName, getNodeListById, getNodeAjaxOptions } from '../../../../../../../static/js/node_ajax';
+import { getNodeVariableSchema } from '../../../../../static/js/variable.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import _ from 'lodash';
+
+/* Create and Register Function Collection and Node. */
+define('pgadmin.node.trigger_function', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-trigger_function']) {
+ pgBrowser.Nodes['coll-trigger_function'] =
+ pgBrowser.Collection.extend({
+ node: 'trigger_function',
+ label: gettext('Trigger functions'),
+ type: 'coll-trigger_function',
+ columns: ['name', 'funcowner', 'description'],
+ hasStatistics: true,
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['trigger_function']) {
+ pgBrowser.Nodes['trigger_function'] = schemaChild.SchemaChildNode.extend({
+ type: 'trigger_function',
+ sqlAlterHelp: 'plpgsql-trigger.html',
+ sqlCreateHelp: 'plpgsql-trigger.html',
+ dialogHelp: url_for('help.static', {'filename': 'trigger_function_dialog.html'}),
+ label: gettext('Trigger function'),
+ collection_type: 'coll-trigger_function',
+ canEdit: function(itemData, item) {
+ let node = pgBrowser.tree.findNodeByDomElement(item);
+
+ return !(!node || node.parentNode.getData()._type === 'trigger');
+ },
+ hasSQL: true,
+ showMenu: function(itemData, item) {
+ return this.canEdit(itemData, item);
+ },
+ hasDepends: true,
+ hasStatistics: true,
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_trigger_function_on_coll', node: 'coll-trigger_function', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger function...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_trigger_function', node: 'trigger_function', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger function...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_trigger_function', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger function...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },
+ ]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new TriggerFunctionSchema(
+ (privileges)=>getNodePrivilegeRoleSchema('', treeNodeInfo, itemNodeData, privileges),
+ ()=>getNodeVariableSchema(this, treeNodeInfo, itemNodeData, false, false),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListById(pgBrowser.Nodes['schema'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ language: ()=>getNodeAjaxOptions('get_languages', this, treeNodeInfo, itemNodeData, {noCache: true}, (res) => {
+ return _.reject(res, function(o) {
+ return o.label == 'sql';
+ });
+ }),
+ nodeInfo: treeNodeInfo
+ },
+ {
+ funcowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ pronamespace: treeNodeInfo.schema ? treeNodeInfo.schema._id : null
+ }
+ );
+ },
+ });
+
+ }
+
+ return pgBrowser.Nodes['trigger_function'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..8e9fbd74adc790cf622f2ece037f451771dff08b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/static/js/trigger_function.ui.js
@@ -0,0 +1,274 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { isEmptyString } from 'sources/validators';
+
+
+export default class TriggerFunctionSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, getVariableSchema, fieldOptions={}, initValues={}) {
+ super({
+ name: null,
+ oid: null,
+ xmin: null,
+ funcowner: null,
+ pronamespace: null,
+ description: null,
+ pronargs: null, /* Argument Count */
+ proargs: null, /* Arguments */
+ proargtypenames: null, /* Argument Signature */
+ prorettypename: 'trigger', /* Return Type */
+ lanname: 'plpgsql', /* Language Name in which function is being written */
+ provolatile: null, /* Volatility */
+ proretset: null, /* Return Set */
+ proisstrict: null,
+ prosecdef: null, /* Security of definer */
+ proiswindow: null, /* Window Function ? */
+ procost: null, /* Estimated execution Cost */
+ prorows: null, /* Estimated number of rows */
+ proleakproof: null,
+ args: [],
+ prosrc: null,
+ prosrc_c: null,
+ probin: '$libdir/',
+ options: [],
+ variables: [],
+ proacl: null,
+ seclabels: [],
+ acl: [],
+ sysfunc: null,
+ sysproc: null,
+ ...initValues
+ });
+
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.getVariableSchema = getVariableSchema;
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ language: [],
+ nodeInfo: null,
+ ...fieldOptions,
+ };
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ isReadonly() {
+ return false;
+ }
+
+ setReadonlyInEditMode() {
+ return !this.isNew();
+ }
+
+
+ isVisible(state) {
+ return state.name != 'sysproc';
+ }
+
+ isDisabled() {
+ return 'catalog' in this.fieldOptions.nodeInfo;
+ }
+
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ noEmpty: true
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'funcowner', label: gettext('Owner'), cell: 'text',
+ type:'select', disabled: obj.isDisabled, readonly: obj.isReadonly,
+ options: obj.fieldOptions.role,
+ controlProps: { allowClear: false }
+ },{
+ id: 'pronamespace', label: gettext('Schema'), cell: 'string',
+ type: 'select', cache_level: 'database',
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ mode: ['create', 'edit'],
+ options: obj.fieldOptions.schema,
+ controlProps: { allowClear: false }
+ },{
+ id: 'sysfunc', label: gettext('System trigger function?'),
+ cell:'boolean', type: 'switch',
+ mode: ['properties'], visible: obj.isVisible
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'pronargs', label: gettext('Argument count'), cell: 'text',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'proargs', label: gettext('Arguments'), cell: 'string',
+ type: 'text', group: gettext('Definition'), mode: ['properties', 'edit'],
+ disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode,
+ },{
+ id: 'proargtypenames', label: gettext('Signature arguments'), cell:
+ 'text', type: 'text', group: gettext('Definition'), mode: ['properties'],
+ disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode,
+ },{
+ id: 'prorettypename', label: gettext('Return type'), cell: 'text',
+ type: 'select', group: gettext('Definition'),
+ disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode,
+ controlProps: {
+ width: '100%',
+ allowClear: false,
+ },
+ mode: ['create'], visible: obj.isVisible,
+ options: [
+ {label: gettext('trigger'), value: 'trigger'},
+ {label: gettext('event_trigger'), value: 'event_trigger'},
+ ],
+ },{
+ id: 'prorettypename', label: gettext('Return type'), cell: 'text',
+ type: 'text', group: gettext('Definition'),
+ mode: ['properties', 'edit'], disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode,
+ visible: obj.isVisible
+ }, {
+ id: 'lanname', label: gettext('Language'), cell: 'text',
+ type: 'select', group: gettext('Definition'),
+ mode: ['create', 'properties', 'edit'],
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ options: obj.fieldOptions.language,
+ controlProps: {
+ allowClear: false,
+ filter: (options) => {
+ return (options||[]).filter(option => {
+ return option.label != '';
+ });
+ }
+ },
+ },{
+ id: 'prosrc', label: gettext('Code'), cell: 'text',
+ type: 'sql', isFullTab: true,
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Code'), deps: ['lanname'],
+ visible: (state) => {
+ return state.lanname !== 'c';
+ },
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'probin', label: gettext('Object file'), cell: 'string',
+ type: 'text', group: gettext('Definition'), deps: ['lanname'],
+ visible: (state) => {
+ return state.lanname == 'c';
+ },
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'prosrc_c', label: gettext('Link symbol'), cell: 'string',
+ type: 'text', group: gettext('Definition'), deps: ['lanname'],
+ visible: (state) => {
+ return state.lanname == 'c';
+ },
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'provolatile', label: gettext('Volatility'), cell: 'text',
+ type: 'select', group: gettext('Options'),
+ options:[
+ {'label': 'VOLATILE', 'value': 'v'},
+ {'label': 'STABLE', 'value': 's'},
+ {'label': 'IMMUTABLE', 'value': 'i'},
+ ], disabled: obj.isDisabled, readonly: obj.isReadonly,
+ controlProps: { allowClear: false },
+ },{
+ id: 'proretset', label: gettext('Returns a set?'), type: 'switch',
+ group: gettext('Options'), disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode,
+ visible: obj.isVisible
+ },{
+ id: 'proisstrict', label: gettext('Strict?'), type: 'switch',
+ disabled: obj.isDisabled, readonly: obj.isReadonly, group: gettext('Options'),
+ },{
+ id: 'prosecdef', label: gettext('Security of definer?'),
+ group: gettext('Options'), cell:'boolean', type: 'switch',
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'proiswindow', label: gettext('Window?'),
+ group: gettext('Options'), cell:'boolean', type: 'switch',
+ disabled: obj.isDisabled, readonly: obj.setReadonlyInEditMode, visible: obj.isVisible
+ },{
+ id: 'procost', label: gettext('Estimated cost'), type: 'text',
+ group: gettext('Options'), disabled: obj.isDisabled, readonly: obj.isReadonly,
+ },{
+ id: 'prorows', label: gettext('Estimated rows'), type: 'text',
+ group: gettext('Options'),
+ disabled: (state) => {
+ let isDisabled = true;
+ if(state.proretset) {
+ isDisabled = false;
+ }
+ return isDisabled;
+ },
+ readonly: obj.isReadonly,
+ deps: ['proretset'], visible: obj.isVisible
+ },{
+ id: 'proleakproof', label: gettext('Leak proof?'),
+ group: gettext('Options'), cell:'boolean', type: 'switch', min_version: 90200,
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ }, {
+ id: 'proacl', label: gettext('Privileges'), mode: ['properties'],
+ group: gettext('Security'), type: 'text',
+ },
+ {
+ id: 'variables', label: '', type: 'collection',
+ group: gettext('Parameters'), control: 'variable-collection',
+ mode: ['edit', 'create'], canEdit: false,
+ canDelete: true, disabled: obj.isDisabled, readonly: obj.isReadonly,
+ schema: this.getVariableSchema(),
+ editable: false,
+ },
+ {
+ id: 'acl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['X']),
+ uniqueCol : ['grantee'],
+ editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ },
+ {
+ id: 'seclabels', label: gettext('Security labels'), type: 'collection',
+ schema: new SecLabelSchema(),
+ editable: false, group: gettext('Security'),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: true, canDelete: true,
+ uniqueCol : ['provider'],
+ min_version: 90200,
+ disabled: obj.isDisabled, readonly: obj.isReadonly,
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+
+ if (isEmptyString(state.service)) {
+
+ /* code validation*/
+ if (isEmptyString(state.prosrc)) {
+ errmsg = gettext('Code cannot be empty.');
+ setError('prosrc', errmsg);
+ return true;
+ } else {
+ setError('prosrc', null);
+ }
+
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b9599093a3f927d0d90111d1d288b52c3d969f93
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a3b4aa73fcf0d9cf08a74e856f5748b8449df0ce
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/count.sql
@@ -0,0 +1,9 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2709bc56f0782ec791c794ce3960a303a23ee589
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9a49887784fcb4fcf7d866f13167d523f199da3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cb2eb80f8582a3723a7be36490fdc5963e689271
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace as nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dfc141f4f8523cf93b44078fc2e2a3ca9363e21d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/node.sql
@@ -0,0 +1,26 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind IN ('f', 'w')
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b8745c6a74fa77249c1dc58a061fd42bc8ec9dd7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/11_plus/properties.sql
@@ -0,0 +1,36 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1daa2e1bd1e2bf7334efdb9fe912a2e8452931be
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/create.sql
@@ -0,0 +1,73 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.prosupportfunc %}
+ SUPPORT {{ data.prosupportfunc }}
+{% endif -%}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/get_support_functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/get_support_functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7cc21ee03d121b0b32125bbed2cdc8d141870c69
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/get_support_functions.sql
@@ -0,0 +1,12 @@
+SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS sfunctions
+FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
+WHERE p.pronamespace = n.oid
+AND p.prolang = l.oid
+AND p.prorettype = 'internal'::regtype::oid
+AND pg_catalog.array_to_string(p.proargtypes, ',') = 'internal'::regtype::oid::text
+AND (l.lanname = 'internal' or l.lanname = 'c' )
+-- -- If Show SystemObjects is not true
+{% if not show_system_objects %}
+ AND (nspname NOT LIKE 'pg\_%' AND nspname NOT in ('information_schema'))
+{% endif %}
+ORDER BY nspname ASC, proname ASC
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..23d9e9544a37c36c565744e57d2d84adf3fdd7c0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/properties.sql
@@ -0,0 +1,43 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ CASE WHEN prosupport = 0::oid THEN ''
+ ELSE (
+ SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
+ FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
+ WHERE p.pronamespace = n.oid
+ AND p.oid = pr.prosupport::OID
+ ) END AS prosupportfunc,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..73f7cdb7f36192f64176b386322ae7b0f4ade1ff
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/12_plus/update.sql
@@ -0,0 +1,130 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif %}
+
+ {% if data.prosupportfunc %}SUPPORT {{ data.prosupportfunc }}{% elif data.prosupportfunc is not defined and o_data.prosupportfunc %}SUPPORT {{ o_data.prosupportfunc }}{% endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..429c82d452724ca51f82e27b25025cf0ad4e0b61
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/create.sql
@@ -0,0 +1,76 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.prosupportfunc %}
+ SUPPORT {{ data.prosupportfunc }}
+{% endif -%}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..782b943851087055f48ebd93bc5d2360b064bc58
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/properties.sql
@@ -0,0 +1,45 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
+ CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ CASE WHEN prosupport = 0::oid THEN ''
+ ELSE (
+ SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
+ FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
+ WHERE p.pronamespace = n.oid
+ AND p.oid = pr.prosupport::OID
+ ) END AS prosupportfunc,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a3d3f24a3c467db3c5315b49383f4d54e353350d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/14_plus/update.sql
@@ -0,0 +1,133 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif %}
+
+ {% if data.prosupportfunc %}SUPPORT {{ data.prosupportfunc }}{% elif data.prosupportfunc is not defined and o_data.prosupportfunc %}SUPPORT {{ o_data.prosupportfunc }}{% endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c30978e025a80de2b3b9d679b45e521391ab4e06
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..effaeeee3bb93e67244031116da2c494b2329858
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f97fdcdf3b95a08c73eb60fe6b87405c617435c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c58142347fcd868264187e8384420046f939819d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/create.sql
@@ -0,0 +1,70 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6d0ce90fcfad9934087c16843526aff8cc8bd24b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..083e294f67b160f0c8360c3fbf2ad312c0f31fd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fe091cc9c8aa19fb34181dacf96366dc3b7b1f3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace as nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..eecbdcfdd92e0958fde0ffbb8b5afb726d366af0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/node.sql
@@ -0,0 +1,26 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ proisagg = FALSE
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5c6883761df6de59e308c3b806a94b6a3200709e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/properties.sql
@@ -0,0 +1,35 @@
+SELECT
+ pr.oid, pr.xmin, pr.proiswindow, pr.prosrc, pr.prosrc AS prosrc_c,
+ pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e624d5f52e8b050260d356bf37898d3ca8a2bdf1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/update.sql
@@ -0,0 +1,128 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/pg/sql/default/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b9599093a3f927d0d90111d1d288b52c3d969f93
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d602b1d1bc83fdad726b02a1a9cd59e8610c7fbf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/count.sql
@@ -0,0 +1,9 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1c721d1a0ac53a62eb3881280f2998801bf1a312
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/delete.sql
@@ -0,0 +1,22 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9a49887784fcb4fcf7d866f13167d523f199da3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cb2eb80f8582a3723a7be36490fdc5963e689271
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace as nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2b2dd8107e691b85743099de0a0479e163abe4d4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/node.sql
@@ -0,0 +1,27 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') || ')' AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pr.protype = '0'::char
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b8745c6a74fa77249c1dc58a061fd42bc8ec9dd7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/11_plus/properties.sql
@@ -0,0 +1,36 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..45728f8fca4eb13a19795ed23b506f49d9e50d53
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/create.sql
@@ -0,0 +1,74 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.prosupportfunc %}
+
+ SUPPORT {{ data.prosupportfunc }}
+{% endif -%}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/get_support_functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/get_support_functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7cc21ee03d121b0b32125bbed2cdc8d141870c69
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/get_support_functions.sql
@@ -0,0 +1,12 @@
+SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS sfunctions
+FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
+WHERE p.pronamespace = n.oid
+AND p.prolang = l.oid
+AND p.prorettype = 'internal'::regtype::oid
+AND pg_catalog.array_to_string(p.proargtypes, ',') = 'internal'::regtype::oid::text
+AND (l.lanname = 'internal' or l.lanname = 'c' )
+-- -- If Show SystemObjects is not true
+{% if not show_system_objects %}
+ AND (nspname NOT LIKE 'pg\_%' AND nspname NOT in ('information_schema'))
+{% endif %}
+ORDER BY nspname ASC, proname ASC
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..920ea8fb09930096148911ee6411b2259424bc25
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/properties.sql
@@ -0,0 +1,37 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ CASE WHEN prosupport = 0::oid THEN '' ELSE prosupport::text END AS prosupportfunc,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..73f7cdb7f36192f64176b386322ae7b0f4ade1ff
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/12_plus/update.sql
@@ -0,0 +1,130 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif %}
+
+ {% if data.prosupportfunc %}SUPPORT {{ data.prosupportfunc }}{% elif data.prosupportfunc is not defined and o_data.prosupportfunc %}SUPPORT {{ o_data.prosupportfunc }}{% endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..429c82d452724ca51f82e27b25025cf0ad4e0b61
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/create.sql
@@ -0,0 +1,76 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.prosupportfunc %}
+ SUPPORT {{ data.prosupportfunc }}
+{% endif -%}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4576d25f8227f6805464cbcf52d3ae122a7f8602
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/properties.sql
@@ -0,0 +1,39 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
+ CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
+ CASE WHEN prosupport = 0::oid THEN '' ELSE prosupport::text END AS prosupportfunc,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a3d3f24a3c467db3c5315b49383f4d54e353350d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/14_plus/update.sql
@@ -0,0 +1,133 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif %}
+
+ {% if data.prosupportfunc %}SUPPORT {{ data.prosupportfunc }}{% elif data.prosupportfunc is not defined and o_data.prosupportfunc %}SUPPORT {{ o_data.prosupportfunc }}{% endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c30978e025a80de2b3b9d679b45e521391ab4e06
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..effaeeee3bb93e67244031116da2c494b2329858
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f97fdcdf3b95a08c73eb60fe6b87405c617435c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c58142347fcd868264187e8384420046f939819d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/create.sql
@@ -0,0 +1,70 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{func_def}}
+{% else %}
+CREATE{% if query_type is defined %}{{' OR REPLACE'}}{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif -%}
+)
+{% endif %}
+ RETURNS{% if data.proretset and (data.prorettypename.startswith('SETOF ') or data.prorettypename.startswith('TABLE')) %} {{ data.prorettypename }} {% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER {% endif %}
+{% if data.proiswindow %}WINDOW {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED {% elif data.proparallel == 's' %}PARALLEL SAFE {% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %}{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}
+{% endif %}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6d0ce90fcfad9934087c16843526aff8cc8bd24b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..083e294f67b160f0c8360c3fbf2ad312c0f31fd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fe091cc9c8aa19fb34181dacf96366dc3b7b1f3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace as nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..27e2127821235a4a3e087242a031a7c75a434c56
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/node.sql
@@ -0,0 +1,27 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') || ')' AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ proisagg = FALSE
+ AND pr.protype = '0'::char
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5c6883761df6de59e308c3b806a94b6a3200709e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/properties.sql
@@ -0,0 +1,35 @@
+SELECT
+ pr.oid, pr.xmin, pr.proiswindow, pr.prosrc, pr.prosrc AS prosrc_c,
+ pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e624d5f52e8b050260d356bf37898d3ca8a2bdf1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/update.sql
@@ -0,0 +1,128 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% set set_variables = [] %}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+{% set set_variables = data.merged_variables %}
+{% elif 'variables' in o_data and o_data.variables|length > 0 %}
+{% set set_variables = o_data.variables %}
+{% endif %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}
+{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %},{% endif %}
+{% endfor %}
+{% endif -%}
+)
+ RETURNS {% if 'prorettypename' in data %}{{ data.prorettypename }}{% else %}{{ o_data.prorettypename }}{% endif %}
+
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows and data.prorows != '0' %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif -%}{% if set_variables and set_variables|length > 0 %}{% for v in set_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/functions/ppas/sql/default/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3ee42371059d2ddb5e6b6efc26b02b9f2b8b2093
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3a3bf5698452df9ad44abd8bba55a3e05e42d61e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1be1b3961472ba447918d20d831f2cc89dcbc80b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind = 'p'
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..807268a6153f3411cb5114fadf2cbc3aa993b561
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/create.sql
@@ -0,0 +1,58 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE OR REPLACE PROCEDURE {{func_def}}
+{% else %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}{% if data.arguments is defined %}
+({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname)}} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor -%}
+{% endif %}
+)
+{% endif %}
+LANGUAGE {{ data.lanname|qtLiteral(conn) }}{% if data.prosecdef %}
+
+ SECURITY DEFINER {% endif %}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+
+{% if data.funcowner %}
+ALTER PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+
+{% if data.acl and not is_sql %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "PROCEDURE", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "PROCEDURE", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..daacd44ee347fdc12cb820e353afae6e595aa10f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind = 'p'::char
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP PROCEDURE IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cd566e2d3e76902677b3d10b9cd30e6d3789bc5d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind = 'p'::char
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89a61772e9c5573afd493457fea27e9de4d5bd07
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..24f25c75d5959e4e38f6a2617dd8dc12c0bd8578
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/node.sql
@@ -0,0 +1,33 @@
+SELECT
+ pr.oid,
+ CASE WHEN
+ pg_catalog.pg_get_function_identity_arguments(pr.oid) <> ''
+ THEN
+ pr.proname || '(' || pg_catalog.pg_get_function_identity_arguments(pr.oid) || ')'
+ ELSE
+ pr.proname::text
+ END AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind = 'p'::char
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d51e26d5bb41cf1fdea8f8fdabec34764985120f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/properties.sql
@@ -0,0 +1,47 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (
+ WITH name_with_args_tab AS (SELECT pg_catalog.pg_get_function_identity_arguments(pr.oid) AS val)
+ SELECT CASE WHEN
+ val <> ''
+ THEN
+ pr.proname || '(' || val || ')'
+ ELSE
+ pr.proname::text
+ END
+ FROM name_with_args_tab
+ ) AS name_with_args,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind = 'p'
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f5aee3efe5953276e69c77915307e24456268164
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/update.sql
@@ -0,0 +1,112 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+
+{% endif -%}
+{% if data.change_func %}
+CREATE OR REPLACE PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif %}
+)
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %}SECURITY DEFINER{% endif %}
+{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant,
+ priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'PROCEDURE', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'PROCEDURE', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'PROCEDURE', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.pronamespace %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/11_plus/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1be1b3961472ba447918d20d831f2cc89dcbc80b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind = 'p'
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2be6c82b172ef7f800d444b97a3de4c19eb2d02f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/create.sql
@@ -0,0 +1,61 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE OR REPLACE PROCEDURE {{func_def}}
+{% else %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}{% if data.arguments is defined %}
+({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname)}} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor -%}
+{% endif %}
+)
+{% endif %}
+LANGUAGE {{ data.lanname|qtLiteral(conn) }}{% if data.prosecdef %}
+
+ SECURITY DEFINER {% endif %}
+{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+
+{% if data.funcowner %}
+ALTER PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+
+{% if data.acl and not is_sql %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "PROCEDURE", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "PROCEDURE", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4dad586d565a61130612173cd2ab22dc45a76352
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/properties.sql
@@ -0,0 +1,49 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
+ CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (
+ WITH name_with_args_tab AS (SELECT pg_catalog.pg_get_function_identity_arguments(pr.oid) AS val)
+ SELECT CASE WHEN
+ val <> ''
+ THEN
+ pr.proname || '(' || val || ')'
+ ELSE
+ pr.proname::text
+ END
+ FROM name_with_args_tab
+ ) AS name_with_args,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind = 'p'
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d5701a023317e807d8ea76a5ffe8488aea2194ec
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/pg/sql/14_plus/update.sql
@@ -0,0 +1,114 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+
+{% endif -%}
+{% if data.change_func %}
+CREATE OR REPLACE PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif %}
+)
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %}SECURITY DEFINER{% endif %}
+{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}{% else %}
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant,
+ priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'PROCEDURE', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'PROCEDURE', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'PROCEDURE', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.pronamespace %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3a3bf5698452df9ad44abd8bba55a3e05e42d61e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..edbed6d4cba217d626f2d311ec1b7b498b98865d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cd8c921515d72357a5d19d46ef97a9320c1c4b4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/create.sql
@@ -0,0 +1,66 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE OR REPLACE PROCEDURE {{func_def}}
+{% else %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}{% if data.arguments is defined %}
+({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname)}} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor -%}
+{% endif %}
+)
+{% endif %}
+LANGUAGE {{ data.lanname|qtLiteral(conn) }}{% if data.prosecdef %}
+
+ SECURITY DEFINER {% endif %}
+{% if data.lanname == 'edbspl' %}
+{% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED{% elif data.proparallel == 's' %}PARALLEL SAFE{% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %} {% endif %}{% if data.procost %}
+
+ COST {{data.procost}}{% endif %}{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% endif %}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+
+{% if data.funcowner %}
+ALTER PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+
+{% if data.acl and not is_sql %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "PROCEDURE", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "PROCEDURE", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..daacd44ee347fdc12cb820e353afae6e595aa10f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind = 'p'::char
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP PROCEDURE IF EXISTS {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cd566e2d3e76902677b3d10b9cd30e6d3789bc5d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind = 'p'::char
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89a61772e9c5573afd493457fea27e9de4d5bd07
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..24f25c75d5959e4e38f6a2617dd8dc12c0bd8578
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/node.sql
@@ -0,0 +1,33 @@
+SELECT
+ pr.oid,
+ CASE WHEN
+ pg_catalog.pg_get_function_identity_arguments(pr.oid) <> ''
+ THEN
+ pr.proname || '(' || pg_catalog.pg_get_function_identity_arguments(pr.oid) || ')'
+ ELSE
+ pr.proname::text
+ END AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind = 'p'::char
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dcca1a9170da6e91643ef4bd20e79d0c08a2f93e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/properties.sql
@@ -0,0 +1,47 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (
+ WITH name_with_args_tab AS (SELECT pg_catalog.pg_get_function_identity_arguments(pr.oid) AS val)
+ SELECT CASE WHEN
+ val <> ''
+ THEN
+ pr.proname || '(' || val || ')'
+ ELSE
+ pr.proname::text
+ END
+ FROM name_with_args_tab
+ ) AS name_with_args,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..497d53822545770790932ebc31311e9884e3e970
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/11_plus/update.sql
@@ -0,0 +1,121 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+
+{% endif -%}
+{% if data.change_func %}
+CREATE OR REPLACE PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif %}
+)
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}
+{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }} {% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %}SECURITY DEFINER{% endif %}
+{% if data.lanname == 'edbspl' or (o_data.lanname == 'edbspl' and not 'lanname' in data ) %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
+ {% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}}{% endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+{% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'PROCEDURE', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'PROCEDURE', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'PROCEDURE', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.pronamespace %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..edbed6d4cba217d626f2d311ec1b7b498b98865d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f0f23945bbe9af601985e6d8da629209e931a1bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/create.sql
@@ -0,0 +1,69 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE OR REPLACE PROCEDURE {{func_def}}
+{% else %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}{% if data.arguments is defined %}
+({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname)}} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor -%}
+{% endif %}
+)
+{% endif %}
+LANGUAGE {{ data.lanname|qtLiteral(conn) }}{% if data.prosecdef %}
+
+ SECURITY DEFINER {% endif %}
+{% if data.lanname == 'edbspl' %}
+{% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %}PARALLEL RESTRICTED{% elif data.proparallel == 's' %}PARALLEL SAFE{% elif data.proparallel == 'u' %}PARALLEL UNSAFE{% endif %} {% endif %}{% if data.procost %}
+
+ COST {{data.procost}}{% endif %}{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% endif %}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+
+{% if data.funcowner %}
+ALTER PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+
+{% if data.acl and not is_sql %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "PROCEDURE", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "PROCEDURE", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args_without}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a1a81dcf5ba1ea77c468edb96005aeeb03fd14ed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/properties.sql
@@ -0,0 +1,49 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ pg_catalog.pg_get_function_sqlbody(pr.oid) AS prosrc_sql,
+ CASE WHEN pr.prosqlbody IS NOT NULL THEN true ELSE false END as is_pure_sql,
+ (
+ WITH name_with_args_tab AS (SELECT pg_catalog.pg_get_function_identity_arguments(pr.oid) AS val)
+ SELECT CASE WHEN
+ val <> ''
+ THEN
+ pr.proname || '(' || val || ')'
+ ELSE
+ pr.proname::text
+ END
+ FROM name_with_args_tab
+ ) AS name_with_args,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind = 'p'::char
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8de573c55cedeea96c42e3c7188e453799f009e8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/14_plus/update.sql
@@ -0,0 +1,124 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+
+{% endif -%}
+{% if data.change_func %}
+CREATE OR REPLACE PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({% if data.arguments %}{% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+{% endif %}
+)
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}
+{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }} {% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %}SECURITY DEFINER{% endif %}
+{% if data.lanname == 'edbspl' or (o_data.lanname == 'edbspl' and not 'lanname' in data ) %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
+ {% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}}{% endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+{% endif %}
+
+{% if data.is_pure_sql %}{{ data.prosrc }}
+{% else %}
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'PROCEDURE', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'PROCEDURE', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'PROCEDURE', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.pronamespace %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3ee42371059d2ddb5e6b6efc26b02b9f2b8b2093
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..effaeeee3bb93e67244031116da2c494b2329858
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..aa89e2f8a76d6a59150c7335edad323289640877
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..51efc8635f2c67b974c2bda89159957e5ca030c1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/create.sql
@@ -0,0 +1,60 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+{% if query_for == 'sql_panel' and func_def is defined %}
+CREATE OR REPLACE PROCEDURE {{func_def}}
+{% else %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}{% if data.arguments is defined %}
+({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname)}} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor -%}
+){% endif %}
+
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %} {% endif %}{% if data.proleakproof %}LEAKPROOF {% endif %}
+{% if data.proisstrict %}STRICT {% endif %}
+{% if data.prosecdef %}SECURITY DEFINER{% endif %}
+{% if data.proparallel and (data.proparallel == 'r' or data.proparallel == 's' or data.proparallel == 'u') %}
+{% if data.proparallel == 'r' %} PARALLEL RESTRICTED{% elif data.proparallel == 's' %} PARALLEL SAFE {% elif data.proparallel == 'u' %} PARALLEL UNSAFE{% endif %}{% endif %}{% if data.procost %}
+
+ COST {{data.procost}}{% endif %}{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+AS {{ data.prosrc }};
+
+{% if data.funcowner %}
+ALTER PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+
+{% if data.acl and not is_sql %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "PROCEDURE", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args_without)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "PROCEDURE", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(data.pronamespace, data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', data.name, r.provider, r.label, data.pronamespace, data.func_args_without) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4008e7be3e79baf0fd04cf92646bd2756937784d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP PROCEDURE {{ conn|qtIdent(nspname, name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..083e294f67b160f0c8360c3fbf2ad312c0f31fd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5b05f7933a6844b910877e7e99f15ca678c91698
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dde3fbeb7f0d69f156eb114f1adb2ac954ed74f1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/node.sql
@@ -0,0 +1,34 @@
+SELECT
+ pr.oid,
+ CASE WHEN
+ pg_catalog.pg_get_function_identity_arguments(pr.oid) <> ''
+ THEN
+ pr.proname || '(' || pg_catalog.pg_get_function_identity_arguments(pr.oid) || ')'
+ ELSE
+ pr.proname::text
+ END AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ proisagg = FALSE
+ AND pr.protype = '1'::char
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname NOT IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..af676f3e31cd65112d459f1c10d014ae56e05754
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/properties.sql
@@ -0,0 +1,46 @@
+SELECT
+ pr.oid, pr.xmin,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (
+ WITH name_with_args_tab AS (SELECT pg_catalog.pg_get_function_identity_arguments(pr.oid) AS val)
+ SELECT CASE WHEN
+ val <> ''
+ THEN
+ pr.proname || '(' || val || ')'
+ ELSE
+ pr.proname::text
+ END
+ FROM name_with_args_tab
+ ) AS name_with_args,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1c0e885179f217863a7bdbd3f98d43700c731f27
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/update.sql
@@ -0,0 +1,109 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+CREATE OR REPLACE PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if data.arguments %}({% for p in data.arguments %}{% if p.argmode %}{{p.argmode}} {% endif %}{% if p.argname %}{{ conn|qtIdent(p.argname) }} {% endif %}{% if p.argtype %}{{ p.argtype }}{% endif %}{% if p.argdefval %} DEFAULT {{p.argdefval}}{% endif %}
+{% if not loop.last %}, {% endif %}
+{% endfor %}
+)
+{% endif %}
+
+ {% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }} {% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %} {% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %}LEAKPROOF{% else %}NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+
+ {% if 'proparallel' in data and data.proparallel %}PARALLEL {{ data.proparallel }}{% elif 'proparallel' not in data and o_data.proparallel %}PARALLEL {{ o_data.proparallel }}{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}}{% endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+{% endif %}
+
+AS {% if data.prosrc %}{{ data.prosrc }}{% else %}{{ o_data.prosrc }}{% endif %};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}{% if o_data.proargtypenames %}({{ o_data.proargtypenames }}){% endif %}
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.datacl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'PROCEDURE', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'PROCEDURE', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif %}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'PROCEDURE', name, data.variables.deleted, o_data.pronamespace) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'PROCEDURE', name, data.merged_variables, o_data.pronamespace) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'PROCEDURE', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'PROCEDURE', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.pronamespace %}
+
+ALTER PROCEDURE {{ conn|qtIdent(o_data.pronamespace, name) }}
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/procedures/ppas/sql/default/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ae9079b90d7a703b3cf48f55d36c36fb6374a0f2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind IN ('f', 'w')
+ AND typname = 'trigger'
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c4e2cd657d99ee085dfbce6671df58a4cd91228
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/count.sql
@@ -0,0 +1,14 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9377e6a466104ccb1a9f7a6498f8b07c7f81011a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/create.sql
@@ -0,0 +1,57 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.proargnames %}{{data.proargnames}}{% endif %})
+ RETURNS{% if data.proretset and data.prorettypename.startswith('SETOF ') %} {{ data.prorettypename }}{% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %}{% endif %}{% if data.proleakproof %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
+{% if data.proisstrict %} STRICT{% endif %}
+{% if data.prosecdef %} SECURITY DEFINER{% endif %}
+{% if data.proiswindow %} WINDOW{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4eb207cf245a2801debae7851fa96ef1757e46d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND typname IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9a49887784fcb4fcf7d866f13167d523f199da3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1da0793f9a93eab7a25cf4916e2f89d668a2c7c8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/get_oid.sql
@@ -0,0 +1,18 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4619bcfcf893e270b72d6286d0ff554a3e56985d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/node.sql
@@ -0,0 +1,27 @@
+SELECT
+ pr.oid, pr.proname || '()' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind IN ('f', 'w')
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..afa3dcc1dcd473e12bc0ee7a21bdb42c1e8027d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/properties.sql
@@ -0,0 +1,37 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f9a2b1c0f3f7c41b44f8e03ddc528a35ac482a49
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/11_plus/update.sql
@@ -0,0 +1,114 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}()
+ RETURNS {{ o_data.prorettypename }}
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }}{% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3ee42371059d2ddb5e6b6efc26b02b9f2b8b2093
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a927a5633a8c57c5b4a08e00702b8081aef4f83e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.proisagg = FALSE
+ AND typname = 'trigger'
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..18266de943078170c28604ec47f0ddf644e90c07
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/count.sql
@@ -0,0 +1,14 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9377e6a466104ccb1a9f7a6498f8b07c7f81011a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/create.sql
@@ -0,0 +1,57 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({% if data.proargnames %}{{data.proargnames}}{% endif %})
+ RETURNS{% if data.proretset and data.prorettypename.startswith('SETOF ') %} {{ data.prorettypename }}{% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %}{% endif %}{% if data.proleakproof %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
+{% if data.proisstrict %} STRICT{% endif %}
+{% if data.prosecdef %} SECURITY DEFINER{% endif %}
+{% if data.proiswindow %} WINDOW{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..42bd27f66a49d68f5aba7816d4632af187504faa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND typname IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..083e294f67b160f0c8360c3fbf2ad312c0f31fd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8b1d2410594d4c3fc3ce4cbe91a939331d9cb3b2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_oid.sql
@@ -0,0 +1,18 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..322fdb76e2ce81c69fd21ad88c96efdca1984b04
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/node.sql
@@ -0,0 +1,27 @@
+SELECT
+ pr.oid, pr.proname || '()' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ proisagg = FALSE
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9679f2c0632f92dd20bd58af0f113fd8849bf437
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/properties.sql
@@ -0,0 +1,36 @@
+SELECT
+ pr.oid, pr.xmin, pr.proiswindow, pr.prosrc, pr.prosrc AS prosrc_c,
+ pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('edbspl', 'sql', 'internal')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f9a2b1c0f3f7c41b44f8e03ddc528a35ac482a49
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/update.sql
@@ -0,0 +1,114 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}()
+ RETURNS {{ o_data.prorettypename }}
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }}{% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif data.prorows is not defined and o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.acl %}
+{% for priv in data.acl.changed %}
+
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.old_grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/pg/sql/default/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..701810d26f19999058eab482e9e8dc27d422d869
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..997152d0607b3852d1c885d3c6dbc4ca91d5a33a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/count.sql
@@ -0,0 +1,13 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4eb207cf245a2801debae7851fa96ef1757e46d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND typname IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9a49887784fcb4fcf7d866f13167d523f199da3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..16a94add6eadf1407d0dc58c2a44290645a94356
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/get_oid.sql
@@ -0,0 +1,18 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('sql', 'internal')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0ed66310987279ed8ffc1b7ebc4a6c80f53feaf0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/node.sql
@@ -0,0 +1,26 @@
+SELECT
+ pr.oid, pr.proname || '()' AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ pr.prokind IN ('f', 'w')
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname IN ('trigger', 'event_trigger')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c9f2fae3badc917a20dbdf2507e31b798b20b57e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/11_plus/properties.sql
@@ -0,0 +1,36 @@
+SELECT
+ pr.oid, pr.xmin,
+ CASE WHEN pr.prokind = 'w' THEN true ELSE false END AS proiswindow,
+ pr.prosrc, pr.prosrc AS prosrc_c, pr.pronamespace, pr.prolang, pr.procost, pr.prorows, pr.prokind,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile, pr.proparallel,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pr.pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname IN ('trigger', 'event_trigger')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3ee42371059d2ddb5e6b6efc26b02b9f2b8b2093
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT
+ COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(privilege_type) AS privileges,
+ pg_catalog.array_agg(is_grantable) AS grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ (d).privilege_type AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(db.proacl) AS d FROM pg_catalog.pg_proc db
+ WHERE db.oid = {{fnid}}::OID) a ORDER BY privilege_type
+ ) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a927a5633a8c57c5b4a08e00702b8081aef4f83e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/coll_stats.sql
@@ -0,0 +1,20 @@
+SELECT
+ funcname AS {{ conn|qtIdent(_('Name')) }},
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ AND funcid IN (
+ SELECT p.oid
+ FROM
+ pg_catalog.pg_proc p
+ JOIN
+ pg_catalog.pg_type typ ON typ.oid=p.prorettype
+ WHERE
+ p.proisagg = FALSE
+ AND typname = 'trigger'
+ )
+ORDER BY funcname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dd9006c0a38b005bc4efc3336f024c85123f39fd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/count.sql
@@ -0,0 +1,14 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('sql', 'internal')
+ AND pronamespace = {{scid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8827bb55d6e503f01c81dff20204942e7cf254c4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/create.sql
@@ -0,0 +1,57 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}
+{% set is_columns = [] %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data %}
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}()
+ RETURNS{% if data.proretset and data.prorettypename.startswith('SETOF ') %} {{ data.prorettypename }}{% elif data.proretset %} SETOF {{ data.prorettypename }}{% else %} {{ data.prorettypename }}{% endif %}
+
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }}
+{% if data.procost %}
+ COST {{data.procost}}
+{% endif %}
+ {% if data.provolatile %}{% if data.provolatile == 'i' %}IMMUTABLE{% elif data.provolatile == 's' %}STABLE{% else %}VOLATILE{% endif %}{% endif %}{% if data.proleakproof %} LEAKPROOF{% else %} NOT LEAKPROOF{% endif %}
+{% if data.proisstrict %} STRICT{% endif %}
+{% if data.prosecdef %} SECURITY DEFINER{% endif %}
+{% if data.proiswindow %} WINDOW{% endif %}
+{% if data.prorows and (data.prorows | int) > 0 %}
+
+ ROWS {{data.prorows}}{% endif -%}{% if data.variables %}{% for v in data.variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor %}
+{% endif %}
+
+AS {% if data.lanname == 'c' %}
+{{ data.probin|qtLiteral(conn) }}, {{ data.prosrc_c|qtLiteral(conn) }}
+{% else %}
+$BODY${{ data.prosrc }}$BODY${% endif -%};
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{% if data.acl %}
+{% for p in data.acl %}
+
+{{ PRIVILEGE.SET(conn, "FUNCTION", p.grantee, data.name, p.without_grant, p.with_grant, data.pronamespace, data.func_args)}}
+{% endfor %}{% endif %}
+{% if data.revoke_all %}
+
+{{ PRIVILEGE.UNSETALL(conn, "FUNCTION", "PUBLIC", data.name, data.pronamespace, data.func_args_without)}}
+{% endif %}
+{% if data.description %}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(data.pronamespace, data.name) }}({{data.func_args}})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{% if r.label and r.provider %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', data.name, r.provider, r.label, data.pronamespace, data.func_args) }}
+{% endif %}
+{% endfor %}
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..42bd27f66a49d68f5aba7816d4632af187504faa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/delete.sql
@@ -0,0 +1,21 @@
+{% if scid and fnid %}
+SELECT
+ pr.proname as name, '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as func_args,
+ nspname
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND typname IN ('trigger', 'event_trigger')
+ AND pr.oid = {{fnid}};
+{% endif %}
+
+{% if name %}
+DROP FUNCTION {{ conn|qtIdent(nspname, name) }}{{func_args}}{% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_definition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_definition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..083e294f67b160f0c8360c3fbf2ad312c0f31fd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_definition.sql
@@ -0,0 +1,15 @@
+SELECT
+ pg_catalog.pg_get_functiondef({{fnid}}::oid) AS func_def,
+ COALESCE(pg_catalog.pg_get_function_identity_arguments(pr.oid), '') as
+ func_with_identity_arguments,
+ nspname,
+ pr.proname as proname,
+ COALESCE(pg_catalog.pg_get_function_arguments(pr.oid), '') as func_args
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+WHERE
+ proisagg = FALSE
+ AND pronamespace = {{scid}}::oid
+ AND pr.oid = {{fnid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_languages.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_languages.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2843741f4b5b865f686173abc34a51194a726947
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_languages.sql
@@ -0,0 +1,4 @@
+SELECT
+ lanname as label, lanname as value
+FROM
+ pg_catalog.pg_language;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dc94c254369194531e14324a57240d815b085b2d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_oid.sql
@@ -0,0 +1,18 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner, pr.pronamespace AS nsp
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('sql', 'internal')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_out_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_out_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9ec158ecdb8ee4d0d9af5eea0888eed4afeeb2ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_out_types.sql
@@ -0,0 +1,6 @@
+SELECT
+ pg_catalog.format_type(oid, NULL) AS out_arg_type
+FROM
+ pg_catalog.pg_type
+WHERE
+ oid = {{ out_arg_oid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed340f529c11bdec69e42aea22c812a4c3a7ad5f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/get_types.sql
@@ -0,0 +1,20 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid, typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ (
+ typtype IN ('b', 'c', 'd', 'e', 'p', 'r')
+ AND typname NOT IN ('any', 'trigger', 'language_handler', 'event_trigger')
+ )
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c4ae760aaf5c1b2c0b1399073c59395badac7ebc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/node.sql
@@ -0,0 +1,27 @@
+SELECT
+ pr.oid, pr.proname || '()' AS name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass)
+WHERE
+ proisagg = FALSE
+{% if fnid %}
+ AND pr.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+{% if scid %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pr.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('sql', 'internal')
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8ef144b66bb1e143ab21c6b8acc70bf2d5027521
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/properties.sql
@@ -0,0 +1,36 @@
+SELECT
+ pr.oid, pr.xmin, pr.proiswindow, pr.prosrc, pr.prosrc AS prosrc_c,
+ pr.pronamespace, pr.prolang, pr.procost, pr.prorows,
+ pr.prosecdef, pr.proleakproof, pr.proisstrict, pr.proretset, pr.provolatile,
+ pr.pronargs, pr.prorettype, pr.proallargtypes, pr.proargmodes, pr.probin, pr.proacl,
+ pr.proname, pr.proname AS name, pg_catalog.pg_get_function_result(pr.oid) AS prorettypename,
+ typns.nspname AS typnsp, lanname, proargnames, pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pronargdefaults, proconfig, pg_catalog.pg_get_userbyid(proowner) AS funcowner, description,
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabel sl1
+ WHERE
+ sl1.objoid=pr.oid) AS seclabels
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_namespace typns ON typns.oid=typ.typnamespace
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=pr.oid AND des.classoid='pg_proc'::regclass and des.objsubid = 0)
+WHERE
+ proisagg = FALSE
+ AND typname IN ('trigger', 'event_trigger')
+ AND lanname NOT IN ('sql', 'internal')
+{% if fnid %}
+ AND pr.oid = {{fnid}}::oid
+{% else %}
+ AND pronamespace = {{scid}}::oid
+{% endif %}
+ORDER BY
+ proname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..26e87b08c8ce55617a9d0c3b9128ac0ca722d1f3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/update.sql
@@ -0,0 +1,110 @@
+{% import 'macros/functions/security.macros' as SECLABEL %}
+{% import 'macros/functions/privilege.macros' as PRIVILEGE %}
+{% import 'macros/functions/variable.macros' as VARIABLE %}{% if data %}
+{% set name = o_data.name %}
+{% set exclude_quoting = ['search_path'] %}
+{% if data.name %}
+{% if data.name != o_data.name %}
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, o_data.name) }}({{
+o_data.proargtypenames }})
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% set name = data.name %}
+{% endif %}
+{% endif -%}
+{% if data.change_func %}
+
+CREATE OR REPLACE FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}()
+ RETURNS {{ o_data.prorettypename }}
+{% if 'lanname' in data %}
+ LANGUAGE {{ data.lanname|qtLiteral(conn) }} {% else %}
+ LANGUAGE {{ o_data.lanname|qtLiteral(conn) }}
+ {% endif %}{% if 'provolatile' in data and data.provolatile %}{{ data.provolatile }}{% elif 'provolatile' not in data and o_data.provolatile %}{{ o_data.provolatile }}{% endif %}
+{% if ('proleakproof' in data and data.proleakproof) or ('proleakproof' not in data and o_data.proleakproof) %} LEAKPROOF{% elif 'proleakproof' in data and not data.proleakproof %} NOT LEAKPROOF{% endif %}
+{% if ('proisstrict' in data and data.proisstrict) or ('proisstrict' not in data and o_data.proisstrict) %} STRICT{% endif %}
+{% if ('prosecdef' in data and data.prosecdef) or ('prosecdef' not in data and o_data.prosecdef) %} SECURITY DEFINER{% endif %}
+{% if ('proiswindow' in data and data.proiswindow) or ('proiswindow' not in data and o_data.proiswindow) %} WINDOW{% endif %}
+
+ {% if data.procost %}COST {{data.procost}}{% elif o_data.procost %}COST {{o_data.procost}}{% endif %}{% if data.prorows %}
+
+ ROWS {{data.prorows}}{% elif o_data.prorows and o_data.prorows != '0' %} ROWS {{o_data.prorows}} {%endif -%}{% if data.merged_variables %}{% for v in data.merged_variables %}
+
+ SET {{ conn|qtIdent(v.name) }}={% if v.name in exclude_quoting %}{{ v.value }}{% else %}{{ v.value|qtLiteral(conn) }}{% endif %}{% endfor -%}
+ {% endif %}
+
+AS {% if (data.lanname == 'c' or o_data.lanname == 'c') and ('probin' in data or 'prosrc_c' in data) %}
+{% if 'probin' in data %}{{ data.probin|qtLiteral(conn) }}{% else %}{{ o_data.probin|qtLiteral(conn) }}{% endif %}, {% if 'prosrc_c' in data %}{{ data.prosrc_c|qtLiteral(conn) }}{% else %}{{ o_data.prosrc_c|qtLiteral(conn) }}{% endif %}{% elif 'prosrc' in data %}
+$BODY${{ data.prosrc }}$BODY${% elif o_data.lanname == 'c' %}
+{{ o_data.probin|qtLiteral(conn) }}, {{ o_data.prosrc_c|qtLiteral(conn) }}{% else %}
+$BODY${{ o_data.prosrc }}$BODY${% endif -%};
+{% endif -%}
+{% if data.funcowner %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ OWNER TO {{ conn|qtIdent(data.funcowner) }};
+{% endif -%}
+{# The SQL generated below will change priviledges #}
+{% if data.acl %}
+{% if 'deleted' in data.acl %}
+{% for priv in data.acl.deleted %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in data.datacl %}
+{% for priv in data.acl.changed %}
+
+{{ PRIVILEGE.UNSETALL(conn, 'FUNCTION', priv.grantee, name, o_data.pronamespace, o_data.proargtypenames) }}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in data.acl %}
+{% for priv in data.acl.added %}
+
+{{ PRIVILEGE.SET(conn, 'FUNCTION', priv.grantee, name, priv.without_grant, priv.with_grant, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}{% endif -%}
+{% endif -%}
+{% if data.change_func == False %}
+{% if data.variables %}
+{% if 'deleted' in data.variables and data.variables.deleted|length > 0 %}
+
+{{ VARIABLE.UNSET(conn, 'FUNCTION', name, data.variables.deleted, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% if 'merged_variables' in data and data.merged_variables|length > 0 %}
+
+{{ VARIABLE.SET(conn, 'FUNCTION', name, data.merged_variables, o_data.pronamespace, o_data.proargtypenames) }}
+{% endif -%}
+{% endif -%}
+{% endif -%}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+
+{{ SECLABEL.UNSET(conn, 'FUNCTION', name, r.provider, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+
+{{ SECLABEL.SET(conn, 'FUNCTION', name, r.provider, r.label, o_data.pronamespace, o_data.proargtypenames) }}
+{% endfor %}
+{% endif -%}
+{% if data.description is defined and data.description != o_data.description%}
+
+COMMENT ON FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif -%}
+
+{% if data.pronamespace %}
+
+ALTER FUNCTION {{ conn|qtIdent(o_data.pronamespace, name) }}({{o_data.proargtypenames }})
+ SET SCHEMA {{ conn|qtIdent(data.pronamespace) }};
+{% endif -%}
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c75e5b47f0ffa92429debbe64fb03a5aae139aa0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/templates/trigger_functions/ppas/sql/default/variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ name, vartype, min_val, max_val, enumvals
+FROM
+ pg_catalog.pg_settings
+WHERE
+ context in ('user', 'superuser');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ba6fdfa9c84990f575bbe8968a4840b6039efee
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/functions/utils.py
@@ -0,0 +1,262 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+import copy
+import re
+from flask import render_template
+from pgadmin.utils.ajax import internal_server_error
+
+
+def get_argument_values(data):
+ """
+ This function is used to get the argument values for
+ function/procedure.
+ :param data:
+ :return:
+ """
+ proargtypes = []
+ if ('proargtypenames' in data and data['proargtypenames'] and
+ isinstance(data['proargtypenames'], str)):
+ proargtypes = [ptype for ptype in data['proargtypenames'].split(",")]
+ elif 'proargtypenames' in data and data['proargtypenames']:
+ proargtypes = data['proargtypenames']
+
+ proargmodes = (
+ data)['proargmodes'] if 'proargmodes' in data and data['proargmodes'] \
+ else ['i'] * len(proargtypes)
+ proargnames = (
+ data)['proargnames'] if 'proargnames' in data and data['proargnames'] \
+ else []
+
+ proargdefaultvals = []
+ if ('proargdefaultvals' in data and data['proargdefaultvals'] and
+ isinstance(data['proargdefaultvals'], str)):
+ proargdefaultvals = re.split(
+ r',(?=(?:[^\"\']*[\"\'][^\"\']*[\"\'])*[^\"\']*$)',
+ data['proargdefaultvals'])
+ elif 'proargdefaultvals' in data and data['proargdefaultvals']:
+ proargdefaultvals = data['proargdefaultvals']
+
+ proallargtypes = data['proallargtypes'] \
+ if 'proallargtypes' in data and data['proallargtypes'] else []
+
+ return {'proargtypes': proargtypes, 'proargmodes': proargmodes,
+ 'proargnames': proargnames,
+ 'proargdefaultvals': proargdefaultvals,
+ 'proallargtypes': proallargtypes}
+
+
+def params_list_for_display(proargmodes_fltrd, proargtypes,
+ proargnames, proargdefaultvals):
+ """
+ This function is used to prepare dictionary of arguments to
+ display on UI.
+ :param proargmodes_fltrd:
+ :param proargtypes:
+ :param proargnames:
+ :param proargdefaultvals:
+ :return:
+ """
+ # Insert null value against the parameters which do not have
+ # default values.
+ if len(proargmodes_fltrd) > len(proargdefaultvals):
+ dif = len(proargmodes_fltrd) - len(proargdefaultvals)
+ while dif > 0:
+ proargdefaultvals.insert(0, '')
+ dif -= 1
+
+ param = {"arguments": [
+ map_arguments_dict(
+ i, proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '',
+ proargtypes[i] if len(proargtypes) > i else '',
+ proargnames[i] if len(proargnames) > i else '',
+ proargdefaultvals[i] if len(proargdefaultvals) > i else ''
+ )
+ for i in range(len(proargtypes))]}
+ return param
+
+
+def display_properties_argument_list(proargmodes_fltrd, proargtypes,
+ proargnames, proargdefaultvals):
+ """
+ This function is used to prepare list of arguments to display on UI.
+ :param proargmodes_fltrd:
+ :param proargtypes:
+ :param proargnames:
+ :param proargdefaultvals:
+ :return:
+ """
+ proargs = [map_arguments_list(
+ proargmodes_fltrd[i] if len(proargmodes_fltrd) > i else '',
+ proargtypes[i] if len(proargtypes) > i else '',
+ proargnames[i] if len(proargnames) > i else '',
+ proargdefaultvals[i] if len(proargdefaultvals) > i else ''
+ )
+ for i in range(len(proargtypes))]
+
+ return proargs
+
+
+def map_arguments_dict(argid, argmode, argtype, argname, argdefval):
+ """
+ Returns Dict of formatted Arguments.
+ Args:
+ argid: Argument Sequence Number
+ argmode: Argument Mode
+ argname: Argument Name
+ argtype: Argument Type
+ argdefval: Argument Default Value
+ """
+ # The pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) SQL
+ # statement gives us '-' as a default value for INOUT mode.
+ # so, replacing it with empty string.
+ if argmode == 'INOUT' and argdefval.strip() == '-':
+ argdefval = ''
+
+ return {"argid": argid,
+ "argtype": argtype.strip() if argtype is not None else '',
+ "argmode": argmode,
+ "argname": argname,
+ "argdefval": argdefval}
+
+
+def map_arguments_list(argmode, argtype, argname, argdef):
+ """
+ Returns List of formatted Arguments.
+ Args:
+ argmode: Argument Mode
+ argname: Argument Name
+ argtype: Argument Type
+ argdef: Argument Default Value
+ """
+ # The pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) SQL
+ # statement gives us '-' as a default value for INOUT mode.
+ # so, replacing it with empty string.
+ if argmode == 'INOUT' and argdef.strip() == '-':
+ argdef = ''
+
+ arg = ''
+
+ if argmode:
+ arg += argmode + " "
+ if argname:
+ arg += argname + " "
+ if argtype:
+ arg += argtype + " "
+ if argdef:
+ arg += " DEFAULT " + argdef
+
+ return arg.strip(" ")
+
+
+def format_arguments_from_db(sql_template_path, conn, data):
+ """
+ Create Argument list of the Function.
+
+ Args:
+ sql_template_path:
+ conn:
+ data: Function Data
+
+ Returns:
+ Function Arguments in the following format.
+ [
+ {'proargtypes': 'integer', 'proargmodes: 'IN',
+ 'proargnames': 'column1', 'proargdefaultvals': 1}, {...}
+ ]
+ Where
+ Arguments:
+ # proargtypes: Argument Types (Data Type)
+ # proargmodes: Argument Modes [IN, OUT, INOUT, VARIADIC]
+ # proargnames: Argument Name
+ # proargdefaultvals: Default Value of the Argument
+ """
+ arguments = get_argument_values(data)
+ proargtypes = arguments['proargtypes']
+ proargmodes = arguments['proargmodes']
+ proargnames = arguments['proargnames']
+ proargdefaultvals = arguments['proargdefaultvals']
+ proallargtypes = arguments['proallargtypes']
+
+ proargmodenames = {
+ 'i': 'IN', 'o': 'OUT', 'b': 'INOUT', 'v': 'VARIADIC', 't': 'TABLE'
+ }
+
+ # We need to put default parameter at proper location in list
+ # Total number of default parameters
+ total_default_parameters = len(proargdefaultvals)
+
+ # Total number of parameters
+ total_parameters = len(proargtypes)
+
+ # Parameters which do not have default parameters
+ non_default_parameters = total_parameters - total_default_parameters
+
+ # only if we have at least one parameter with default value
+ if total_default_parameters > 0 and non_default_parameters > 0:
+ for idx in range(non_default_parameters):
+ # Set null value for parameter non-default parameter
+ proargdefaultvals.insert(idx, '')
+
+ # The proargtypes doesn't give OUT params, so we need to fetch
+ # those from database explicitly, below code is written for this
+ # purpose.
+ #
+ # proallargtypes gives all the Function's argument including OUT,
+ # but we have not used that column; as the data type of this
+ # column (i.e. oid[]) is not supported by oidvectortypes(oidvector)
+ # function which we have used to fetch the datatypes
+ # of the other parameters.
+
+ proargmodes_fltrd = copy.deepcopy(proargmodes)
+ proargnames_fltrd = []
+ cnt = 0
+ for m in proargmodes:
+ if m == 'o': # Out Mode
+ sql = render_template("/".join([sql_template_path,
+ 'get_out_types.sql']),
+ out_arg_oid=proallargtypes[cnt])
+ status, out_arg_type = conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=out_arg_type)
+
+ # Insert out parameter datatype
+ proargtypes.insert(cnt, out_arg_type)
+ proargdefaultvals.insert(cnt, '')
+ elif m == 'v': # Variadic Mode
+ proargdefaultvals.insert(cnt, '')
+ elif m == 't': # Table Mode
+ proargmodes_fltrd.remove(m)
+ proargnames_fltrd.append(proargnames[cnt])
+
+ cnt += 1
+
+ cnt = 0
+ # Map param's short form to its actual name. (ex: 'i' to 'IN')
+ for m in proargmodes_fltrd:
+ proargmodes_fltrd[cnt] = proargmodenames[m]
+ cnt += 1
+
+ # Removes Argument Names from the list if that argument is removed
+ # from the list
+ for i in proargnames_fltrd:
+ proargnames.remove(i)
+
+ # Prepare list of Argument list dict to be displayed in the Data Grid.
+ params = params_list_for_display(proargmodes_fltrd, proargtypes,
+ proargnames, proargdefaultvals)
+
+ # Prepare string formatted Argument to be displayed in the Properties
+ # panel.
+ proargs = display_properties_argument_list(proargmodes_fltrd, proargtypes,
+ proargnames, proargdefaultvals)
+
+ proargs = {"proargs": ", ".join(proargs)}
+
+ return params, proargs
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..56eda2cd41563d01577f9ee41d5bb60d78c5c6a8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/__init__.py
@@ -0,0 +1,374 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Operator Node """
+
+from functools import wraps
+
+from flask import render_template
+from flask_babel import gettext
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+
+
+class OperatorModule(SchemaChildModule):
+ """
+ class OperatorModule(SchemaChildModule)
+
+ A module class for Operator node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Operator and it's base module.
+
+ * get_nodes(gid, sid, did, scid, opid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'operator'
+ _COLLECTION_LABEL = gettext("Operators")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the OperatorModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90100
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=OperatorView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ return False
+
+
+blueprint = OperatorModule(__name__)
+
+
+class OperatorView(PGChildNodeView):
+ """
+ This class is responsible for generating routes for Operator node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the OperatorView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Operator nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Operator node.
+
+ * properties(gid, sid, did, scid, opid)
+ - This function will show the properties of the selected Operator node
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Operator node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Operator"
+ BASE_TEMPLATE_PATH = 'operators/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'opid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = \
+ self.BASE_TEMPLATE_PATH.format(self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the operator nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available operator nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the operator node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available operator child nodes
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-operator",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, opid):
+ """
+ This function will fetch properties of the operator node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ opid: Operator ID
+
+ Returns:
+ JSON of given operator node
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), opid=opid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-operator"
+ ),
+ status=200
+ )
+
+ return gone(self.not_found_error_msg())
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, opid):
+ """
+ This function will show the properties of the selected operator node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ opid: Operator ID
+
+ Returns:
+ JSON of selected operator node
+ """
+
+ status, res = self._fetch_properties(scid, opid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, opid):
+ """
+ This function fetch the properties for the specified object.
+
+ :param scid: Schema ID
+ :param opid: Operator ID
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, opid=opid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return True, res['rows'][0]
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, opid):
+ """
+ This function will generates reverse engineered sql for operator
+ object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ opid: Operator ID
+ json_resp: True then return json response
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, opid=opid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data)
+
+ sql_header = "-- Operator: {0};\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ name=data['name'],
+ oprnamespace=data['schema'],
+ lefttype=data['lefttype'],
+ righttype=data['righttype'],
+ )
+ SQL = sql_header + '\n' + SQL.strip('\n')
+
+ return ajax_response(response=SQL)
+
+
+OperatorView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/coll-operator.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/coll-operator.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5ad8f7235407caeb984b4fb1b0cb47017b129883
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/coll-operator.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/operator.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/operator.svg
new file mode 100644
index 0000000000000000000000000000000000000000..80e5ae26f90e17521493316d493716ecade2d7fd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/img/operator.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.js
new file mode 100644
index 0000000000000000000000000000000000000000..dfdcade86f1319c202180fe5dea7a579e372c527
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.js
@@ -0,0 +1,55 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import OperatorSchema from './operator.ui';
+
+define('pgadmin.node.operator', [
+ 'sources/gettext',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.browser.collection',
+], function(gettext, pgAdmin, pgBrowser, schemaChild) {
+
+ if (!pgBrowser.Nodes['coll-operator']) {
+ pgAdmin.Browser.Nodes['coll-operator'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'operator',
+ label: gettext('Operators'),
+ type: 'coll-operator',
+ columns: ['name', 'owner', 'description'],
+ canDrop: false,
+ canDropCascade: false,
+ canSelect: false
+ });
+ }
+
+ if (!pgBrowser.Nodes['operator']) {
+ pgAdmin.Browser.Nodes['operator'] = schemaChild.SchemaChildNode.extend({
+ type: 'operator',
+ sqlAlterHelp: 'sql-alteroperator.html',
+ sqlCreateHelp: 'sql-createoperator.html',
+ label: gettext('Operator'),
+ collection_type: 'coll-operator',
+ hasSQL: true,
+ hasDepends: false,
+ canDrop: false,
+ canDropCascade: false,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+ },
+ getSchema: ()=>{
+ return new OperatorSchema();
+ }
+ });
+ }
+ return pgBrowser.Nodes['operator'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..b3014ae44eb600477527e5ae69e617961d9a924e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/static/js/operator.ui.js
@@ -0,0 +1,125 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import gettext from 'sources/gettext';
+
+export default class OperatorSchema extends BaseUISchema {
+ constructor(fieldOptions = {},initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ owner: undefined,
+ description: undefined,
+ schema: null,
+ lefttype: undefined,
+ righttype: undefined,
+ operproc:undefined,
+ joinproc: undefined,
+ restrproc: undefined,
+ commutator: undefined,
+ negator:undefined,
+ support_hash: false,
+ support_merge: false,
+ ...initValues
+ });
+ this.fieldOptions = fieldOptions;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ return [
+ {
+ id: 'name', label: gettext('Name'), type: 'tel',
+ readonly: true,
+ },
+ {
+ id: 'oid', label: gettext('OID'),
+ type: 'text', mode: ['properties']
+ },
+ {
+ id: 'owner', label: gettext('Owner'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'schema', label: gettext('Schema'),
+ mode: ['create', 'edit'],
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'is_sys_obj', label: gettext('System operator?'),
+ cell: 'boolean', type: 'switch', mode: ['properties'],
+ },
+ {
+ id: 'description', label: gettext('Comment'),
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ readonly: true,
+ },
+ {
+ id: 'lefttype', label: gettext('Left type'),
+ group: gettext('Definition'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'righttype', label: gettext('Right type'),
+ group: gettext('Definition'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'resulttype', label: gettext('Result type'),
+ group: gettext('Definition'),
+ type: 'text', mode: ['properties'],
+ },
+ {
+ id: 'oprkind', label: gettext('Kind'),
+ group: gettext('Definition'),
+ type: 'text', mode: ['properties'],
+ },
+ {
+ id: 'operproc', label: gettext('Operator function'),
+ group: gettext('Definition'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'restrproc', label: gettext('Restrict function'),
+ group: gettext('Implementation'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'joinproc', label: gettext('Join function'),
+ group: gettext('Implementation'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'commutator', label: gettext('Commutator'),
+ group: gettext('Implementation'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'negator', label: gettext('Negator'),
+ group: gettext('Implementation'),
+ type: 'text', readonly: true,
+ },
+ {
+ id: 'support_hash', label: gettext('Supports hash'),
+ group: gettext('Implementation'),
+ cell: 'boolean', type: 'switch', readonly: true,
+ },
+ {
+ id: 'support_merge', label: gettext('Supports merge'),
+ group: gettext('Implementation'),
+ cell: 'boolean', type: 'switch', readonly: true,
+ }
+ ];
+ }
+}
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c15382ce51ba822c589c566c687c419a4352ef93
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/11_plus/create.sql
@@ -0,0 +1,13 @@
+{% if data %}
+CREATE OPERATOR {{data.schema}}.{{data.name}} (
+ FUNCTION = {{data.operproc}}{% if data.lefttype %},
+ LEFTARG = {{data.lefttype}}{% endif %}{% if data.righttype %},
+ RIGHTARG = {{data.righttype}}{% endif %}{% if data.commutator %},
+ COMMUTATOR = {{data.commutator}}{% endif %}{% if data.negator %},
+ NEGATOR = {{data.negator}}{% endif %}{% if data.restrproc %},
+ RESTRICT = {{data.restrproc}}{% endif %}{% if data.joinproc %},
+ JOIN = {{data.joinproc}}{% endif %}{% if data.support_hash %},
+ HASHES{% endif %}{% if data.support_merge %}, MERGES{% endif %}
+
+);
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..27c4ec67a3bc0d7857948e1f31706de7321e3ba7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/count.sql
@@ -0,0 +1,6 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_operator op
+ JOIN pg_catalog.pg_type et on et.oid=op.oprresult
+{% if scid %}
+ WHERE op.oprnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6c31580741b6609d20fca95fbc5a0375c7f8cdac
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/create.sql
@@ -0,0 +1,13 @@
+{% if data %}
+CREATE OPERATOR {{data.schema}}.{{data.name}} (
+ PROCEDURE = {{data.operproc}}{% if data.lefttype %},
+ LEFTARG = {{data.lefttype}}{% endif %}{% if data.righttype %},
+ RIGHTARG = {{data.righttype}}{% endif %}{% if data.commutator %},
+ COMMUTATOR = {{data.commutator}}{% endif %}{% if data.negator %},
+ NEGATOR = {{data.negator}}{% endif %}{% if data.restrproc %},
+ RESTRICT = {{data.restrproc}}{% endif %}{% if data.joinproc %},
+ JOIN = {{data.joinproc}}{% endif %}{% if data.support_hash %},
+ HASHES{% endif %}{% if data.support_merge %}, MERGES{% endif %}
+
+);
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..63b93b772c9da316fbb7802026b3f22a45225d2c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/delete.sql
@@ -0,0 +1,13 @@
+{% if lefttype %}
+{% set ltype = lefttype %}
+{% else %}
+{% set ltype = none %}
+{% endif %}
+{% if righttype %}
+{% set rtype = righttype %}
+{% else %}
+{% set rtype = none %}
+{% endif %}
+{% if name %}
+DROP OPERATOR IF EXISTS {{conn|qtIdent(oprnamespace)}}.{{name}} ({{ltype}} , {{rtype}}){% if cascade %} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d2444927a40c853b802bba051281626631383438
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/nodes.sql
@@ -0,0 +1,23 @@
+SELECT op.oid, pg_catalog.pg_get_userbyid(op.oprowner) as owner,
+ CASE WHEN lt.typname IS NOT NULL AND rt.typname IS NOT NULL THEN
+ op.oprname || ' (' || pg_catalog.format_type(lt.oid, NULL) || ', ' || pg_catalog.format_type(rt.oid, NULL) || ')'
+ WHEN lt.typname IS NULL AND rt.typname IS NOT NULL THEN
+ op.oprname || ' (' || pg_catalog.format_type(rt.oid, NULL) || ')'
+ WHEN lt.typname IS NOT NULL AND rt.typname IS NULL THEN
+ op.oprname || ' (' || pg_catalog.format_type(lt.oid, NULL) || ')'
+ ELSE op.oprname || '()'
+END as name,
+lt.typname as lefttype, rt.typname as righttype, description
+FROM pg_catalog.pg_operator op
+ LEFT OUTER JOIN pg_catalog.pg_type lt ON lt.oid=op.oprleft
+ LEFT OUTER JOIN pg_catalog.pg_type rt ON rt.oid=op.oprright
+ JOIN pg_catalog.pg_type et on et.oid=op.oprresult
+ LEFT OUTER JOIN pg_catalog.pg_operator co ON co.oid=op.oprcom
+ LEFT OUTER JOIN pg_catalog.pg_operator ne ON ne.oid=op.oprnegate
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=op.oid AND des.classoid='pg_operator'::regclass)
+{% if scid %}
+ WHERE op.oprnamespace = {{scid}}::oid
+{% elif opid %}
+ WHERE op.oid = {{opid}}::oid
+{% endif %}
+ORDER BY op.oprname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..513e8621efa7c86b67d9422481de8b8858ba7f29
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/operators/templates/operators/sql/default/properties.sql
@@ -0,0 +1,25 @@
+SELECT op.oid, op.oprname as name, ns.nspname as schema,
+ pg_catalog.pg_get_userbyid(op.oprowner) as owner,
+ op.oprcanhash as support_hash, op.oprcanmerge as support_merge,
+ ns.nspname as schema,
+ CASE WHEN op.oprkind = 'b' THEN 'infix'
+ WHEN op.oprkind = 'l' THEN 'prefix'
+ WHEN op.oprkind = 'r' THEN 'postfix'
+ ELSE 'unknown' END as oprkind, et.typname as resulttype,
+ pg_catalog.format_type(lt.oid, NULL) as lefttype,
+ pg_catalog.format_type(rt.oid, NULL) as righttype,
+ co.oprname as commutator, op.oprcode as operproc,
+ ne.oprname as negator, description,
+ CASE WHEN op.oprrest = '-'::regproc THEN null ELSE op.oprrest END as restrproc,
+ CASE WHEN op.oprjoin = '-'::regproc THEN null ELSE op.oprjoin END as joinproc
+FROM pg_catalog.pg_operator op
+ LEFT OUTER JOIN pg_catalog.pg_namespace ns ON ns.oid=op.oprnamespace
+ LEFT OUTER JOIN pg_catalog.pg_type lt ON lt.oid=op.oprleft
+ LEFT OUTER JOIN pg_catalog.pg_type rt ON rt.oid=op.oprright
+ JOIN pg_catalog.pg_type et on et.oid=op.oprresult
+ LEFT OUTER JOIN pg_catalog.pg_operator co ON co.oid=op.oprcom
+ LEFT OUTER JOIN pg_catalog.pg_operator ne ON ne.oid=op.oprnegate
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=op.oid AND des.classoid='pg_operator'::regclass)
+WHERE op.oprnamespace = {{scid}}::oid
+{% if opid %} AND op.oid = {{opid}}::oid {% endif %}
+ORDER BY op.oprname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..96fd36ee505b41b121498c2eca49d2c25403ef03
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/__init__.py
@@ -0,0 +1,904 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Package Node"""
+import re
+from functools import wraps
+
+import json
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.utils.ajax import make_json_response, \
+ make_response as ajax_response, internal_server_error, \
+ precondition_required, gone
+from pgadmin.utils.driver import get_driver
+
+
+class PackageModule(SchemaChildModule):
+ """
+ class PackageModule(CollectionNodeModule)
+
+ A module class for Package node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the PackageModule and it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * script_load()
+ - Load the module script for package, when any of the database node is
+ initialized.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ """
+
+ _NODE_TYPE = 'package'
+ _COLLECTION_LABEL = gettext("Packages")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90100
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the package node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=PackageView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for schema, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ def register(self, app, options):
+ """
+ Override the default register function to automagically register
+ sub-modules at once.
+ """
+ from .edbfuncs import blueprint as module
+ self.submodules.append(module)
+
+ from .edbfuncs import procedure_blueprint as module
+ self.submodules.append(module)
+
+ from .edbvars import blueprint as module
+ self.submodules.append(module)
+ super().register(app, options)
+
+
+blueprint = PackageModule(__name__)
+
+
+class PackageView(PGChildNodeView, SchemaDiffObjectCompare):
+ node_type = blueprint.node_type
+ node_label = "Package"
+ node_icon = "icon-%s" % node_type
+ BASE_TEMPLATE_PATH = 'packages/ppas/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'pkgid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ keys_to_ignore = ['oid', 'schema', 'xmin', 'oid-2', 'acl']
+
+ def check_precondition(action=None):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ def wrap(f):
+ @wraps(f)
+ def wrapped(self, *args, **kwargs):
+
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+ self.qtIdent = driver.qtIdent
+
+ if 'did' in kwargs:
+ self.conn = self.manager.connection(did=kwargs['did'])
+ else:
+ self.conn = self.manager.connection()
+ # If DB not connected then return error to browser
+ if not self.conn.connected():
+ return precondition_required(
+ gettext(
+ "Connection to the server has been lost."
+ )
+ )
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ sql = render_template(
+ "/".join([self.template_path, 'get_schema.sql']),
+ scid=kwargs['scid']
+ )
+ status, rset = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ self.schema = rset
+ # Allowed ACL on package
+ self.acl = ['X']
+
+ return f(self, *args, **kwargs)
+
+ return wrapped
+
+ return wrap
+
+ @check_precondition(action='list')
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the package nodes within the
+ collection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition(action='nodes')
+ def nodes(self, gid, sid, did, scid, pkgid=None):
+ """
+ This function is used to create all the child nodes within the
+ collection.
+ Here it will create all the package nodes.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid,
+ pkgid=pkgid
+ )
+ status, rset = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if pkgid is not None:
+ if len(rset['rows']) == 0:
+ return gone(
+ errormsg=self.not_found_error_msg()
+ )
+
+ row = rset['rows'][0]
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['description']
+ )
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition(action='node')
+ def node(self, gid, sid, did, scid, pkgid):
+ """
+ This function will show the selected package node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+
+ Returns:
+
+ """
+ res = []
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, pkgid=pkgid
+ )
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(
+ errormsg=self.not_found_error_msg()
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.node_icon
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition(action='properties')
+ def properties(self, gid, sid, did, scid, pkgid):
+ """
+ This function will show the properties of the selected package node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+
+ Returns:
+
+ """
+ status, res = self._fetch_properties(scid, pkgid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, pkgid):
+ """
+ This function is used to fetch the properties of specified object.
+ :param scid:
+ :param pkgid:
+ :return:
+ """
+ sql = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, pkgid=pkgid)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(
+ errormsg=self.not_found_error_msg()
+ )
+
+ res['rows'][0]['pkgheadsrc'] = self.get_inner(
+ res['rows'][0]['pkgheadsrc'])
+ res['rows'][0]['pkgbodysrc'] = self.get_inner(
+ res['rows'][0]['pkgbodysrc'])
+
+ sql = render_template("/".join([self.template_path, self._ACL_SQL]),
+ scid=scid,
+ pkgid=pkgid)
+ status, rset1 = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=rset1)
+
+ for row in rset1['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ res['rows'][0]['schema'] = self.schema
+
+ return True, res['rows'][0]
+
+ @check_precondition(action="create")
+ def create(self, gid, sid, did, scid):
+ """
+ Create the package.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ required_args = [
+ 'name',
+ 'pkgheadsrc'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ data['schema'] = self.schema
+
+ sql, _ = self.getSQL(data=data, scid=scid, pkgid=None)
+
+ status, msg = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=msg)
+
+ # We need oid of newly created package.
+ sql = render_template(
+ "/".join([
+ self.template_path, self._OID_SQL
+ ]),
+ name=data['name'], scid=scid, conn=self.conn
+ )
+
+ sql = sql.strip('\n').strip(' ')
+ if sql and sql != "":
+ status, pkgid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=pkgid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ pkgid,
+ scid,
+ data['name'],
+ icon=self.node_icon
+ )
+ )
+
+ @check_precondition(action='delete')
+ def delete(self, gid, sid, did, scid, pkgid=None, only_sql=False):
+ """
+ This function will drop the object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+ only_sql: Return SQL only if True
+
+ Returns:
+
+ """
+
+ if pkgid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [pkgid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for pkgid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ pkgid=pkgid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ res['rows'][0]['schema'] = self.schema
+
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=res['rows'][0],
+ cascade=cascade)
+
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Package dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition(action='update')
+ def update(self, gid, sid, did, scid, pkgid):
+ """
+ This function will update the object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ sql, name = self.getSQL(data=data, scid=scid, pkgid=pkgid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ pkgid,
+ scid,
+ name,
+ icon=self.node_icon,
+ **other_node_info
+ )
+ )
+
+ @check_precondition(action='msql')
+ def msql(self, gid, sid, did, scid, pkgid=None):
+ """
+ This function to return modified SQL.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+ """
+
+ data = {}
+ for k, v in request.args.items():
+ try:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ if pkgid is None:
+ required_args = [
+ 'name',
+ 'pkgheadsrc'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ sql, _ = self.getSQL(data=data, scid=scid, pkgid=pkgid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ def getSQL(self, **kwargs):
+ """
+ This function will generate sql from model data.
+ :param kwargs
+ :return:
+ """
+
+ scid = kwargs.get('scid')
+ data = kwargs.get('data')
+ pkgid = kwargs.get('pkgid', None)
+ sqltab = kwargs.get('sqltab', False)
+ is_schema_diff = kwargs.get('is_schema_diff', None)
+ target_schema = kwargs.get('target_schema', None)
+
+ if target_schema:
+ data['schema'] = target_schema
+ else:
+ data['schema'] = self.schema
+
+ if pkgid is not None and not sqltab:
+ return self.get_sql_with_pkgid(scid, pkgid, data, is_schema_diff)
+ else:
+ # To format privileges coming from client
+ if 'pkgacl' in data:
+ data['pkgacl'] = parse_priv_to_db(data['pkgacl'], self.acl)
+
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+
+ return sql, data['name']
+
+ def format_privilege_data(self, data):
+ # To format privileges data coming from client
+ for key in ['pkgacl']:
+ if key in data and data[key] is not None:
+ if 'added' in data[key]:
+ data[key]['added'] = parse_priv_to_db(
+ data[key]['added'], self.acl)
+ if 'changed' in data[key]:
+ data[key]['changed'] = parse_priv_to_db(
+ data[key]['changed'], self.acl)
+ if 'deleted' in data[key]:
+ data[key]['deleted'] = parse_priv_to_db(
+ data[key]['deleted'], self.acl)
+
+ def get_sql_with_pkgid(self, scid, pkgid, data, is_schema_diff):
+ """
+
+ :param scid:
+ :param pkgid:
+ :param data:
+ :param is_schema_diff:
+ :return:
+ """
+ required_args = [
+ 'name'
+ ]
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]), scid=scid,
+ pkgid=pkgid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return gone(
+ errormsg=self.not_found_error_msg()
+ )
+
+ res['rows'][0]['pkgheadsrc'] = self.get_inner(
+ res['rows'][0]['pkgheadsrc'])
+ res['rows'][0]['pkgbodysrc'] = self.get_inner(
+ res['rows'][0]['pkgbodysrc'])
+
+ sql = render_template("/".join([self.template_path, self._ACL_SQL]),
+ scid=scid,
+ pkgid=pkgid)
+
+ status, rset1 = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset1)
+
+ for row in rset1['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ # Making copy of output for further processing
+ old_data = dict(res['rows'][0])
+
+ # To format privileges data coming from client
+ self.format_privilege_data(data)
+
+ # If name is not present with in update data then copy it
+ # from old data
+ for arg in required_args:
+ if arg not in data:
+ data[arg] = old_data[arg]
+
+ sql = render_template("/".join([self.template_path,
+ self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn,
+ is_schema_diff=is_schema_diff)
+ return sql, data['name'] if 'name' in data else old_data['name']
+
+ @check_precondition(action="sql")
+ def sql(self, gid, sid, did, scid, pkgid, **kwargs):
+ """
+ This function will generate sql for sql panel
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+ is_schema_diff:
+ json_resp: json response or plain text response
+ """
+ is_schema_diff = kwargs.get('is_schema_diff', None)
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ try:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, pkgid=pkgid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ errormsg=self.not_found_error_msg()
+ )
+
+ res['rows'][0]['pkgheadsrc'] = self.get_inner(
+ res['rows'][0]['pkgheadsrc'])
+ res['rows'][0]['pkgbodysrc'] = self.get_inner(
+ res['rows'][0]['pkgbodysrc'])
+
+ sql = render_template("/".join([self.template_path,
+ self._ACL_SQL]),
+ scid=scid,
+ pkgid=pkgid)
+ status, rset1 = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset1)
+
+ for row in rset1['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ result = res['rows'][0]
+ if target_schema:
+ result['schema'] = target_schema
+
+ sql, _ = self.getSQL(data=result, scid=scid, pkgid=pkgid,
+ sqltab=True, is_schema_diff=is_schema_diff,
+ target_schema=target_schema)
+
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+
+ # Return sql for schema diff
+ if not json_resp:
+ return sql
+
+ sql_header = "-- Package: {0}.{1}\n\n-- ".format(
+ self.schema, result['name'])
+
+ sql_header += render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=result)
+ sql_header += "\n\n"
+
+ sql = sql_header + sql
+
+ return ajax_response(response=sql)
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition(action="dependents")
+ def dependents(self, gid, sid, did, scid, pkgid):
+ """
+ This function gets the dependents and returns an ajax response
+ for the package node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+ """
+ dependents_result = self.get_dependents(self.conn, pkgid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition(action="dependencies")
+ def dependencies(self, gid, sid, did, scid, pkgid):
+ """
+ This function gets the dependencies and returns an ajax response
+ for the package node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ pkgid: Package ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, pkgid)
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @staticmethod
+ def get_inner(sql):
+ if sql is None:
+ return None
+ start = 0
+ start_position = re.search("\\s+[is|as]+\\s+", sql, flags=re.I)
+
+ if start_position:
+ start = start_position.start() + 4
+
+ try:
+ end_position = [i for i in re.finditer("end", sql, flags=re.I)][-1]
+ end = end_position.start()
+ except IndexError:
+ return sql[start:].strip("\n")
+
+ return sql[start:end].strip("\n")
+
+ @check_precondition(action="fetch_objects_to_compare")
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the packages for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ if self.manager.server_type != 'ppas':
+ return res
+
+ sql = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.getSQL(data=data, scid=scid, pkgid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, pkgid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, pkgid=oid,
+ is_schema_diff=True, json_resp=False,
+ target_schema=target_schema)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, pkgid=oid,
+ is_schema_diff=True, json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, PackageView)
+PackageView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4bdc47a4e9257dc485325bffeee654dcfc59f43
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/__init__.py
@@ -0,0 +1,696 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Edb Functions/Edb Procedures Node."""
+
+import copy
+import re
+from functools import wraps
+
+from flask import render_template, make_response
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers.databases.schemas import packages
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ DataTypeReader
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, \
+ make_response as ajax_response, internal_server_error, gone
+from pgadmin.utils.ajax import precondition_required
+from pgadmin.utils.driver import get_driver
+from pgadmin.utils.preferences import Preferences
+
+
+class EdbFuncModule(CollectionNodeModule):
+ """
+ class EdbFuncModule(CollectionNodeModule):
+
+ This class represents The Functions Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Functions Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Functions collection node.
+
+ * node_inode():
+ - Returns Functions node as leaf node.
+
+ * script_load()
+ - Load the module script for Functions, when schema node is
+ initialized.
+
+ * csssnippets()
+ - Returns a snippet of css.
+ """
+
+ _NODE_TYPE = 'edbfunc'
+ _COLLECTION_LABEL = gettext("Functions")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Function Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = 90100
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def get_nodes(self, gid, sid, did, scid, pkgid):
+ """
+ Generate Functions collection node.
+ """
+ yield self.generate_browser_collection_node(pkgid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Functions, when the
+ package node is initialized.
+ """
+ return packages.PackageModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ def register_preferences(self):
+ """
+ Register preferences for this module.
+ """
+ # Add the node informaton for browser, not in respective
+ # node preferences
+ self.browser_preference = Preferences.module('browser')
+ self.pref_show_system_objects = self.browser_preference.preference(
+ 'show_system_objects'
+ )
+ self.pref_show_node = self.browser_preference.register(
+ 'node', 'show_node_' + self.node_type,
+ gettext('Package {0}').format(self.label), 'node',
+ self.SHOW_ON_BROWSER, category_label=gettext('Nodes')
+ )
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = EdbFuncModule(__name__)
+
+
+class EdbFuncView(PGChildNodeView, DataTypeReader):
+ """
+ class EdbFuncView(PGChildNodeView, DataTypeReader)
+
+ This class inherits PGChildNodeView and DataTypeReader to get the different
+ routes for the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Functions.
+
+ Methods:
+ -------
+ * validate_request(f):
+ - Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid, pkgid):
+ - List the Functions.
+
+ * nodes(gid, sid, did, scid, pkgid):
+ - Returns all the Functions to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, pkgid, edbfnid):
+ - Returns the Functions properties.
+
+ * sql(gid, sid, did, scid, pkgid, edbfnid):
+ - Returns the SQL for the Functions object.
+
+ * dependents(gid, sid, did, scid, ,pkgid, edbfnid):
+ - Returns the dependents for the Functions object.
+
+ * dependencies(gid, sid, did, scid, pkgid, edbfnid):
+ - Returns the dependencies for the Functions object.
+
+ * compare(**kwargs):
+ - This function will compare the nodes from two different schemas.
+ """
+
+ node_type = blueprint.node_type
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'pkgid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'edbfnid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties'},
+ {'get': 'list'}
+ ],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks the database connection status.
+ Attaches the connection object and template path to the class object.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+
+ # Get database connection
+ self.conn = self.manager.connection(did=kwargs['did'])
+
+ self.qtIdent = driver.qtIdent
+ self.qtLiteral = driver.qtLiteral
+
+ if not self.conn.connected():
+ return precondition_required(
+ gettext(
+ "Connection to the server has been lost."
+ )
+ )
+
+ # Set template path for sql scripts depending
+ # on the server version.
+ template_initial = None
+ if self.node_type == 'edbfunc':
+ template_initial = 'edbfuncs'
+ elif self.node_type == 'edbproc':
+ template_initial = 'edbprocs'
+
+ self.sql_template_path = "/".join([
+ template_initial,
+ self.manager.server_type,
+ '#{0}#'
+ ]).format(self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, pkgid):
+ """
+ List all the Functions.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ SQL = render_template("/".join([self.sql_template_path,
+ self._NODE_SQL]),
+ pkgid=pkgid,
+ conn=self.conn)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, pkgid, edbfnid=None):
+ """
+ Returns all the Functions to generate the Nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ """
+
+ res = []
+ SQL = render_template(
+ "/".join([self.sql_template_path, self._NODE_SQL]),
+ pkgid=pkgid,
+ fnid=edbfnid,
+ conn=self.conn
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if edbfnid is not None:
+ if len(rset['rows']) == 0:
+ return gone(
+ errormsg=gettext("Could not find the function")
+ )
+ row = rset['rows'][0]
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ pkgid,
+ row['name'],
+ icon="icon-" + self.node_type,
+ funcowner=row['funcowner']
+ ),
+ status=200
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ pkgid,
+ row['name'],
+ icon="icon-" + self.node_type,
+ funcowner=row['funcowner']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, pkgid, edbfnid=None):
+ """
+ Returns the Function properties.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ pkgid: Package Id
+ edbfnid: Function Id
+ """
+ SQL = render_template("/".join([self.sql_template_path,
+ self._PROPERTIES_SQL]),
+ pkgid=pkgid, edbfnid=edbfnid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the function in the database.")
+ )
+
+ resp_data = res['rows'][0]
+
+ # Get formatted Arguments
+ frmtd_params, frmtd_proargs = self._format_arguments_from_db(resp_data)
+ resp_data.update(frmtd_params)
+ resp_data.update(frmtd_proargs)
+
+ return ajax_response(
+ response=resp_data,
+ status=200
+ )
+
+ def _format_arguments_from_db(self, data):
+ """
+ Create Argument list of the Function.
+
+ Args:
+ data: Function Data
+
+ Returns:
+ Function Arguments in the following format.
+ [
+ {'proargtypes': 'integer', 'proargmodes: 'IN',
+ 'proargnames': 'column1', 'proargdefaultvals': 1}, {...}
+ ]
+ Where
+ Arguments:
+ proargtypes: Argument Types (Data Type)
+ proargmodes: Argument Modes [IN, OUT, INOUT, VARIADIC]
+ proargnames: Argument Name
+ proargdefaultvals: Default Value of the Argument
+ """
+ proargtypes = [ptype for ptype in data['proargtypenames'].split(",")] \
+ if data['proargtypenames'] else []
+ proargmodes = data['proargmodes'] if data['proargmodes'] else []
+ proargnames = data['proargnames'] if data['proargnames'] else []
+ proargdefaultvals = [ptype for ptype in
+ data['proargdefaultvals'].split(",")] \
+ if data['proargdefaultvals'] else []
+
+ proargmodenames = {'i': 'IN', 'o': 'OUT', 'b': 'INOUT',
+ 'v': 'VARIADIC', 't': 'TABLE'}
+
+ # EPAS explicitly converts OUT to INOUT, So we always have proargtypes
+
+ proargmodes_fltrd = copy.deepcopy(proargmodes)
+ proargnames_fltrd = []
+ cnt = 0
+ for m in proargmodes:
+ if m in ['v', 'o']: # Out / Variadic Mode
+ proargdefaultvals.insert(cnt, '')
+ elif m == 't': # Table Mode
+ proargmodes_fltrd.remove(m)
+ proargnames_fltrd.append(proargnames[cnt])
+
+ cnt += 1
+
+ cnt = 0
+ # Map param's short form to its actual name. (ex: 'i' to 'IN')
+ for m in proargmodes_fltrd:
+ proargmodes_fltrd[cnt] = proargmodenames[m]
+ cnt += 1
+
+ # Removes Argument Names from the list if that argument is removed
+ # from the list
+ for i in proargnames_fltrd:
+ proargnames.remove(i)
+
+ # Insert null value against the parameters which do not have
+ # default values.
+ dif = len(proargmodes_fltrd) - len(proargdefaultvals)
+ while dif > 0:
+ proargdefaultvals.insert(0, '')
+ dif -= 1
+
+ def list_get(arr, index, default=''):
+ return arr[index] if len(arr) > index else default
+
+ # Prepare list of Argument list dict to be displayed in the Data Grid.
+ params = {"arguments": [
+ self._map_arguments_dict(
+ i, list_get(proargmodes_fltrd, i),
+ list_get(proargtypes, i),
+ list_get(proargnames, i),
+ list_get(proargdefaultvals, i)
+ )
+ for i in range(len(proargtypes))]}
+
+ # Prepare string formatted Argument to be displayed in the Properties
+ # panel.
+
+ proargs = [self._map_arguments_list(
+ list_get(proargmodes_fltrd, i),
+ list_get(proargtypes, i),
+ list_get(proargnames, i),
+ list_get(proargdefaultvals, i)
+ )
+ for i in range(len(proargtypes))]
+
+ proargs = {"proargs": ", ".join(proargs)}
+
+ return params, proargs
+
+ def _map_arguments_dict(self, argid, argmode, argtype, argname, argdefval):
+ """
+ Returns Dict of formatted Arguments.
+ Args:
+ argid: Argument Sequence Number
+ argmode: Argument Mode
+ argname: Argument Name
+ argtype: Argument Type
+ argdef: Argument Default Value
+ """
+ # The pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) SQL
+ # statement gives us '-' as a default value for INOUT mode.
+ # so, replacing it with empty string.
+ if argmode == 'INOUT' and argdefval.strip() == '-':
+ argdefval = ''
+
+ return {"argid": argid,
+ "argtype": argtype.strip() if argtype is not None else '',
+ "argmode": argmode,
+ "argname": argname,
+ "argdefval": argdefval}
+
+ def _map_arguments_list(self, argmode, argtype, argname, argdef):
+ """
+ Returns List of formatted Arguments.
+ Args:
+ argmode: Argument Mode
+ argname: Argument Name
+ argtype: Argument Type
+ argdef: Argument Default Value
+ """
+ # The pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) SQL
+ # statement gives us '-' as a default value for INOUT mode.
+ # so, replacing it with empty string.
+ if argmode == 'INOUT' and argdef.strip() == '-':
+ argdef = ''
+
+ arg = ''
+
+ if argmode:
+ arg += argmode + " "
+ if argname:
+ arg += argname + " "
+ if argtype:
+ arg += argtype + " "
+ if argdef:
+ arg += " DEFAULT " + argdef
+
+ return arg.strip(" ")
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, pkgid, edbfnid=None):
+ """
+ Returns the SQL for the Function object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ fnid: Function Id
+ """
+ SQL = render_template(
+ "/".join([self.sql_template_path, 'get_body.sql']),
+ edbfnid=edbfnid)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the function in the database.")
+ )
+
+ body = res['rows'][0]['funcdef']
+
+ if body is None:
+ body = ''
+
+ SQL = render_template("/".join([self.sql_template_path,
+ 'get_name.sql']),
+ edbfnid=edbfnid)
+
+ status, name = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = "-- Package {}: {}".format(
+ 'Function' if self.node_type == 'edbfunc' else 'Procedure',
+ name)
+ if body != '':
+ sql += "\n\n"
+ sql += body
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, pkgid, edbfnid):
+ """
+ This function get the dependents and return ajax response
+ for the Function node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Function Id
+ """
+ dependents_result = self.get_dependents(self.conn, edbfnid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, pkgid, edbfnid):
+ """
+ This function get the dependencies and return ajax response
+ for the Function node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ doid: Function Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, edbfnid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @staticmethod
+ def get_inner(sql):
+ if sql is None:
+ return None
+ start = 0
+ start_position = re.search(r"\s+[is|as]+\s+", sql, flags=re.I)
+
+ if start_position:
+ start = start_position.start() + 4
+
+ try:
+ end_position = [i for i in re.finditer("end", sql, flags=re.I)][-1]
+ end = end_position.start()
+ except IndexError:
+ return sql[start:].strip("\n")
+
+ return sql[start:end].strip("\n")
+
+
+EdbFuncView.register_node_view(blueprint)
+
+
+class EdbProcModule(CollectionNodeModule):
+ """
+ class EdbProcModule(CollectionNodeModule):
+
+ This class represents The Procedures Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Procedures Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Procedures collection node.
+
+ * node_inode():
+ - Returns Procedures node as leaf node.
+
+ * script_load()
+ - Load the module script for Procedures, when schema node is
+ initialized.
+
+ """
+
+ _NODE_TYPE = 'edbproc'
+ _COLLECTION_LABEL = gettext("Procedures")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Procedure Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = 90100
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def get_nodes(self, gid, sid, did, scid, pkgid):
+ """
+ Generate Procedures collection node.
+ """
+ yield self.generate_browser_collection_node(pkgid)
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Procedures, when the
+ database node is initialized.
+ """
+ return packages.PackageModule.node_type
+
+ def register_preferences(self):
+ """
+ Register preferences for this module.
+ """
+ # Add the node informaton for browser, not in respective
+ # node preferences
+ self.browser_preference = Preferences.module('browser')
+ self.pref_show_system_objects = self.browser_preference.preference(
+ 'show_system_objects'
+ )
+ self.pref_show_node = self.browser_preference.register(
+ 'node', 'show_node_' + self.node_type,
+ gettext('Package {0}').format(self.label), 'node',
+ self.SHOW_ON_BROWSER, category_label=gettext('Nodes')
+ )
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+procedure_blueprint = EdbProcModule(__name__)
+
+
+class EdbProcView(EdbFuncView):
+ node_type = procedure_blueprint.node_type
+
+
+EdbProcView.register_node_view(procedure_blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/css/edbfunc.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/css/edbfunc.css
new file mode 100644
index 0000000000000000000000000000000000000000..16b2e71987106c57a2ba59e1f8aaa3b2df9a8eb3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/css/edbfunc.css
@@ -0,0 +1,3 @@
+.functions_code {
+ height: 130px !important;
+}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbfunc.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbfunc.svg
new file mode 100644
index 0000000000000000000000000000000000000000..0600aa1e3eeb6048f4b36f8f5393ca9163136ec8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbfunc.svg
@@ -0,0 +1 @@
+coll-edbfunc
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbproc.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbproc.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f389883223caaabc043044adfb0f0f7da2bdf5a3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/coll-edbproc.svg
@@ -0,0 +1 @@
+coll-edbproc
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbfunc.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbfunc.svg
new file mode 100644
index 0000000000000000000000000000000000000000..c2de7148db3f95bee3be44c5906bf4ddde98afa1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbfunc.svg
@@ -0,0 +1 @@
+edbfunc
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbproc.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbproc.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b18047388ecfa095cf6ab49fc3d971e32f9617d6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/img/edbproc.svg
@@ -0,0 +1 @@
+edbproc
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.js
new file mode 100644
index 0000000000000000000000000000000000000000..747ab664636a668caf6d8c2e2db8158994bde8ef
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.js
@@ -0,0 +1,63 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import EDBFuncSchema from './edbfunc.ui';
+
+/* Create and Register Function Collection and Node. */
+define('pgadmin.node.edbfunc', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgBrowser) {
+
+ if (!pgBrowser.Nodes['coll-edbfunc']) {
+ pgBrowser.Nodes['coll-edbfunc'] =
+ pgBrowser.Collection.extend({
+ node: 'edbfunc',
+ label: gettext('Functions'),
+ type: 'coll-edbfunc',
+ columns: ['name', 'funcowner', 'description'],
+ canDrop: false,
+ canDropCascade: false,
+ });
+ }
+
+ if (!pgBrowser.Nodes['edbfunc']) {
+ pgBrowser.Nodes['edbfunc'] = pgBrowser.Node.extend({
+ type: 'edbfunc',
+ dialogHelp: url_for('help.static', {'filename': 'edbfunc_dialog.html'}),
+ label: gettext('Function'),
+ collection_type: 'coll-edbfunc',
+ hasDepends: true,
+ canEdit: false,
+ hasSQL: true,
+ hasScriptTypes: [],
+ parent_type: ['package'],
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ },
+ canDrop: false,
+ canDropCascade: false,
+ getSchema: () => {
+ return new EDBFuncSchema(
+ {}, {
+ name: 'sysfunc'
+ }
+ );
+ }
+ });
+
+ }
+
+ return pgBrowser.Nodes['edbfunc'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..7a7a6e6c9ba173ad821864be81eef8d084bb85b3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbfunc.ui.js
@@ -0,0 +1,83 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class EDBFuncSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ funcowner: undefined,
+ pronargs: undefined, /* Argument Count */
+ proargs: undefined, /* Arguments */
+ proargtypenames: undefined, /* Argument Signature */
+ prorettypename: undefined, /* Return Type */
+ lanname: 'sql', /* Language Name in which function is being written */
+ prosrc: undefined,
+ proacl: undefined,
+ visibility: 'Unknown',
+ warn_text: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ ...fieldOptions
+ };
+ }
+
+ isVisible(state) {
+ return state.name == 'sysfunc' || state.name == 'sysproc';
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'funcowner', label: gettext('Owner'), cell: 'string',
+ type: 'text', readonly: true,
+ },{
+ id: 'pronargs', label: gettext('Argument count'), cell: 'string',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'proargs', label: gettext('Arguments'), cell: 'string',
+ type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'proargtypenames', label: gettext('Signature arguments'), cell:
+ 'string', type: 'text', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'prorettypename', label: gettext('Return type'), cell: 'string',
+ type: 'text', group: gettext('Definition'),
+ mode: ['properties'], visible: (state) => this.isVisible(state),
+ },{
+ id: 'visibility', label: gettext('Visibility'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'lanname', label: gettext('Language'), cell: 'string',
+ type: 'text', group: gettext('Definition'), readonly: true,
+ },{
+ id: 'prosrc', label: gettext('Code'), cell: 'string',
+ mode: ['properties'],
+ group: gettext('Code'),
+ type: 'sql', isFullTab: true,
+ visible: function(state) {
+ return state.lanname !== 'c';
+ },
+ disabled: true,
+ }];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbproc.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbproc.js
new file mode 100644
index 0000000000000000000000000000000000000000..24fee54ce38f437bff54303a77b4ad145b98d2bc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/static/js/edbproc.js
@@ -0,0 +1,68 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import EDBFuncSchema from './edbfunc.ui';
+
+/* Create and Register Procedure Collection and Node. */
+define('pgadmin.node.edbproc', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser
+) {
+
+ if (!pgBrowser.Nodes['coll-edbproc']) {
+ pgAdmin.Browser.Nodes['coll-edbproc'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'edbproc',
+ label: gettext('Procedures'),
+ type: 'coll-edbproc',
+ columns: ['name', 'funcowner', 'description'],
+ hasStatistics: true,
+ canDrop: false,
+ canDropCascade: false,
+ });
+ }
+
+ // Inherit Functions Node
+ if (!pgBrowser.Nodes['edbproc']) {
+ pgAdmin.Browser.Nodes['edbproc'] = pgBrowser.Node.extend({
+ type: 'edbproc',
+ dialogHelp: url_for('help.static', {'filename': 'edbproc_dialog.html'}),
+ label: gettext('Procedure'),
+ collection_type: 'coll-edbproc',
+ hasDepends: true,
+ canEdit: false,
+ hasSQL: true,
+ hasScriptTypes: [],
+ parent_type: ['package'],
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.proc_initialized)
+ return;
+
+ this.proc_initialized = true;
+
+ },
+ canDrop: false,
+ canDropCascade: false,
+ getSchema: () => {
+ return new EDBFuncSchema(
+ {}, {
+ name: 'sysproc'
+ }
+ );
+ }
+ });
+
+ }
+
+ return pgBrowser.Nodes['edbproc'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fdf0fce5b00f25f5f77e3161e23a001c9f2603b9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind IN ('f', 'w')
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..78572e40cfdfd350ce499367822cc5bc1f77ec7a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/11_plus/properties.sql
@@ -0,0 +1,27 @@
+SELECT pg_proc.oid,
+ proname AS name,
+ pronargs,
+ proallargtypes,
+ proargnames AS argnames,
+ pronargdefaults,
+ pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ proargdeclaredmodes AS proargmodes,
+ proargnames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner,
+ pg_catalog.pg_get_function_result(pg_proc.oid) AS prorettypename,
+ prosrc,
+ lanname,
+ CASE
+ WHEN proaccess = '+' THEN 'Public'
+ WHEN proaccess = '-' THEN 'Private'
+ ELSE 'Unknown' END AS visibility
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace, pg_catalog.pg_language lng
+WHERE prokind IN ('f', 'w')
+AND pronamespace = {{pkgid}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
+AND lng.oid=prolang
+{% if edbfnid %}
+AND pg_proc.oid = {{edbfnid}}::oid
+{% endif %}
+ ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_body.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_body.sql
new file mode 100644
index 0000000000000000000000000000000000000000..822d22d7ef468af844dd438fbdbe0846e1bf5cbb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_body.sql
@@ -0,0 +1 @@
+SELECT pg_catalog.pg_get_functiondef({{edbfnid}}::oid) AS funcdef;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..003d8e8f75b860b0756d9eabf0d5b0d0d1252f3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_name.sql
@@ -0,0 +1,3 @@
+SELECT proname AS name
+FROM pg_catalog.pg_proc
+WHERE oid = {{edbfnid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e63cda3fd99ae0123e0500f97af5e695f2cd7197
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d42b5b161700d3ecfae2ac650c09689c0f20964
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/node.sql
@@ -0,0 +1,10 @@
+SELECT pg_proc.oid,
+ pg_proc.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pg_proc.oid), '') || ')' AS name,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace
+WHERE protype = '0'::char
+{% if fnid %}
+AND pg_proc.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+AND pronamespace = {{pkgid|qtLiteral(conn)}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..250115238ae6eab47583c55140a84c351919f4ee
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/properties.sql
@@ -0,0 +1,27 @@
+SELECT pg_proc.oid,
+ proname AS name,
+ pronargs,
+ proallargtypes,
+ proargnames AS argnames,
+ pronargdefaults,
+ pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ proargdeclaredmodes AS proargmodes,
+ proargnames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner,
+ pg_catalog.pg_get_function_result(pg_proc.oid) AS prorettypename,
+ prosrc,
+ lanname,
+ CASE
+ WHEN proaccess = '+' THEN 'Public'
+ WHEN proaccess = '-' THEN 'Private'
+ ELSE 'Unknown' END AS visibility
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace, pg_catalog.pg_language lng
+WHERE protype = '0'::char
+AND pronamespace = {{pkgid}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
+AND lng.oid=prolang
+{% if edbfnid %}
+AND pg_proc.oid = {{edbfnid}}::oid
+{% endif %}
+ ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbfuncs/ppas/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c4a2cca4a17773ec3d39d4bfd35e60d9a88b281a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ pr.prokind = 'p'
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f25b0af1e2097c5e9e6328508dacdb10ad457c0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/11_plus/properties.sql
@@ -0,0 +1,27 @@
+SELECT pg_proc.oid,
+ proname AS name,
+ pronargs,
+ proallargtypes,
+ proargnames AS argnames,
+ pronargdefaults,
+ pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ proargdeclaredmodes AS proargmodes,
+ proargnames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner,
+ pg_catalog.pg_get_function_result(pg_proc.oid) AS prorettypename,
+ prosrc,
+ lanname,
+ CASE
+ WHEN proaccess = '+' THEN 'Public'
+ WHEN proaccess = '-' THEN 'Private'
+ ELSE 'Unknown' END AS visibility
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace, pg_catalog.pg_language lng
+WHERE prokind = 'p'
+AND pronamespace = {{pkgid}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
+AND lng.oid=prolang
+{% if edbfnid %}
+AND pg_proc.oid = {{edbfnid}}::oid
+{% endif %}
+ ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_body.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_body.sql
new file mode 100644
index 0000000000000000000000000000000000000000..822d22d7ef468af844dd438fbdbe0846e1bf5cbb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_body.sql
@@ -0,0 +1 @@
+SELECT pg_catalog.pg_get_functiondef({{edbfnid}}::oid) AS funcdef;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..003d8e8f75b860b0756d9eabf0d5b0d0d1252f3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_name.sql
@@ -0,0 +1,3 @@
+SELECT proname AS name
+FROM pg_catalog.pg_proc
+WHERE oid = {{edbfnid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e63cda3fd99ae0123e0500f97af5e695f2cd7197
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_oid.sql
@@ -0,0 +1,17 @@
+SELECT
+ pr.oid, pr.proname || '(' || COALESCE(pg_catalog
+ .pg_get_function_identity_arguments(pr.oid), '') || ')' as name,
+ lanname, pg_catalog.pg_get_userbyid(proowner) as funcowner
+FROM
+ pg_catalog.pg_proc pr
+JOIN
+ pg_catalog.pg_type typ ON typ.oid=prorettype
+JOIN
+ pg_catalog.pg_language lng ON lng.oid=prolang
+JOIN
+ pg_catalog.pg_namespace nsp ON nsp.oid=pr.pronamespace
+ AND nsp.nspname={{ nspname|qtLiteral(conn) }}
+WHERE
+ proisagg = FALSE
+ AND typname NOT IN ('trigger', 'event_trigger')
+ AND pr.proname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ba6bcbe43233e68e5ceb909dc9253c37e15423e5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/node.sql
@@ -0,0 +1,10 @@
+SELECT pg_proc.oid,
+ pg_proc.proname || '(' || COALESCE(pg_catalog.pg_get_function_identity_arguments(pg_proc.oid), '') || ')' AS name,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace
+WHERE protype = '1'::char
+{% if fnid %}
+AND pg_proc.oid = {{ fnid|qtLiteral(conn) }}
+{% endif %}
+AND pronamespace = {{pkgid|qtLiteral(conn)}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3e8f434b5fbf35bc89309a695b0292b0a2f92125
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/properties.sql
@@ -0,0 +1,27 @@
+SELECT pg_proc.oid,
+ proname AS name,
+ pronargs,
+ proallargtypes,
+ proargnames AS argnames,
+ pronargdefaults,
+ pg_catalog.oidvectortypes(proargtypes) AS proargtypenames,
+ proargmodes,
+ proargnames,
+ pg_catalog.pg_get_expr(proargdefaults, 'pg_catalog.pg_class'::regclass) AS proargdefaultvals,
+ pg_catalog.pg_get_userbyid(proowner) AS funcowner,
+ pg_catalog.pg_get_function_result(pg_proc.oid) AS prorettypename,
+ prosrc,
+ lanname,
+ CASE
+ WHEN proaccess = '+' THEN 'Public'
+ WHEN proaccess = '-' THEN 'Private'
+ ELSE 'Unknown' END AS visibility
+FROM pg_catalog.pg_proc, pg_catalog.pg_namespace, pg_catalog.pg_language lng
+WHERE protype = '1'::char
+AND pronamespace = {{pkgid}}::oid
+AND pg_proc.pronamespace = pg_namespace.oid
+AND lng.oid=prolang
+{% if edbfnid %}
+AND pg_proc.oid = {{edbfnid}}::oid
+{% endif %}
+ ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e4b99e467eaa3d5643c5c07f64aca0e0ca2beba0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbfuncs/templates/edbprocs/ppas/default/stats.sql
@@ -0,0 +1,8 @@
+SELECT
+ calls AS {{ conn|qtIdent(_('Number of calls')) }},
+ total_time AS {{ conn|qtIdent(_('Total time')) }},
+ self_time AS {{ conn|qtIdent(_('Self time')) }}
+FROM
+ pg_catalog.pg_stat_user_functions
+WHERE
+ funcid = {{fnid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1bc5f543103168b3ac1c898fbbbe8e5ea6dcab1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/__init__.py
@@ -0,0 +1,329 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Edb Functions/Edb Procedures Node."""
+
+from functools import wraps
+
+from flask import render_template, make_response
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers.databases.schemas import packages
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ DataTypeReader
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, \
+ make_response as ajax_response, internal_server_error, gone
+from pgadmin.utils.ajax import precondition_required
+from pgadmin.utils.driver import get_driver
+
+
+class EdbVarModule(CollectionNodeModule):
+ """
+ class EdbvarModule(CollectionNodeModule):
+
+ This class represents The Functions Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Functions Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Functions collection node.
+
+ * node_inode():
+ - Returns Functions node as leaf node.
+
+ * script_load()
+ - Load the module script for Functions, when schema node is
+ initialized.
+
+ * csssnippets()
+ - Returns a snippet of css.
+ """
+
+ _NODE_TYPE = 'edbvar'
+ _COLLECTION_LABEL = gettext("Variables")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the Variable Module.
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+
+ self.min_ver = 90100
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def get_nodes(self, gid, sid, did, scid, pkgid):
+ """
+ Generate Functions collection node.
+ """
+ yield self.generate_browser_collection_node(pkgid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for Functions, when the
+ package node is initialized.
+ """
+ return packages.PackageModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Make the node as leaf node.
+ Returns:
+ False as this node doesn't have child nodes.
+ """
+ return False
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = EdbVarModule(__name__)
+
+
+class EdbVarView(PGChildNodeView, DataTypeReader):
+ """
+ class EdbFuncView(PGChildNodeView, DataTypeReader)
+
+ This class inherits PGChildNodeView and DataTypeReader to get the different
+ routes for
+ the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Functions.
+
+ Methods:
+ -------
+ * validate_request(f):
+ - Works as a decorator.
+ Validating request on the request of create, update and modified SQL.
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid, pkgid):
+ - List the Functions.
+
+ * nodes(gid, sid, did, scid, pkgid):
+ - Returns all the Functions to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, pkgid, varid):
+ - Returns the Functions properties.
+
+ * sql(gid, sid, did, scid, pkgid, varid):
+ - Returns the SQL for the Functions object.
+
+ * compare(**kwargs):
+ - This function will compare the nodes from two different schemas.
+ """
+
+ node_type = blueprint.node_type
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'pkgid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'varid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties'},
+ {'get': 'list'}
+ ],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}]
+ })
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks the database connection status.
+ Attaches the connection object and template path to the class object.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+
+ # Get database connection
+ self.conn = self.manager.connection(did=kwargs['did'])
+
+ self.qtIdent = driver.qtIdent
+ self.qtLiteral = driver.qtLiteral
+
+ if not self.conn.connected():
+ return precondition_required(
+ gettext(
+ "Connection to the server has been lost."
+ )
+ )
+
+ self.sql_template_path = "/edbvars/ppas"
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, pkgid):
+ """
+ List all the Functions.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ pkgid: Package Id
+ """
+
+ SQL = render_template("/".join([self.sql_template_path,
+ self._NODE_SQL]),
+ pkgid=pkgid,
+ conn=self.conn)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, pkgid):
+ """
+ Returns all the Functions to generate the Nodes.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ pkgid: Package Id
+ """
+
+ res = []
+ SQL = render_template(
+ "/".join([self.sql_template_path, self._NODE_SQL]),
+ pkgid=pkgid, conn=self.conn
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ pkgid,
+ row['name'],
+ icon="icon-" + self.node_type
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, pkgid, varid=None):
+ """
+ Returns the Function properties.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ pkgid: Package Id
+ varid: Variable Id
+ """
+ resp_data = {}
+ SQL = render_template("/".join([self.sql_template_path,
+ self._PROPERTIES_SQL]),
+ pkgid=pkgid, varid=varid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(
+ errormsg=gettext("Could not find the variables")
+ )
+
+ resp_data = res['rows'][0]
+
+ return ajax_response(
+ response=resp_data,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, pkgid, varid=None):
+ """
+ Returns the SQL for the Function object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ pkgid: Package Id
+ varid: variable Id
+ """
+ SQL = render_template(
+ "/".join([self.sql_template_path, self._PROPERTIES_SQL]),
+ varid=varid,
+ pkgid=pkgid)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ errormsg=gettext("Could not find the variables")
+ )
+
+ var = res['rows'][0]
+
+ sql = "-- Package Variable: {}".format(var['name'])
+ sql += "\n\n"
+ sql += "{} {};".format(var['name'], var['datatype'])
+
+ return ajax_response(response=sql)
+
+
+EdbVarView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/coll-edbvar.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/coll-edbvar.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f21224417f38a57ab0f1c8242fbe21931baf9519
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/coll-edbvar.svg
@@ -0,0 +1 @@
+coll-edbvar
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/edbvar.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/edbvar.svg
new file mode 100644
index 0000000000000000000000000000000000000000..a6da7d1275bc42be55436c12a07591020e4d6cf8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/img/edbvar.svg
@@ -0,0 +1 @@
+edbvar
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.js
new file mode 100644
index 0000000000000000000000000000000000000000..0067123cb9555c567ebbe4123723d1841b0cddf3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.js
@@ -0,0 +1,58 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import EDBVarSchema from './edbvar.ui';
+
+/* Create and Register Function Collection and Node. */
+define('pgadmin.node.edbvar', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgBrowser) {
+
+ if (!pgBrowser.Nodes['coll-edbvar']) {
+ pgBrowser.Nodes['coll-edbvar'] =
+ pgBrowser.Collection.extend({
+ node: 'edbvar',
+ label: gettext('Variables'),
+ type: 'coll-edbvar',
+ columns: ['name', 'funcowner', 'description'],
+ canDrop: false,
+ canDropCascade: false,
+ });
+ }
+
+ if (!pgBrowser.Nodes['edbvar']) {
+ pgBrowser.Nodes['edbvar'] = pgBrowser.Node.extend({
+ type: 'edbvar',
+ dialogHelp: url_for('help.static', {'filename': 'edbvar_dialog.html'}),
+ label: gettext('Function'),
+ collection_type: 'coll-edbvar',
+ canEdit: false,
+ hasSQL: true,
+ hasScriptTypes: [],
+ parent_type: ['package'],
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ },
+ canDrop: false,
+ canDropCascade: false,
+ getSchema: () => {
+ return new EDBVarSchema();
+ }
+ });
+
+ }
+
+ return pgBrowser.Nodes['edbvar'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..58fd2b37c3171d6789c50e64d2dfe60a7763e7b1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/static/js/edbvar.ui.js
@@ -0,0 +1,46 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class EDBVarSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ datatype: undefined,
+ visibility: 'Unknown',
+ ...initValues
+ });
+ this.fieldOptions = {
+ ...fieldOptions
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'datatype', label: gettext('Data type'), cell: 'string',
+ type: 'text', readonly: true,
+ },{
+ id: 'visibility', label: gettext('Visibility'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ }];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/node.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/node.sql
new file mode 100644
index 0000000000000000000000000000000000000000..09c69262c5d04dfe8720b2b7f7fecbc54b167c74
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/node.sql
@@ -0,0 +1,8 @@
+SELECT oid,
+ varname AS name
+FROM pg_catalog.edb_variable
+WHERE varpackage = {{pkgid}}::oid
+{% if varid %}
+AND oid = {{ varid|qtLiteral(conn) }}
+{% endif %}
+ORDER BY varname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..650882e914a983292c35be04ebe3c407f940f446
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/edbvars/templates/edbvars/ppas/properties.sql
@@ -0,0 +1,13 @@
+SELECT oid,
+ varname AS name,
+ pg_catalog.format_type(vartype, NULL) as datatype,
+ CASE
+ WHEN varaccess = '+' THEN 'Public'
+ WHEN varaccess = '-' THEN 'Private'
+ ELSE 'Unknown' END AS visibility
+FROM pg_catalog.edb_variable
+WHERE varpackage = {{pkgid}}::oid
+{% if varid %}
+AND oid = {{varid}}
+{% endif %}
+ORDER BY varname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/coll-package.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/coll-package.svg
new file mode 100644
index 0000000000000000000000000000000000000000..770549683d7ea79d76da316bd3a5a83135d78d51
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/coll-package.svg
@@ -0,0 +1 @@
+coll-package
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/package.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/package.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b3bae4f3e4d98908d25eb977ae8a2978e3496a87
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/img/package.svg
@@ -0,0 +1 @@
+package
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.js
new file mode 100644
index 0000000000000000000000000000000000000000..948e053be5bfe303c5e1a808f708b37aeda04ad3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.js
@@ -0,0 +1,108 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import PackageSchema from './package.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import { getNodeListByName } from '../../../../../../../static/js/node_ajax';
+
+
+define('pgadmin.node.package', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode) {
+
+ // Extend the browser's collection class for package collection
+ if (!pgBrowser.Nodes['coll-package']) {
+ pgBrowser.Nodes['coll-package'] =
+ pgBrowser.Collection.extend({
+ node: 'package',
+ label: gettext('Packages'),
+ type: 'coll-package',
+ columns: ['name' ,'owner', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the browser's node class for package node
+ if (!pgBrowser.Nodes['package']) {
+ pgBrowser.Nodes['package'] = schemaChild.SchemaChildNode.extend({
+ type: 'package',
+ epasHelp: true,
+ dialogHelp: url_for('help.static', {'filename': 'package_dialog.html'}),
+ label: gettext('Package'),
+ collection_type: 'coll-package',
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_package_on_coll', node: 'coll-package', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Package...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_package', node: 'package', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Package...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_package', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Package...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },
+ ]);
+
+ },
+ canCreate: function(itemData, item, data) {
+ //If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ if (server && server.server_type === 'pg')
+ return false;
+
+ // If it is catalog then don't allow user to create package
+ return treeData['catalog'] == undefined;
+ },
+ getSchema: (treeNodeInfo, itemNodeData) => {
+ let nodeObj = pgBrowser.Nodes['package'];
+ return new PackageSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(nodeObj, treeNodeInfo, itemNodeData, privileges),
+ {
+ schemas:() => getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ node_info: treeNodeInfo
+ }, {
+ schema: ('schema' in treeNodeInfo)? treeNodeInfo.schema.label : ''
+ }
+ );
+ }
+ });
+ }
+
+ return pgBrowser.Nodes['package'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..5f19ec3290bfe97a217943e4de2f307bf36c8283
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/static/js/package.ui.js
@@ -0,0 +1,154 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { isEmptyString } from 'sources/validators';
+
+export default class PackageSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, fieldOptions = {}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ owner: undefined,
+ is_sys_object: undefined,
+ description: undefined,
+ pkgheadsrc: undefined,
+ pkgbodysrc: undefined,
+ acl: undefined,
+ pkgacl: [],
+ warn_text: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ schemas: [],
+ ...fieldOptions
+ };
+ this.warningText = null;
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let packageSchemaObj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', mode: ['properties', 'create', 'edit'], noEmpty: true,
+ readonly: function (state) {
+ return !packageSchemaObj.isNew(state);
+ },
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'owner', label: gettext('Owner'), cell: 'string',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ readonly: true, editable: false,
+ visible: function (state) {
+ return !packageSchemaObj.isNew(state);
+ },
+ },{
+ id: 'schema', label: gettext('Schema'), node: 'schema',
+ readonly: function (state) {
+ return !packageSchemaObj.isNew(state);
+ }, noEmpty: true,
+ type: (state) => {
+ return {
+ type: 'select',
+ options: packageSchemaObj.fieldOptions.schemas,
+ optionsLoaded: (options) => { packageSchemaObj.fieldOptions.schemas = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ let res = [];
+ if (state && packageSchemaObj.isNew(state)) {
+ options.forEach((option) => {
+ // If schema name start with pg_* then we need to exclude them
+ if(option?.label.match(/^pg_/)) {
+ return;
+ }
+ res.push({ label: option.label, value: option.value, image: 'icon-schema' });
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ }
+ },{
+ id: 'is_sys_object', label: gettext('System package?'),
+ cell:'boolean', type: 'switch',mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), type: 'multiline',
+ mode: ['properties', 'create', 'edit'],
+ },{
+ id: 'pkgheadsrc',
+ type: 'sql', isFullTab: true, cell: 'text',
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Header'),
+ depChange: (state, source, topState, actionObj) => {
+
+ if(packageSchemaObj._origData.oid && state.pkgheadsrc != actionObj.oldState.pkgheadsrc) {
+ packageSchemaObj.warningText = gettext(
+ 'Updating the package header definition may remove its existing body.'
+ ) + '' + gettext('Do you want to continue?') +
+ ' ';
+ }
+ else {
+ packageSchemaObj.warningText = null;
+ }
+ }
+ },{
+ id: 'pkgbodysrc',
+ type: 'sql', isFullTab: true, cell: 'text',
+ mode: ['properties', 'create', 'edit'], group: gettext('Body'),
+ depChange: (state, source, topState, actionObj) => {
+
+ if(packageSchemaObj._origData.oid && state.pkgbodysrc != actionObj.oldState.pkgbodysrc) {
+ packageSchemaObj.warningText = gettext(
+ 'Updating the package header definition may remove its existing body.'
+ ) + '' + gettext('Do you want to continue?') +
+ ' ';
+ }
+ else {
+ packageSchemaObj.warningText = null;
+ }
+ }
+ },{
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'pkgacl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['X']),
+ uniqueCol : ['grantee', 'grantor'], editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+ /* code validation */
+ if (isEmptyString(state.pkgheadsrc)) {
+ errmsg = gettext('Header cannot be empty.');
+ setError('pkgheadsrc', errmsg);
+ return true;
+ } else {
+ setError('pkgheadsrc', null);
+ }
+ return null;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7aa6fe79c30e749d1b5be4290ca2970266032ed2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/count.sql
@@ -0,0 +1,6 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE nspparent = {{scid}}::oid
+AND nspobjecttype = 0
+AND nspcompoundtrigger = false
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0112d29eaa71e10bb5ec09ca07cc057cee66823b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/12_plus/nodes.sql
@@ -0,0 +1,16 @@
+SELECT
+ nsp.oid, nspname AS name, des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE nspparent = {{scid}}::oid
+{% if pkgid %}
+AND nsp.oid = {{pkgid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = nsp.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+AND nspobjecttype = 0
+AND nspcompoundtrigger = false
+ORDER BY nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4dd0185fbf5f404667e3b2fa7e758aeaea78bf79
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/acl.sql
@@ -0,0 +1,36 @@
+SELECT 'pkgacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT nspacl
+ FROM pg_catalog.pg_namespace
+ WHERE nspparent = {{scid}}::oid
+ AND oid = {{pkgid}}::oid
+ AND nspobjecttype = 0
+ ) acl,
+ (SELECT (d).grantee AS grantee, (d).grantor AS grantor, (d).is_grantable
+ AS is_grantable, (d).privilege_type AS privilege_type FROM (SELECT pg_catalog.aclexplode(nspacl) as d FROM pg_catalog.pg_namespace
+ WHERE nspparent = {{scid}}::oid
+ AND oid = {{pkgid}}::oid
+ AND nspobjecttype = 0) a ORDER BY privilege_type) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d82347a3bb3936e5ce2b47478b090eaaa489f773
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/count.sql
@@ -0,0 +1,5 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE nspparent = {{scid}}::oid
+AND nspobjecttype = 0;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c56925d3d84fa03a236dc5cffafe60b3ce2efb00
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/create.sql
@@ -0,0 +1,25 @@
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+
+{% if data %}
+CREATE OR REPLACE PACKAGE {{ conn|qtIdent(data.schema,data.name) }}
+IS
+{{data.pkgheadsrc}}
+END {{ conn|qtIdent(data.name) }};
+{% if data.pkgbodysrc %}
+
+CREATE OR REPLACE PACKAGE BODY {{ conn|qtIdent(data.schema,data.name) }}
+IS
+{{data.pkgbodysrc}}
+
+END {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.pkgacl %}
+
+{% for priv in data.pkgacl %}
+{{ PRIVILEGE.SET(conn, 'PACKAGE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}{% if data.description %}
+COMMENT ON PACKAGE {{ conn|qtIdent(data.schema,data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c5bb596c8617593ea17c0ba9d877c55d628fab86
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/delete.sql
@@ -0,0 +1 @@
+DROP PACKAGE {{ conn|qtIdent(data.schema,data.name) }}{% if cascade%} CASCADE{% endif %};
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..53a133d546e008261333d8f8d1fb61bd81b8796f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_oid.sql
@@ -0,0 +1,5 @@
+SELECT nsp.oid
+FROM pg_catalog.pg_namespace nsp
+WHERE nspparent = {{scid}}::oid
+AND nspname = {{ name|qtLiteral(conn) }}
+AND nspobjecttype = 0;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d77757ea906817b6458b2ccec1cc45c219fa3a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/get_schema.sql
@@ -0,0 +1,6 @@
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fbc0bb24c6ada4049a21f9869445e6a7d84f8835
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/grant.sql
@@ -0,0 +1,26 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{# Construct sequence name from name and schema #}
+{% set seqname=conn|qtIdent(data.schema, data.name) %}
+{% if data.seqowner %}
+
+ALTER SEQUENCE {{ seqname }}
+ OWNER TO {{ conn|qtIdent(data.seqowner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON SEQUENCE {{ seqname }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% if data.securities %}
+
+{% for r in data.securities %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ead30b1a5d5ace4ee1fdcab06e8ca9bcf6f30c97
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/nodes.sql
@@ -0,0 +1,15 @@
+SELECT
+ nsp.oid, nspname AS name, des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE nspparent = {{scid}}::oid
+{% if pkgid %}
+AND nsp.oid = {{pkgid}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = nsp.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+AND nspobjecttype = 0
+ORDER BY nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b572c8966cab25989f4a1c6eec50894fa9397d93
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/properties.sql
@@ -0,0 +1,18 @@
+SELECT nsp.oid, nsp.xmin, nspname AS name,
+ pg_catalog.edb_get_packagebodydef(nsp.oid) AS pkgbodysrc,
+ pg_catalog.edb_get_packageheaddef(nsp.oid) AS pkgheadsrc,
+ pg_catalog.pg_get_userbyid(nspowner) AS owner,
+ pg_catalog.array_to_string(nsp.nspacl::text[], ', ') as acl,
+ description,
+ CASE
+ WHEN nspname LIKE E'pg\\_%' THEN true
+ ELSE false
+ END AS is_sys_object
+FROM pg_catalog.pg_namespace nsp
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE nspparent = {{scid}}::oid
+{% if pkgid %}
+AND nsp.oid = {{pkgid}}::oid
+{% endif %}
+AND nspobjecttype = 0
+ORDER BY nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d732cd81e705bdea081690356c52ce7a2d304294
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/packages/templates/packages/ppas/default/update.sql
@@ -0,0 +1,48 @@
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+
+{% if data %}
+{% set recreate_pkg_body = false %}
+{% if data.pkgbodysrc is defined and data.pkgbodysrc == '' %}
+{% if is_schema_diff is defined and is_schema_diff != None %}{% set recreate_pkg_body = true %}{% endif %}
+DROP PACKAGE BODY {{ conn|qtIdent(data.schema,data.name) }};
+{% endif %}
+{% if data.pkgheadsrc %}
+
+CREATE OR REPLACE PACKAGE {{ conn|qtIdent(data.schema,data.name) }}
+IS
+{{data.pkgheadsrc}}
+END {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if data.pkgbodysrc or (o_data.pkgbodysrc and recreate_pkg_body) %}
+
+CREATE OR REPLACE PACKAGE BODY {{ conn|qtIdent(data.schema,data.name) }}
+IS
+{% if data.pkgbodysrc %}{{data.pkgbodysrc}}{% else %}{{o_data.pkgbodysrc}}{% endif %}
+
+END {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.pkgacl %}
+{% if 'deleted' in data.pkgacl %}
+{% for priv in data.pkgacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'PACKAGE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.pkgacl %}
+{% for priv in data.pkgacl.changed %}
+{{ PRIVILEGE.UNSETALL(conn, 'PACKAGE', priv.grantee, data.name, data.schema) }}
+{{ PRIVILEGE.SET(conn, 'PACKAGE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.pkgacl %}
+{% for priv in data.pkgacl.added %}
+{{ PRIVILEGE.SET(conn, 'PACKAGE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if data.description is defined %}
+
+COMMENT ON PACKAGE {{ conn|qtIdent(data.schema,data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf91c344097b2f5e87c5e0cc33df546a94eac646
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/__init__.py
@@ -0,0 +1,995 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Sequence Node"""
+
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify
+from flask_babel import gettext as _
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+
+
+class SequenceModule(SchemaChildModule):
+ """
+ class SequenceModule(CollectionNodeModule)
+
+ A module class for Sequence node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the SequenceModule and it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * script_load()
+ - Load the module script for sequence, when any of the database node is
+ initialized.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ """
+
+ _NODE_TYPE = 'sequence'
+ _COLLECTION_LABEL = _("Sequences")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the sequence node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=SequenceView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Override this property to make the node a leaf node.
+
+ Returns: False as this is the leaf node
+ """
+ return False
+
+
+blueprint = SequenceModule(__name__)
+
+
+class SequenceView(PGChildNodeView, SchemaDiffObjectCompare):
+ node_type = blueprint.node_type
+ node_label = "Sequence"
+ node_icon = "icon-%s" % node_type
+ BASE_TEMPLATE_PATH = 'sequences/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'seid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema', 'current_value']
+
+ def check_precondition(action=None):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ def wrap(f):
+ @wraps(f)
+ def wrapped(self, *args, **kwargs):
+
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+
+ if action and action in ["drop"]:
+ self.conn = self.manager.connection()
+ elif 'did' in kwargs:
+ self.conn = self.manager.connection(did=kwargs['did'])
+ else:
+ self.conn = self.manager.connection()
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version
+ )
+ self.acl = ['r', 'w', 'U']
+ self.qtIdent = driver.qtIdent
+
+ return f(self, *args, **kwargs)
+ return wrapped
+ return wrap
+
+ @check_precondition(action='list')
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the sequence nodes within the
+ collection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sequence_nodes = self._get_sequence_nodes(res['rows'])
+ return ajax_response(
+ response=sequence_nodes,
+ status=200
+ )
+
+ @check_precondition(action='nodes')
+ def nodes(self, gid, sid, did, scid, seid=None):
+ """
+ This function is used to create all the child nodes within the
+ collection, Here it will create all the sequence nodes.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ res = []
+ show_internal = False
+ # If show_system_objects is true then no need to hide any sequences.
+ if self.blueprint.show_system_objects:
+ show_internal = True
+
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ scid=scid,
+ seid=seid,
+ show_internal=show_internal,
+ conn=self.conn
+ )
+ status, rset = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if seid is not None:
+ if len(rset['rows']) == 0:
+ return gone(errormsg=self.not_found_error_msg())
+ row = rset['rows'][0]
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['comment']
+
+ ),
+ status=200
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['comment']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def _get_sequence_nodes(self, nodes):
+ """
+ This function is used to iterate through all the sequences node and
+ hiding sequences created as part of an IDENTITY column.
+ :param nodes:
+ :return:
+ """
+ # If show_system_objects is true then no need to hide any sequences.
+ if self.blueprint.show_system_objects:
+ return nodes
+
+ seq_nodes = []
+ for row in nodes:
+ system_seq = self._get_dependency(row['oid'],
+ show_system_objects=True)
+ seq = [dep for dep in system_seq
+ if dep['type'] == 'column' and dep['field'] == 'internal']
+ if len(seq) > 0:
+ continue
+
+ # Append the node into the newly created list
+ seq_nodes.append(row)
+
+ return seq_nodes
+
+ @check_precondition(action='properties')
+ def properties(self, gid, sid, did, scid, seid):
+ """
+ This function will show the properties of the selected sequence node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+
+ Returns:
+
+ """
+ status, res = self._fetch_properties(scid, seid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, seid):
+ """
+ This function is used to fetch the properties of the specified object.
+ :param scid:
+ :param seid:
+ :return:
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, seid=seid
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ for row in res['rows']:
+ sql = render_template(
+ "/".join([self.template_path, 'get_def.sql']),
+ data=row
+ )
+ status, rset1 = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=rset1)
+
+ row['current_value'] = rset1['rows'][0]['last_value']
+ row['minimum'] = rset1['rows'][0]['min_value']
+ row['maximum'] = rset1['rows'][0]['max_value']
+ row['increment'] = rset1['rows'][0]['increment_by']
+ row['start'] = rset1['rows'][0]['start_value']
+ row['cache'] = rset1['rows'][0]['cache_value']
+ row['cycled'] = rset1['rows'][0]['is_cycled']
+
+ self._add_securities_to_row(row)
+
+ sql = render_template(
+ "/".join([self.template_path, self._ACL_SQL]),
+ scid=scid, seid=seid
+ )
+ status, dataclres = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ for row in dataclres['rows']:
+ priv = parse_priv_from_db(row)
+ if row['deftype'] in res['rows'][0]:
+ res['rows'][0][row['deftype']].append(priv)
+ else:
+ res['rows'][0][row['deftype']] = [priv]
+
+ return True, res['rows'][0]
+
+ def _add_securities_to_row(self, row):
+ sec_lbls = []
+ if 'securities' in row and row['securities'] is not None:
+ for sec in row['securities']:
+ import re
+ sec = re.search(r'([^=]+)=(.*$)', sec)
+ sec_lbls.append({
+ 'provider': sec.group(1),
+ 'label': sec.group(2)
+ })
+ row['securities'] = sec_lbls
+
+ @check_precondition(action="create")
+ def create(self, gid, sid, did, scid):
+ """
+ Create the sequence.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+
+ """
+ required_args = [
+ 'name',
+ 'schema',
+ 'seqowner',
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ try:
+ # The SQL below will execute CREATE DDL only
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=e)
+
+ status, msg = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=msg)
+
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)
+
+ # The SQL below will execute rest DMLs because we cannot execute
+ # CREATE with any other
+ sql = render_template(
+ "/".join([self.template_path, self._GRANT_SQL]),
+ data=data, conn=self.conn
+ )
+ sql = sql.strip('\n').strip(' ')
+ if sql and sql != "":
+ status, msg = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=msg)
+
+ # We need oid of newly created sequence.
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ name=data['name'],
+ schema=data['schema'],
+ conn=self.conn
+ )
+ sql = sql.strip('\n').strip(' ')
+
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ row = rset['rows'][0]
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ row['oid'],
+ row['relnamespace'],
+ data['name'],
+ icon=self.node_icon
+ )
+ )
+
+ @check_precondition(action='delete')
+ def delete(self, gid, sid, did, scid, seid=None, only_sql=False):
+ """
+ This function will drop the object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ only_sql: Return SQL only if True
+
+ Returns:
+
+ """
+ if seid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [seid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for seid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, seid=seid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=_(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ sql = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=res['rows'][0], cascade=cascade
+ )
+
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=_("Sequence dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition(action='update')
+ def update(self, gid, sid, did, scid, seid):
+ """
+ This function will update the object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ sql, _ = self.get_SQL(gid, sid, did, data, scid, seid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ seid=seid,
+ conn=self.conn
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+ row = rset['rows'][0]
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ seid,
+ row['schema'],
+ row['name'],
+ icon=self.node_icon,
+ description=row['comment']
+ )
+ )
+
+ @check_precondition(action='msql')
+ def msql(self, gid, sid, did, scid, seid=None):
+ """
+ This function to return modified SQL.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ """
+
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ if seid is None:
+ required_args = [
+ 'name',
+ 'schema'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ sql, _ = self.get_SQL(gid, sid, did, data, scid, seid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ def get_SQL(self, gid, sid, did, data, scid, seid=None,
+ add_not_exists_clause=False):
+ """
+ This function will generate sql from model data.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ """
+
+ required_args = [
+ 'name'
+ ]
+
+ if seid is not None:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, seid=seid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ # Making copy of output for further processing
+ old_data = dict(res['rows'][0])
+ old_data = self._formatter(old_data, scid, seid)
+
+ self._format_privilege_data(data)
+
+ # If name is not present with in update data then copy it
+ # from old data
+ for arg in required_args:
+ if arg not in data:
+ data[arg] = old_data[arg]
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ return sql, data['name'] if 'name' in data else old_data['name']
+ else:
+ # To format privileges coming from client
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)
+
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn,
+ add_not_exists_clause=add_not_exists_clause
+ )
+ sql += render_template(
+ "/".join([self.template_path, self._GRANT_SQL]),
+ data=data, conn=self.conn
+ )
+ return sql, data['name']
+
+ def _format_privilege_data(self, data):
+ # To format privileges data coming from client
+ for key in ['relacl']:
+ if key in data and data[key] is not None:
+ if 'added' in data[key]:
+ data[key]['added'] = parse_priv_to_db(
+ data[key]['added'], self.acl
+ )
+ if 'changed' in data[key]:
+ data[key]['changed'] = parse_priv_to_db(
+ data[key]['changed'], self.acl
+ )
+ if 'deleted' in data[key]:
+ data[key]['deleted'] = parse_priv_to_db(
+ data[key]['deleted'], self.acl
+ )
+
+ @check_precondition(action="sql")
+ def sql(self, gid, sid, did, scid, seid, **kwargs):
+ """
+ This function will generate sql for sql panel
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ json_resp: json response or plain text response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid, seid=seid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ for row in res['rows']:
+ sql = render_template(
+ "/".join([self.template_path, 'get_def.sql']),
+ data=row
+ )
+ status, rset1 = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=rset1)
+
+ row['current_value'] = rset1['rows'][0]['last_value']
+ row['minimum'] = rset1['rows'][0]['min_value']
+ row['maximum'] = rset1['rows'][0]['max_value']
+ row['increment'] = rset1['rows'][0]['increment_by']
+ row['start'] = rset1['rows'][0]['start_value']
+ row['cache'] = rset1['rows'][0]['cache_value']
+ row['cycled'] = rset1['rows'][0]['is_cycled']
+
+ result = res['rows'][0]
+ if target_schema:
+ result['schema'] = target_schema
+
+ result = self._formatter(result, scid, seid)
+ sql, _ = self.get_SQL(gid, sid, did, result, scid,
+ add_not_exists_clause=True)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ # Return sql for schema diff
+ if not json_resp:
+ return sql
+
+ sql_header = """-- SEQUENCE: {0}.{1}\n\n""".format(
+ result['schema'], result['name'])
+
+ sql_header += """-- DROP SEQUENCE IF EXISTS {0};
+
+""".format(self.qtIdent(self.conn, result['schema'], result['name']))
+
+ sql = sql_header + sql
+
+ return ajax_response(response=sql)
+
+ def _formatter(self, data, scid, seid):
+ """
+ Args:
+ data: dict of query result
+ scid: Schema ID
+ seid: Sequence ID
+
+ Returns:
+ It will return formatted output of sequence
+ """
+
+ # Need to format security labels according to client js collection
+ if 'securities' in data and data['securities'] is not None:
+ seclabels = []
+ for seclbls in data['securities']:
+ k, v = seclbls.split('=')
+ seclabels.append({'provider': k, 'label': v})
+
+ data['securities'] = seclabels
+
+ # We need to parse & convert ACL coming from database to json format
+ sql = render_template("/".join([self.template_path, self._ACL_SQL]),
+ scid=scid, seid=seid)
+ status, acl = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ data['relacl'] = []
+
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ data.setdefault(row['deftype'], []).append(priv)
+
+ return data
+
+ @check_precondition(action="dependents")
+ def dependents(self, gid, sid, did, scid, seid):
+ """
+ This function gets the dependents and returns an ajax response
+ for the sequence node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ """
+ dependents_result = self.get_dependents(self.conn, seid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition(action="dependencies")
+ def dependencies(self, gid, sid, did, scid, seid):
+ """
+ This function gets the dependencies and returns an ajax response
+ for the sequence node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ seid: Sequence ID
+ """
+
+ return ajax_response(
+ response=self._get_dependency(seid),
+ status=200
+ )
+
+ def _get_dependency(self, seid, show_system_objects=None):
+ dependencies_result = self.get_dependencies(self.conn, seid, None,
+ show_system_objects)
+
+ # Get missing dependencies.
+ # A Corner case, reported by Guillaume Lelarge, could be found at:
+ # http://archives.postgresql.org/pgadmin-hackers/2009-03/msg00026.php
+
+ sql = render_template("/".join([self.template_path,
+ 'get_dependencies.sql']), seid=seid)
+
+ status, result = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=result)
+
+ for row in result['rows']:
+ ref_name = row['refname']
+ if ref_name is None:
+ continue
+
+ dep_type = ''
+ dep_str = row['deptype']
+ if dep_str == 'a':
+ dep_type = 'auto'
+ elif dep_str == 'n':
+ dep_type = 'normal'
+ elif dep_str == 'i':
+ dep_type = 'internal'
+
+ dependencies_result.append({'type': 'column',
+ 'name': ref_name,
+ 'field': dep_type})
+ return dependencies_result
+
+ @check_precondition(action="stats")
+ def statistics(self, gid, sid, did, scid, seid=None):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ seid: Sequence Id
+
+ Returns the statistics for a particular object if seid is specified
+ """
+ if seid is not None:
+ sql = 'stats.sql'
+ schema_name = None
+ else:
+ sql = 'coll_stats.sql'
+ # Get schema name
+ status, schema_name = self.conn.execute_scalar(
+ render_template(
+ 'schemas/pg/#{0}#/sql/get_name.sql'.format(
+ self.manager.version
+ ),
+ scid=scid,
+ conn=self.conn
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, sql]),
+ conn=self.conn, seid=seid,
+ schema_name=schema_name
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition(action="fetch_objects_to_compare")
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the sequences for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ sql = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True,
+ conn=self.conn)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.get_SQL(gid, sid, did, data, scid, oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, seid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, seid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, seid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, SequenceView)
+SequenceView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/coll-sequence.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/coll-sequence.svg
new file mode 100644
index 0000000000000000000000000000000000000000..9be12471d8331a35f0a34195fd60cce38e898a33
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/coll-sequence.svg
@@ -0,0 +1 @@
+coll-sequence 1 3 ..
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/sequence.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/sequence.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5072a1ca8adecc596c2a98a5a392903a248153cb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/img/sequence.svg
@@ -0,0 +1 @@
+sequence 1 3 ..
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.js
new file mode 100644
index 0000000000000000000000000000000000000000..17c3c0cbaa706bf7e3999029c5e7532d853b05af
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.js
@@ -0,0 +1,105 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import SequenceSchema from './sequence.ui';
+
+define('pgadmin.node.sequence', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ // Extend the browser's collection class for sequence collection
+ if (!pgBrowser.Nodes['coll-sequence']) {
+ pgBrowser.Nodes['coll-sequence'] =
+ pgBrowser.Collection.extend({
+ node: 'sequence',
+ label: gettext('Sequences'),
+ type: 'coll-sequence',
+ columns: ['name', 'seqowner', 'comment'],
+ hasStatistics: true,
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ // Extend the browser's node class for sequence node
+ if (!pgBrowser.Nodes['sequence']) {
+ pgBrowser.Nodes['sequence'] = schemaChild.SchemaChildNode.extend({
+ type: 'sequence',
+ sqlAlterHelp: 'sql-altersequence.html',
+ sqlCreateHelp: 'sql-createsequence.html',
+ dialogHelp: url_for('help.static', {'filename': 'sequence_dialog.html'}),
+ label: gettext('Sequence'),
+ collection_type: 'coll-sequence',
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_sequence_on_coll', node: 'coll-sequence', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Sequence...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_sequence', node: 'sequence', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Sequence...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_sequence', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Sequence...'),
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ },
+ ]);
+
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new SequenceSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {}, (m)=>{
+ // If schema name start with pg_* then we need to exclude them
+ return !(m.label.match(/^pg_/));
+ }),
+ allTables: ()=>getNodeListByName('table', treeNodeInfo, itemNodeData, {includeItemKeys: ['_id']}),
+ getColumns: (params)=>{
+ return getNodeAjaxOptions('get_columns', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData, {urlParams: params, useCache:false}, (rows)=>{
+ return rows.map((r)=>({
+ 'value': r.name,
+ 'image': 'icon-column',
+ 'label': r.name,
+ }));
+ });
+ }
+ },
+ {
+ seqowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: itemNodeData.label,
+ }
+ );
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['sequence'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..7c1442ce01339c1066d4155dcbc8f5cff82da8cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/static/js/sequence.ui.js
@@ -0,0 +1,286 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import { emptyValidator, isEmptyString } from '../../../../../../../../static/js/validators';
+
+export class OwnedBySchema extends BaseUISchema {
+ constructor(allTables, getColumns) {
+ super({
+ owned_table: undefined,
+ owned_column: undefined,
+ });
+
+ this.allTables = allTables;
+ this.allTablesOptions = [];
+ this.getColumns = getColumns;
+ }
+
+ getTableOid(tabName) {
+ // Here we will fetch the table oid from table name
+ // iterate over list to find table oid
+ for(const t of this.allTablesOptions) {
+ if(t.label === tabName) {
+ return t._id;
+ }
+ }
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'owned_table', label: gettext('Table'), type: 'select', editable: false,
+ options: obj.allTables,
+ optionsLoaded: (res)=>obj.allTablesOptions=res,
+ },{
+ id: 'owned_column', label: gettext('Column'), editable: false, deps: ['owned_table'],
+ type: (state)=>{
+ let tid = obj.getTableOid(state.owned_table);
+ return {
+ type: 'select',
+ options: state.owned_table ? ()=>obj.getColumns({tid: tid}) : [],
+ optionsReloadBasis: state.owned_table,
+ };
+ },
+ depChange: (state)=>{
+ if(!state.owned_table) {
+ return {
+ owned_column: null,
+ };
+ }
+ }
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ if (!isEmptyString(state.owned_table) && isEmptyString(state.owned_column)) {
+ setError('owned_column', gettext('Column cannot be empty.'));
+ return true;
+ } else {
+ setError('owned_column', null);
+ }
+ }
+}
+
+
+export default class SequenceSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ seqowner: undefined,
+ schema: undefined,
+ is_sys_obj: undefined,
+ comment: undefined,
+ increment: undefined,
+ start: undefined,
+ current_value: undefined,
+ minimum: undefined,
+ maximum: undefined,
+ cache: undefined,
+ cycled: undefined,
+ relpersistence: undefined,
+ relacl: [],
+ securities: [],
+ ...initValues,
+ });
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ allTables: [],
+ ...fieldOptions,
+ };
+ this.ownedSchemaObj = new OwnedBySchema(this.fieldOptions.allTables, this.fieldOptions.getColumns);
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ noEmpty: true,
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text', mode: ['properties'],
+ }, {
+ id: 'seqowner', label: gettext('Owner'),
+ editable: false, type: 'select', options: this.fieldOptions.role,
+ controlProps: { allowClear: false }
+ }, {
+ id: 'schema', label: gettext('Schema'),
+ editable: false, type: 'select', options: this.fieldOptions.schema,
+ controlProps: { allowClear: false },
+ mode: ['create', 'edit'],
+ cache_node: 'database', cache_level: 'database',
+ }, {
+ id: 'is_sys_obj', label: gettext('System sequence?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ }, {
+ id: 'comment', label: gettext('Comment'), type: 'multiline',
+ mode: ['properties', 'create', 'edit'],
+ }, {
+ id: 'current_value', label: gettext('Current value'), type: 'int',
+ mode: ['properties', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'increment', label: gettext('Increment'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'start', label: gettext('Start'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'minimum', label: gettext('Minimum'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'maximum', label: gettext('Maximum'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'cache', label: gettext('Cache'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ min: 1,
+ }, {
+ id: 'cycled', label: gettext('Cycled'), type: 'switch',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ }, {
+ id: 'relpersistence', label: gettext('Unlogged?'), type: 'switch',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ min_version: 150000,
+ }, {
+ type: 'nested-fieldset', label: gettext('Owned By'), group: gettext('Definition'),
+ schema: this.ownedSchemaObj,
+ }, {
+ id: 'owned_by_note', type: 'note', group: gettext('Definition'),
+ mode: ['create', 'edit'],
+ text: gettext('The OWNED BY option causes the sequence to be associated with a specific table column, such that if that column (or its whole table) is dropped, the sequence will be automatically dropped as well. The specified table must have the same owner and be in the same schema as the sequence.'),
+ }, {
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ }, {
+ id: 'relacl', label: gettext('Privileges'), group: gettext('Security'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['r', 'w', 'U']),
+ uniqueCol : ['grantee', 'grantor'], mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ }, {
+ id: 'securities', label: gettext('Security labels'), type: 'collection',
+ editable: false, group: gettext('Security'),
+ schema: new SecLabelSchema(),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'],
+ min_version: 90200,
+ }
+ ];
+ }
+ /* validate function is used to validate the input given by
+ * the user. In case of error, message will be displayed on
+ * the GUI for the respective control.
+ */
+ validate(state, setError) {
+ let errmsg = null,
+ minimum = state.minimum,
+ maximum = state.maximum,
+ start = state.start;
+
+ errmsg = emptyValidator('Owner', state.seqowner);
+ if (errmsg) {
+ setError('seqowner', errmsg);
+ return true;
+ } else {
+ setError('seqowner', errmsg);
+ }
+
+ errmsg = emptyValidator('Schema', state.schema);
+ if (errmsg) {
+ setError('schema', errmsg);
+ return true;
+ } else {
+ setError('schema', errmsg);
+ }
+
+ if (!this.isNew(state)) {
+ errmsg = emptyValidator('Current value', state.current_value);
+ if (errmsg) {
+ setError('current_value', errmsg);
+ return true;
+ } else {
+ setError('current_value', errmsg);
+ }
+
+ errmsg = emptyValidator('Increment value', state.increment);
+ if (errmsg) {
+ setError('increment', errmsg);
+ return true;
+ } else {
+ setError('increment', errmsg);
+ }
+
+ errmsg = emptyValidator('Minimum value', state.minimum);
+ if (errmsg) {
+ setError('minimum', errmsg);
+ return true;
+ } else {
+ setError('minimum', errmsg);
+ }
+
+ errmsg = emptyValidator('Maximum value', state.maximum);
+ if (errmsg) {
+ setError('maximum', errmsg);
+ return true;
+ } else {
+ setError('maximum', errmsg);
+ }
+
+ errmsg = emptyValidator('Cache value', state.cache);
+ if (errmsg) {
+ setError('cache', errmsg);
+ return true;
+ } else {
+ setError('cache', errmsg);
+ }
+ }
+
+ let min_lt = gettext('Minimum value must be less than maximum value.'),
+ start_lt = gettext('Start value cannot be less than minimum value.'),
+ start_gt = gettext('Start value cannot be greater than maximum value.');
+
+ if (isEmptyString(minimum) || isEmptyString(maximum))
+ return null;
+
+ if ((minimum == 0 && maximum == 0) ||
+ (parseInt(minimum, 10) >= parseInt(maximum, 10))) {
+ setError('minimum', min_lt);
+ return true;
+ } else {
+ setError('minimum', null);
+ }
+
+ if (start && minimum && parseInt(start) < parseInt(minimum)) {
+ setError('start', start_lt);
+ return true;
+ } else {
+ setError('start', null);
+ }
+
+ if (start && maximum && parseInt(start) > parseInt(maximum)) {
+ setError('start', start_gt);
+ return true;
+ } else {
+ setError('start', null);
+ }
+ return null;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fd9d406f567d8ec7d9daabb96ad18ec7cd99609c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/create.sql
@@ -0,0 +1,21 @@
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}SEQUENCE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}{% if data.cycled %}
+
+ CYCLE{% endif %}{% if data.increment is defined %}
+
+ INCREMENT {{data.increment|int}}{% endif %}{% if data.start is defined %}
+
+ START {{data.start|int}}{% elif data.current_value is defined %}
+
+ START {{data.current_value|int}}{% endif %}{% if data.minimum is defined %}
+
+ MINVALUE {{data.minimum|int}}{% endif %}{% if data.maximum is defined %}
+
+ MAXVALUE {{data.maximum|int}}{% endif %}{% if data.cache is defined and data.cache|int(-1) > -1%}
+
+ CACHE {{data.cache|int}}{% endif %};
+{### Alter SQL for adding OWNED BY to sequence ###}
+{% if data.owned_table is defined and data.owned_table != None and data.owned_column is defined and data.owned_column != None %}
+
+ALTER SEQUENCE {{ conn|qtIdent(data.schema, data.name) }}
+ OWNED BY {{ conn|qtIdent(data.schema) }}.{{ conn|qtIdent(data.owned_table) }}.{{ conn|qtIdent(data.owned_column) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a885e295e356f810a24d438ebcf6fc86ba86c4a1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/properties.sql
@@ -0,0 +1,23 @@
+{% if scid %}
+SELECT
+ cl.oid as oid,
+ cl.relname as name,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(cl.relowner) AS seqowner,
+ description as comment,
+ pg_catalog.array_to_string(cl.relacl::text[], ', ') as acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=cl.oid) AS securities,
+ depcl.relname AS owned_table,
+ att.attname AS owned_column,
+ (CASE WHEN cl.relpersistence = 'u' THEN true ELSE false END) AS relpersistence
+FROM pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON cl.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
+ AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_depend dep ON (dep.objid=cl.oid and deptype = 'a')
+ LEFT JOIN pg_catalog.pg_attribute att ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
+ LEFT JOIN pg_catalog.pg_class depcl ON depcl.oid = att.attrelid
+WHERE cl.relkind = 'S' AND cl.relnamespace = {{scid}}::oid
+{% if seid %}AND cl.oid = {{seid}}::oid {% endif %}
+ORDER BY cl.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..891645fc62b6e6937846258f20bae95bf767374a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/15_plus/update.sql
@@ -0,0 +1,113 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% if data.name != o_data.name %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if data.seqowner and data.seqowner != o_data.seqowner %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.seqowner) }};
+
+{% endif %}
+{% if (data.owned_table == None and data.owned_column == None) or (data.owned_table == '' and data.owned_column == '')%}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNED BY NONE;
+{% elif (data.owned_table is defined or data.owned_column is defined) and (data.owned_table != o_data.owned_table or data.owned_column != o_data.owned_column) %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNED BY {{ conn|qtIdent(o_data.schema) }}.{% if data.owned_table is defined %}{{ conn|qtIdent(data.owned_table) }}{% else %}{{ conn|qtIdent(o_data.owned_table) }}{% endif %}.{% if data.owned_column is defined %}{{ conn|qtIdent(data.owned_column) }}{% else %}{{ conn|qtIdent(o_data.owned_column) }}{% endif %};
+{% endif %}
+{% if data.current_value is defined %}
+{% set seqname = conn|qtIdent(o_data.schema, data.name) %}
+SELECT setval({{ seqname|qtLiteral(conn) }}, {{ data.current_value }}, true);
+
+{% endif %}
+{% if data.relpersistence in [True, False] and data.relpersistence != o_data.relpersistence %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ SET {% if data.relpersistence %}UNLOGGED{% else %}LOGGED{% endif %};
+
+{% endif %}
+{% set defquery = '' %}
+{% if data.increment is defined %}
+{% set defquery = defquery+'\n INCREMENT '+data.increment|string %}
+{% endif %}
+{% if data.start is defined %}
+{% set defquery = defquery+'\n START '+data.start|string %}
+{% endif %}
+{% if data.minimum is defined %}
+{% set defquery = defquery+'\n MINVALUE '+data.minimum|string %}
+{% endif %}
+{% if data.maximum is defined %}
+{% set defquery = defquery+'\n MAXVALUE '+data.maximum|string %}
+{% endif %}
+{% if data.cache is defined %}
+{% set defquery = defquery+'\n CACHE '+data.cache|string %}
+{% endif %}
+{% if data.cycled == True %}
+{% set defquery = defquery+'\n CYCLE' %}
+{% elif data.cycled == False %}
+{% set defquery = defquery+'\n NO CYCLE' %}
+{% endif %}
+{% if defquery and defquery != '' %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}{{ defquery }};
+
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% set seqname = conn|qtIdent(data.schema, data.name) %}
+{% set schema = data.schema %}
+{% else %}
+{% set seqname = conn|qtIdent(o_data.schema, data.name) %}
+{% set schema = o_data.schema %}
+{% endif %}
+{% if data.comment is defined and data.comment != o_data.comment %}
+COMMENT ON SEQUENCE {{ seqname }}
+ IS {{ data.comment|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.securities and data.securities|length > 0 %}
+
+{% set seclabels = data.securities %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'SEQUENCE', data.name, r.provider, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if data.relacl %}
+
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.grantee, data.name, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.old_grantee, data.name, schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.grantee, data.name, schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1a4e6e86430fe5620f60f13e883b07bf825fdef3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/acl.sql
@@ -0,0 +1,30 @@
+SELECT 'relacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ pg_catalog.aclexplode((SELECT relacl
+ FROM pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
+ WHERE relkind = 'S' AND relnamespace = {{scid}}::oid
+ AND cl.oid = {{seid}}::oid )) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f72e3774eaee97627dc6dbd316fb38905297f5ca
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/backend_support.sql
@@ -0,0 +1,15 @@
+SELECT
+ CASE WHEN nsp.nspname IN ('sys', 'information_schema') THEN true ELSE false END AS dbSupport
+FROM pg_catalog.pg_namespace nsp
+WHERE nsp.oid={{scid}}::oid AND (
+ (nspname = 'pg_catalog' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'pgagent' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'information_schema' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname LIKE '_%' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1))
+ ) AND
+ nspname NOT LIKE E'pg\\temp\\%' AND
+ nspname NOT LIKE E'pg\\toast_temp\\%'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..42b33cefa5c19df56eda227473c4e13f87b0a83b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/coll_stats.sql
@@ -0,0 +1,9 @@
+SELECT
+ relname AS {{ conn|qtIdent(_('Name')) }},
+ blks_read AS {{ conn|qtIdent(_('Blocks read')) }},
+ blks_hit AS {{ conn|qtIdent(_('Blocks hit')) }}
+FROM
+ pg_catalog.pg_statio_all_sequences
+WHERE
+ schemaname = {{ schema_name|qtLiteral(conn) }}
+ORDER BY relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..394d3d3a71654df9ef8115b7f01bc5415e758bd3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class cl
+WHERE
+ relkind = 'S'
+{% if scid %}
+ AND relnamespace = {{scid|qtLiteral(conn)}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..992eb6b6efa3e053b2122611ef8ed374d61fa82f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/create.sql
@@ -0,0 +1,21 @@
+CREATE SEQUENCE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}{% if data.cycled %}
+
+ CYCLE{% endif %}{% if data.increment is defined %}
+
+ INCREMENT {{data.increment|int}}{% endif %}{% if data.start is defined %}
+
+ START {{data.start|int}}{% elif data.current_value is defined %}
+
+ START {{data.current_value|int}}{% endif %}{% if data.minimum is defined %}
+
+ MINVALUE {{data.minimum|int}}{% endif %}{% if data.maximum is defined %}
+
+ MAXVALUE {{data.maximum|int}}{% endif %}{% if data.cache is defined and data.cache|int(-1) > -1%}
+
+ CACHE {{data.cache|int}}{% endif %};
+{### Alter SQL for adding OWNED BY to sequence ###}
+{% if data.owned_table is defined and data.owned_table != None and data.owned_column is defined and data.owned_column != None %}
+
+ALTER SEQUENCE {{ conn|qtIdent(data.schema, data.name) }}
+ OWNED BY {{ conn|qtIdent(data.schema) }}.{{ conn|qtIdent(data.owned_table) }}.{{ conn|qtIdent(data.owned_column) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4f8cfbadf7f40bb59d424f19c78417790639fc60
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP SEQUENCE IF EXISTS {{ conn|qtIdent(data.schema) }}.{{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_def.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_def.sql
new file mode 100644
index 0000000000000000000000000000000000000000..335b1fad6ca022eed7e16229768416e6e48dab0d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_def.sql
@@ -0,0 +1,11 @@
+SELECT
+ last_value,
+ seqmin AS min_value,
+ seqmax AS max_value,
+ seqstart AS start_value,
+ seqcache AS cache_value,
+ seqcycle AS is_cycled,
+ seqincrement AS increment_by,
+ is_called
+FROM pg_catalog.pg_sequence, {{ conn|qtIdent(data.schema) }}.{{ conn|qtIdent(data.name) }}
+WHERE seqrelid = {{data.oid}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_dependencies.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_dependencies.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d161b8f295bb12ce9715cc4bfaac3c90323c4e95
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_dependencies.sql
@@ -0,0 +1,12 @@
+SELECT
+ CASE WHEN att.attname IS NOT NULL AND ref.relname IS NOT NULL THEN ref.relname || '.' || att.attname
+ ELSE ref.relname
+ END AS refname,
+ d2.refclassid, d1.deptype AS deptype
+FROM pg_catalog.pg_depend d1
+ LEFT JOIN pg_catalog.pg_depend d2 ON d1.objid=d2.objid AND d1.refobjid != d2.refobjid
+ LEFT JOIN pg_catalog.pg_class ref ON ref.oid = d2.refobjid
+ LEFT JOIN pg_catalog.pg_attribute att ON d2.refobjid=att.attrelid AND d2.refobjsubid=att.attnum
+WHERE d1.classid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_attrdef')
+ AND d2.refobjid NOT IN (SELECT d3.refobjid FROM pg_catalog.pg_depend d3 WHERE d3.objid=d1.refobjid)
+ AND d1.refobjid={{seid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a0a50ae2b192d5f804c5f1d15e06dc18ad5c1a4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/get_oid.sql
@@ -0,0 +1,7 @@
+SELECT cl.oid as oid, relnamespace
+FROM pg_catalog.pg_class cl
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON (nsp.oid = cl.relnamespace)
+WHERE relkind = 'S'
+AND relname = {{ name|qtLiteral(conn) }}
+AND nspname = {{ schema|qtLiteral(conn) }}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fbc0bb24c6ada4049a21f9869445e6a7d84f8835
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/grant.sql
@@ -0,0 +1,26 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{# Construct sequence name from name and schema #}
+{% set seqname=conn|qtIdent(data.schema, data.name) %}
+{% if data.seqowner %}
+
+ALTER SEQUENCE {{ seqname }}
+ OWNER TO {{ conn|qtIdent(data.seqowner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON SEQUENCE {{ seqname }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% if data.securities %}
+
+{% for r in data.securities %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..327dd1f666c2fb4ee1af044d1cd6647b546a6fe1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/nodes.sql
@@ -0,0 +1,20 @@
+SELECT cl.oid as oid, relname as name, relnamespace as schema, description as comment
+FROM pg_catalog.pg_class cl
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
+ AND des.classoid='pg_class'::regclass)
+{% if show_internal %}
+LEFT JOIN pg_catalog.pg_depend d1 ON d1.refobjid = cl.oid AND d1.deptype = 'i'
+{% endif %}
+WHERE
+ relkind = 'S'
+{% if scid %}
+ AND relnamespace = {{scid|qtLiteral(conn)}}::oid
+{% endif %}
+{% if seid %}
+ AND cl.oid = {{seid|qtLiteral(conn)}}::oid
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = cl.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..64ed3286c63606cb2a7d1d000f4d01daaeb9dcf0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/properties.sql
@@ -0,0 +1,22 @@
+{% if scid %}
+SELECT
+ cl.oid as oid,
+ cl.relname as name,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(cl.relowner) AS seqowner,
+ description as comment,
+ pg_catalog.array_to_string(cl.relacl::text[], ', ') as acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=cl.oid) AS securities,
+ depcl.relname AS owned_table,
+ att.attname AS owned_column
+FROM pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON cl.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cl.oid
+ AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_depend dep ON (dep.objid=cl.oid and deptype = 'a')
+ LEFT JOIN pg_catalog.pg_attribute att ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
+ LEFT JOIN pg_catalog.pg_class depcl ON depcl.oid = att.attrelid
+WHERE cl.relkind = 'S' AND cl.relnamespace = {{scid}}::oid
+{% if seid %}AND cl.oid = {{seid}}::oid {% endif %}
+ORDER BY cl.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec8c119a44c735c6c58cbc17f0d0f7345dfcf2d2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/stats.sql
@@ -0,0 +1,7 @@
+SELECT
+ blks_read AS {{ conn|qtIdent(_('Blocks read')) }},
+ blks_hit AS {{ conn|qtIdent(_('Blocks hit')) }}
+FROM
+ pg_catalog.pg_statio_all_sequences
+WHERE
+ relid = {{ seid }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4dee0445badf50fdc0314bc8632fccecaba2cdc9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/sequences/templates/sequences/sql/default/update.sql
@@ -0,0 +1,108 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% if data.name != o_data.name %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if data.seqowner and data.seqowner != o_data.seqowner %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.seqowner) }};
+
+{% endif %}
+{% if (data.owned_table == None and data.owned_column == None) or (data.owned_table == '' and data.owned_column == '') %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNED BY NONE;
+{% elif (data.owned_table is defined or data.owned_column is defined) and (data.owned_table != o_data.owned_table or data.owned_column != o_data.owned_column) %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ OWNED BY {{ conn|qtIdent(o_data.schema) }}.{% if data.owned_table is defined %}{{ conn|qtIdent(data.owned_table) }}{% else %}{{ conn|qtIdent(o_data.owned_table) }}{% endif %}.{% if data.owned_column is defined %}{{ conn|qtIdent(data.owned_column) }}{% else %}{{ conn|qtIdent(o_data.owned_column) }}{% endif %};
+{% endif %}
+{% if data.current_value is defined %}
+{% set seqname = conn|qtIdent(o_data.schema, data.name) %}
+SELECT setval({{ seqname|qtLiteral(conn) }}, {{ data.current_value }}, true);
+
+{% endif %}
+{% set defquery = '' %}
+{% if data.increment is defined %}
+{% set defquery = defquery+'\n INCREMENT '+data.increment|string %}
+{% endif %}
+{% if data.start is defined %}
+{% set defquery = defquery+'\n START '+data.start|string %}
+{% endif %}
+{% if data.minimum is defined %}
+{% set defquery = defquery+'\n MINVALUE '+data.minimum|string %}
+{% endif %}
+{% if data.maximum is defined %}
+{% set defquery = defquery+'\n MAXVALUE '+data.maximum|string %}
+{% endif %}
+{% if data.cache is defined %}
+{% set defquery = defquery+'\n CACHE '+data.cache|string %}
+{% endif %}
+{% if data.cycled == True %}
+{% set defquery = defquery+'\n CYCLE' %}
+{% elif data.cycled == False %}
+{% set defquery = defquery+'\n NO CYCLE' %}
+{% endif %}
+{% if defquery and defquery != '' %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}{{ defquery }};
+
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER SEQUENCE IF EXISTS {{ conn|qtIdent(o_data.schema, data.name) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% set seqname = conn|qtIdent(data.schema, data.name) %}
+{% set schema = data.schema %}
+{% else %}
+{% set seqname = conn|qtIdent(o_data.schema, data.name) %}
+{% set schema = o_data.schema %}
+{% endif %}
+{% if data.comment is defined and data.comment != o_data.comment %}
+COMMENT ON SEQUENCE {{ seqname }}
+ IS {{ data.comment|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.securities and data.securities|length > 0 %}
+
+{% set seclabels = data.securities %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'SEQUENCE', data.name, r.provider, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'SEQUENCE', data.name, r.provider, r.label, schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if data.relacl %}
+
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.grantee, data.name, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.old_grantee, data.name, schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'SEQUENCE', priv.grantee, data.name, schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'SEQUENCE', priv.grantee, data.name, priv.without_grant, priv.with_grant, schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/catalog.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/catalog.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b3aabcd46c002f70538b649d74c2b8da9f7e7259
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/catalog.svg
@@ -0,0 +1 @@
+coll-catalog
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-catalog.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-catalog.svg
new file mode 100644
index 0000000000000000000000000000000000000000..e4ca778946840ddcab9437b1cb2d1d575f1355dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-catalog.svg
@@ -0,0 +1 @@
+catalog
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-schema.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-schema.svg
new file mode 100644
index 0000000000000000000000000000000000000000..338e8ea0adfbbc4a5d02fe734580b75345e8d8de
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/coll-schema.svg
@@ -0,0 +1 @@
+schema
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/schema.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/schema.svg
new file mode 100644
index 0000000000000000000000000000000000000000..8a1bdf1b132a81837b495412212ef7b7949bcef2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/img/schema.svg
@@ -0,0 +1 @@
+coll-schema
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.js
new file mode 100644
index 0000000000000000000000000000000000000000..483af8be96206efe7f4dd32b354954c6ef89b0a8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.js
@@ -0,0 +1,56 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import CatalogSchema from './catalog.ui';
+
+define('pgadmin.node.catalog', [
+ 'sources/gettext', 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(gettext, pgBrowser) {
+
+ // Extend the browser's collection class for catalog collection
+ if (!pgBrowser.Nodes['coll-catalog']) {
+ pgBrowser.Nodes['coll-catalog'] =
+ pgBrowser.Collection.extend({
+ node: 'catalog',
+ label: gettext('Catalogs'),
+ type: 'coll-catalog',
+ columns: ['name', 'namespaceowner', 'description'],
+ canDrop: false,
+ canDropCascade: false,
+ });
+ }
+ // Extend the browser's node class for catalog node
+ if (!pgBrowser.Nodes['catalog']) {
+ pgBrowser.Nodes['catalog'] = pgBrowser.Node.extend({
+ parent_type: 'database',
+ type: 'catalog',
+ label: gettext('Catalog'),
+ hasSQL: true,
+ hasDepends: true,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ },
+ getSchema: function(treeNodeInfo) {
+ return new CatalogSchema(
+ {
+ namespaceowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name
+ }
+ );
+ }
+ });
+
+ }
+
+ return pgBrowser.Nodes['catalog'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..33e15946675de67a6f0d543187bb831274bbde7c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/catalog.ui.js
@@ -0,0 +1,56 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+export default class CatalogSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ name: undefined,
+ namespaceowner: undefined,
+ nspacl: undefined,
+ is_sys_obj: undefined,
+ description: undefined,
+ securitylabel: [],
+ ...initValues
+ });
+ this.fieldOptions = {
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', readonly: true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string', mode: ['properties'],
+ type: 'text',
+ },{
+ id: 'namespaceowner', label: gettext('Owner'), cell: 'string',
+ type: 'text', readonly: true,
+ },{
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'is_sys_obj', label: gettext('System catalog?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline',
+ }
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/child.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/child.js
new file mode 100644
index 0000000000000000000000000000000000000000..d36e5cff762de4b442ccc007aa972d1b2dcf3e62
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/child.js
@@ -0,0 +1,20 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+/////////////////////////////////////////////////////////////
+
+import * as Node from 'pgbrowser/node';
+import * as SchemaTreeNode from './schema_child_tree_node';
+
+let SchemaChildNode = Node.extend({
+ parent_type: ['schema', 'catalog'],
+ canDrop: SchemaTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaTreeNode.isTreeItemOfChildOfSchema,
+ canCreate: SchemaTreeNode.childCreateMenuEnabled,
+}, false);
+
+export {SchemaChildNode};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.js
new file mode 100644
index 0000000000000000000000000000000000000000..7a8a693aac2c41d4b5c332a78390a0f09d14c86d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.js
@@ -0,0 +1,106 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import PGSchema from './schema.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../static/js/privilege.ui';
+import { getNodeListByName } from '../../../../../../static/js/node_ajax';
+
+define('pgadmin.node.schema', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser) {
+
+ // Extend the browser's collection class for schema collection
+ if (!pgBrowser.Nodes['coll-schema']) {
+ pgBrowser.Nodes['coll-schema'] =
+ pgBrowser.Collection.extend({
+ node: 'schema',
+ label: gettext('Schemas'),
+ type: 'coll-schema',
+ columns: ['name', 'namespaceowner', 'description'],
+ });
+ }
+ // Extend the browser's node class for schema node
+ if (!pgBrowser.Nodes['schema']) {
+ pgBrowser.Nodes['schema'] = pgBrowser.Node.extend({
+ parent_type: 'database',
+ type: 'schema',
+ sqlAlterHelp: 'sql-alterschema.html',
+ sqlCreateHelp: 'sql-createschema.html',
+ dialogHelp: url_for('help.static', {'filename': 'schema_dialog.html'}),
+ label: gettext('Schema'),
+ hasSQL: true,
+ canDrop: true,
+ canDropCascade: true,
+ hasDepends: true,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_schema_on_coll', node: 'coll-schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Schema...'),
+ data: {action: 'create'},
+ },{
+ name: 'create_schema', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Schema...'),
+ data: {action: 'create'},
+ },{
+ name: 'create_schema', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Schema...'),
+ data: {action: 'create'}, enable: 'can_create_schema',
+ },{
+ name: 'generate_erd', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'generate_erd',
+ category: 'erd', priority: 5, label: gettext('ERD For Schema')
+ }]);
+ },
+ can_create_schema: function(node) {
+ return pgBrowser.Nodes['database'].is_conn_allow.call(this, node);
+ },
+ callbacks: {
+ /* Generate the ERD */
+ generate_erd: function(args) {
+ let input = args || {},
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+ pgAdmin.Tools.ERD.showErdTool(d, i, true);
+ },
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ let schemaObj = pgBrowser.Nodes['schema'];
+ return new PGSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(schemaObj, treeNodeInfo, itemNodeData, privileges),
+ {
+ roles:() => getNodeListByName('role', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ server_info: pgBrowser.serverInfo[treeNodeInfo.server._id]
+ },
+ {
+ namespaceowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name
+ }
+ );
+ }
+ });
+
+ pgBrowser.tableChildTreeNodeHierarchy = function(i) {
+ return pgBrowser.tree.getTreeNodeHierarchy(i);
+ };
+ }
+
+ return pgBrowser.Nodes['schema'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..6f5c532235c5d8daeb6f63107a7fa44f09690776
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema.ui.js
@@ -0,0 +1,112 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { DefaultPrivSchema } from '../../../static/js/database.ui';
+import SecLabelSchema from '../../../../static/js/sec_label.ui';
+import { isEmptyString } from 'sources/validators';
+
+export default class PGSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, fieldOptions = {}, initValues={}) {
+ super({
+ name: undefined,
+ namespaceowner: undefined,
+ description: undefined,
+ is_system_obj: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ roles: [],
+ server_info: [],
+ ...fieldOptions,
+ };
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let pgSchemaObj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text',
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'namespaceowner', label: gettext('Owner'), cell: 'string',
+ type: 'select',
+ options: pgSchemaObj.fieldOptions.roles,
+ controlProps: { allowClear: false }
+ },{
+ id: 'is_sys_obj', label: gettext('System schema?'),
+ cell: 'switch', type: 'switch', mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline',
+ },{
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'tblacl', label: gettext('Default TABLE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'seqacl', label: gettext('Default SEQUENCE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'funcacl', label: gettext('Default FUNCTION privileges'),
+ group: gettext('Security'), type: 'text', mode: ['properties'],
+ },{
+ id: 'typeacl', label: gettext('Default TYPE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'], min_version: 90200
+ },
+ {
+ id: 'nspacl', label: gettext('Privileges'), type: 'collection',
+ schema: pgSchemaObj.getPrivilegeRoleSchema(['C', 'U']),
+ uniqueCol : ['grantee', 'grantor'], editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ },
+ {
+ id: 'seclabels', label: gettext('Security labels'),
+ schema: new SecLabelSchema(), editable: false, type: 'collection',
+ group: gettext('Security'), mode: ['edit', 'create'],
+ min_version: 90200, canAdd: true,
+ canEdit: false, canDelete: true,
+ },
+ {
+ type: 'nested-tab',
+ group: gettext('Default privileges'),
+ mode: ['create','edit'],
+ schema: new DefaultPrivSchema(pgSchemaObj.getPrivilegeRoleSchema)
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+
+ // Validation of mandatory fields
+ if (isEmptyString(state.name)) {
+ errmsg = gettext('Name cannot be empty.');
+ setError('name', errmsg);
+ return true;
+ }
+ else if(isEmptyString(state.namespaceowner)) {
+ errmsg = gettext('Owner cannot be empty.');
+ setError('namespaceowner', errmsg);
+ return true;
+ }
+ return null;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema_child_tree_node.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema_child_tree_node.js
new file mode 100644
index 0000000000000000000000000000000000000000..9f63062cc42e635618630465081e343fe518dc22
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/static/js/schema_child_tree_node.js
@@ -0,0 +1,43 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+/////////////////////////////////////////////////////////////
+
+import pgAdmin from 'sources/pgadmin';
+
+let pgBrowser = pgAdmin.Browser;
+
+export function childCreateMenuEnabled(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check) {
+ return true;
+ }
+
+ let node = pgBrowser.tree.findNodeByDomElement(item);
+
+ if (node)
+ return node.anyFamilyMember(
+ (parentNode) => (parentNode.getData()._type === 'schema')
+ );
+
+ return false;
+}
+
+export function isTreeItemOfChildOfSchema(itemData, item) {
+ let node = pgBrowser.tree.findNodeByDomElement(item);
+
+ if (node)
+ return isTreeNodeOfSchemaChild(node);
+
+ return false;
+}
+
+export function isTreeNodeOfSchemaChild(node) {
+ return node.anyParent(
+ (parentNode) => (parentNode.getData()._type === 'schema')
+ );
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f169ac6d92bf2dec0f83c9f486439c4ee4fb18f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/__init__.py
@@ -0,0 +1,807 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Synonym Node """
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, \
+ make_response as ajax_response, internal_server_error, gone
+from pgadmin.utils.ajax import precondition_required
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class SynonymModule(SchemaChildModule):
+ """
+ class SynonymModule(CollectionNodeModule)
+
+ A module class for Synonym node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Synonym and it's base module.
+
+ * get_nodes(gid, sid, did, scid, syid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'synonym'
+ _COLLECTION_LABEL = gettext("Synonyms")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the SynonymModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90100
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=SynonymView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ return False
+
+
+blueprint = SynonymModule(__name__)
+
+
+class SynonymView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Synonym node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the SynonymView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Synonym nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Synonym node.
+
+ * properties(gid, sid, did, scid, syid)
+ - This function will show the properties of the selected Synonym node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new Synonym object
+
+ * update(gid, sid, did, scid, syid)
+ - This function will update the data for the selected Synonym node
+
+ * delete(self, gid, sid, scid, syid):
+ - This function will drop the Synonym object
+
+ * msql(gid, sid, did, scid, syid)
+ - This function is used to return modified SQL for the selected
+ Synonym node
+
+ * get_sql(data, scid, syid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Synonym node.
+
+ * dependency(gid, sid, did, scid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Synonym node.
+
+ * dependent(gid, sid, did, scid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Synonym node.
+
+ * compare(**kwargs):
+ - This function will compare the synonyms nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Synonym"
+ BASE_TEMPLATE_PATH = 'synonyms/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ # If URL has an identifier containing slash character '/'
+ # into the URI, then set param type to path. Because if
+ # param name contains '/' in syid, it gets confused and
+ # wrong url is generated.
+ # Reference:- http://flask.pocoo.org/snippets/76/
+ ids = [
+ {'type': 'path', 'id': 'syid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_target_objects': [{'get': 'get_target_objects'},
+ {'get': 'get_target_objects'}]
+ })
+
+ keys_to_ignore = ['oid', 'oid-2', 'schema', 'synobjschema']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ # If DB not connected then return error to browser
+ if not self.conn.connected():
+ return precondition_required(
+ gettext(
+ "Connection to the server has been lost."
+ )
+ )
+
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # we will set template path for sql scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the synonym nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available synonym nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the synonym node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available synonym child nodes
+ """
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-synonym"
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, syid=None):
+ """
+ Return Synonym node to generate node
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ syid: Synonym id
+ """
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ syid=syid, scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ for row in rset['rows']:
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-%s" % self.node_type
+ ),
+ status=200
+ )
+
+ @check_precondition
+ def get_target_objects(self, gid, sid, did, scid, syid=None):
+ """
+ This function will provide list of objects as per user selection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ syid: Synonym ID
+
+ Returns:
+ List of objects
+ """
+ res = []
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ is_valid_request = True
+ if (
+ 'trgTyp' not in data or data['trgTyp'] is None or
+ data['trgTyp'].strip() == ''
+ ):
+ is_valid_request = False
+
+ if (
+ 'trgSchema' not in data or data['trgSchema'] is None or
+ data['trgSchema'].strip() == ''
+ ):
+ is_valid_request = False
+
+ if is_valid_request:
+ sql = render_template("/".join([self.template_path,
+ 'get_objects.sql']),
+ trgTyp=data['trgTyp'],
+ trgSchema=data['trgSchema'],
+ conn=self.conn)
+ status, rset = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append({'label': row['name'],
+ 'value': row['name']})
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, syid):
+ """
+ This function will show the properties of the selected synonym node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ syid: Synonym ID
+
+ Returns:
+ JSON of selected synonym node
+ """
+ status, res = self._fetch_properties(scid, syid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, syid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param scid:
+ :param syid:
+ :return:
+ """
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, syid=syid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ res['rows'][0]['is_sys_obj'] = (
+ res['rows'][0]['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+ return True, res['rows'][0]
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the synonym object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ required_args = [
+ 'name', 'targettype', 'synobjschema', 'synobjname'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn, comment=False)
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Find parent oid to add properly in tree browser
+ SQL = render_template("/".join([self.template_path,
+ 'get_parent_oid.sql']),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ parent_id = res['rows'][0]['scid']
+ syid = res['rows'][0]['syid']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ syid,
+ int(parent_id),
+ data['name'],
+ icon="icon-synonym"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, syid=None, only_sql=False):
+ """
+ This function will delete the existing synonym object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ only_sql: Return SQL only if True
+ """
+ if syid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [syid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ try:
+ for syid in data['ids']:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, syid=syid)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) > 0:
+ data = res['rows'][0]
+ else:
+ return gone(self.not_found_error_msg())
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ conn=self.conn)
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Synonym dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, syid):
+ """
+ This function will updates the existing synonym object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ SQL, name = self.get_sql(gid, sid, data, scid, syid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ try:
+ if SQL and SQL.strip('\n') and SQL.strip(' '):
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ syid,
+ scid,
+ name,
+ icon="icon-synonym"
+ )
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, syid=None):
+ """
+ This function will generates modified sql for synonym object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ try:
+ SQL, _ = self.get_sql(gid, sid, data, scid, syid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ if SQL and SQL.strip('\n') and SQL.strip(' '):
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_sql(self, gid, sid, data, scid, syid=None):
+ """
+ This function will genrate sql from model data
+ """
+ name = None
+ if syid is not None:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, syid=syid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+ old_data = res['rows'][0]
+ name = old_data['name']
+ # If target schema/object is not present then take it from
+ # old data, it means it does not changed
+ if 'synobjschema' not in data:
+ data['synobjschema'] = old_data['synobjschema']
+ if 'synobjname' not in data:
+ data['synobjname'] = old_data['synobjname']
+
+ SQL = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ else:
+ required_args = [
+ 'name', 'targettype', 'synobjschema', 'synobjname'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return gettext("-- missing definition")
+
+ name = data['name']
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]), comment=False,
+ data=data, conn=self.conn)
+ return SQL.strip('\n'), name
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, syid, **kwargs):
+ """
+ This function will generates reverse engineered sql for synonym object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ json_resp:
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, syid=syid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) > 0:
+ data = res['rows'][0]
+ else:
+ return gone(self.not_found_error_msg())
+
+ if target_schema:
+ data['schema'] = target_schema
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn, comment=True)
+ if not json_resp:
+ return SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, syid):
+ """
+ This function get the dependents and return ajax response
+ for the Synonym node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ """
+ dependents_result = self.get_dependents(self.conn, syid)
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, syid):
+ """
+ This function get the dependencies and return ajax response
+ for the Synonym node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ syid: Synonym ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, syid)
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the synonyms for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ if self.manager.server_type != 'ppas':
+ return res
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), scid=scid,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.get_sql(gid, sid, data, scid, oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, syid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, syid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, syid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, SynonymView)
+SynonymView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/coll-synonym.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/coll-synonym.svg
new file mode 100644
index 0000000000000000000000000000000000000000..bc93a17def449add65642a010648e27713b9ed8b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/coll-synonym.svg
@@ -0,0 +1 @@
+coll-synonym
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/synonym.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/synonym.svg
new file mode 100644
index 0000000000000000000000000000000000000000..a393690361bda711ff442abbc317ac99b9b014d0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/img/synonym.svg
@@ -0,0 +1 @@
+synonym
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.js
new file mode 100644
index 0000000000000000000000000000000000000000..fcca3724ddc7fcda16d507c1b7e6d04ace7ec7dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.js
@@ -0,0 +1,121 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import SynonymSchema from './synonym.ui';
+import _ from 'lodash';
+
+define('pgadmin.node.synonym', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode) {
+
+ if (!pgBrowser.Nodes['coll-synonym']) {
+ pgAdmin.Browser.Nodes['coll-synonym'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'synonym',
+ label: gettext('Synonyms'),
+ type: 'coll-synonym',
+ columns: ['name', 'owner','is_public_synonym'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['synonym']) {
+ pgAdmin.Browser.Nodes['synonym'] = schemaChild.SchemaChildNode.extend({
+ type: 'synonym',
+ epasHelp: true,
+ dialogHelp: url_for('help.static', {'filename': 'synonym_dialog.html'}),
+ label: gettext('Synonym'),
+ collection_type: 'coll-synonym',
+ hasSQL: true,
+ hasDepends: true,
+ parent_type: ['schema', 'catalog'],
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_synonym_on_coll', node: 'coll-synonym', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Synonym...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_synonym', node: 'synonym', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Synonym...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_synonym', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Synonym...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },
+ ]);
+
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new SynonymSchema(
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ synobjschema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {}, (m)=>{
+ // Exclude PPAS catalogs
+ let exclude_catalogs = ['pg_catalog', 'sys', 'pgagent', 'information_schema', 'dbms_job_procedure'];
+ return m && _.indexOf(exclude_catalogs, m.label) == -1;
+ }),
+ getTargetObjectOptions: (targettype, synobjschema) =>
+ {
+ return getNodeAjaxOptions('get_target_objects', this, treeNodeInfo,
+ itemNodeData, {urlParams: {'trgTyp' : targettype, 'trgSchema' : synobjschema}, useCache: false});
+ },
+ },
+ treeNodeInfo,
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: itemNodeData.label,
+ synobjschema: itemNodeData.label,
+ }
+ );
+ },
+ canCreate: function(itemData, item, data) {
+ //If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ if (server && server.server_type === 'pg')
+ return false;
+
+ // If it is catalog then don't allow user to create synonyms
+ return treeData['catalog'] == undefined;
+ },
+ });
+
+ }
+
+ return pgBrowser.Nodes['synonym'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..4ab31aa9084c0a03655beea8c83c4469408cfb91
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/static/js/synonym.ui.js
@@ -0,0 +1,136 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { emptyValidator } from 'sources/validators';
+
+export default class SynonymSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, initValues={}) {
+ super({
+ targettype: 'r',
+ ...initValues,
+ });
+ this.fieldOptions = fieldOptions;
+ this.nodeInfo = nodeInfo;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ readonly: function(state) { return !obj.isNew(state); },
+ }, {
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text', mode: ['properties'],
+ }, {
+ id: 'owner', label: gettext('Owner'),
+ options: this.fieldOptions.role,
+ controlProps: { allowClear: false, editable: false},
+ type: 'select', mode: ['properties', 'create', 'edit'],
+ readonly: true , visible: false,
+ }, {
+ id: 'schema', label: gettext('Schema'),
+ type: 'select', mode: ['properties', 'create', 'edit'],
+ options: this.fieldOptions.schema,
+ controlProps: { allowClear: false, editable: false },
+ readonly: function(state) { return !obj.isNew(state); },
+ }, {
+ id: 'targettype', label: gettext('Target type'),
+ readonly: obj.inCatalog(), group: gettext('Definition'),
+ controlProps: { allowClear: false },
+ type: 'select',
+ options: [
+ {label: gettext('Function'), value: 'f'},
+ {label: gettext('Package'), value: 'P'},
+ {label: gettext('Procedure'), value: 'p'},
+ {label: gettext('Public Synonym'), value: 's'},
+ {label: gettext('Sequence'), value: 'S'},
+ {label: gettext('Table'), value: 'r'},
+ {label: gettext('View'), value: 'v'}
+ ]
+ }, {
+ id: 'synobjschema', label: gettext('Target schema'),
+ type: 'select', mode: ['properties', 'create', 'edit'],
+ group: gettext('Definition'), deps: ['targettype'],
+ controlProps: { allowClear: false},
+ options: this.fieldOptions.synobjschema,
+ readonly: function(state) {
+ // If tagetType is synonym then disable it
+ if(!obj.inCatalog()) {
+ return state.targettype == 's';
+ }
+ return true;
+ },
+ depChange: function(state) {
+ if(!obj.inCatalog() && state.targettype == 's') {
+ return { synobjschema: 'public'};
+ }
+ }
+ }, {
+ id: 'synobjname', label: gettext('Target object'),
+ group: gettext('Definition'),
+ deps: ['targettype', 'synobjschema'],
+ depChange: function(state, source) {
+ if(source[0] == 'targettype' || source[0] == 'synobjschema') {
+ return { synobjname: null};
+ }
+ },
+ type: (state)=>{
+ let fetchOptionsBasis = state.targettype + state.synobjschema;
+ return {
+ type: 'select',
+ options: ()=>obj.fieldOptions.getTargetObjectOptions(state.targettype, state.synobjschema),
+ optionsReloadBasis: fetchOptionsBasis,
+ };
+ },
+ readonly: function() {
+ return obj.inCatalog();
+ }
+ }, {
+ id: 'is_sys_obj', label: gettext('System synonym?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+
+ errmsg = emptyValidator('Name', state.name);
+ if (errmsg) {
+ setError('name', errmsg);
+ return true;
+ } else {
+ setError('name', errmsg);
+ }
+
+ errmsg = emptyValidator('Target schema', state.synobjschema);
+ if (errmsg) {
+ setError('synobjschema', errmsg);
+ return true;
+ } else {
+ setError('synobjschema', errmsg);
+ }
+
+ errmsg = emptyValidator('Target object', state.synobjname);
+ if (errmsg) {
+ setError('synobjname', errmsg);
+ return true;
+ } else {
+ setError('synobjname', errmsg);
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..32ea3862178e6a8ddc15d27aeba4f431a83417aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/count.sql
@@ -0,0 +1,4 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_synonym s
+ JOIN pg_catalog.pg_namespace ns ON s.synnamespace = ns.oid
+ AND s.synnamespace = {{scid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5c5a6da417fd33c898cf70c4b99ce4471463929f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/create.sql
@@ -0,0 +1,21 @@
+{% set is_public = False %}
+{% if data.schema == 'public' %}
+{% set is_public = True %}
+{% endif %}
+{% if comment %}
+-- {% if is_public %}Public{% else %}Private{% endif %} synonym: {% if is_public %}{{ data.name }};
+{% else %}{{ data.schema }}.{{ data.name }};
+{% endif %}
+
+-- DROP {% if is_public %}PUBLIC {% endif %}SYNONYM {% if is_public %}{{ conn|qtIdent(data.name) }};
+{% else %}{{ conn|qtIdent(data.schema, data.name) }};
+{% endif %}
+
+{% endif %}
+CREATE OR REPLACE {% if is_public %}
+PUBLIC SYNONYM {{ conn|qtIdent(data.name) }}
+{% else %}
+SYNONYM {{ conn|qtIdent(data.schema, data.name) }}
+{% endif %}
+ FOR {{ conn|qtIdent(data.synobjschema, data.synobjname) }};
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dee3d6872f666eb787695ef09fb258442b256bae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/delete.sql
@@ -0,0 +1,7 @@
+{% set is_public = False %}
+{% if data.schema == 'public' %}
+{% set is_public = True %}
+{% endif %}
+DROP {% if is_public %}
+PUBLIC SYNONYM {{ conn|qtIdent(data.name) }}{% else %}
+SYNONYM {{ conn|qtIdent(data.schema, data.name) }}{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_objects.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_objects.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8e49753d6a20f4b767d32a0b0b015191482d40b2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_objects.sql
@@ -0,0 +1,56 @@
+{###########################################}
+{### If Target Type is Function ###}
+{###########################################}
+{% if trgTyp == 'f' %}
+SELECT DISTINCT proname AS name
+ FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
+WHERE p.pronamespace = n.oid AND
+ n.nspname = {{ trgSchema|qtLiteral(conn) }} AND
+ p.protype = '0'
+ORDER BY proname;
+{###########################################}
+{### If Target Type is Procedure ###}
+{###########################################}
+{% elif trgTyp == 'p' %}
+SELECT DISTINCT proname AS name
+ FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
+WHERE p.pronamespace = n.oid AND
+ n.nspname = {{ trgSchema|qtLiteral(conn) }} AND
+ p.protype = '1'
+ORDER BY proname;
+{###########################################}
+{### If Target Type is Synonym ###}
+{###########################################}
+{% elif trgTyp == 's' %}
+SELECT synname AS name
+ FROM pg_catalog.pg_synonym
+ORDER BY synname;
+{###########################################}
+{### If Target Type is Package ###}
+{###########################################}
+{% elif trgTyp == 'P' %}
+SELECT nspname AS name
+ FROM pg_catalog.pg_namespace
+WHERE nspparent IN (
+ SELECT oid
+ FROM pg_catalog.pg_namespace
+ WHERE nspname = {{ trgSchema|qtLiteral(conn) }} LIMIT 1
+ )
+ AND nspobjecttype = 0
+ORDER BY nspname;
+{% else %}
+{###################################################}
+{### If Target Type is Table/View/M.View/Sequnce ###}
+{###################################################}
+SELECT relname AS name
+ FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n
+WHERE c.relnamespace = n.oid AND
+ n.nspname = {{ trgSchema|qtLiteral(conn) }} AND
+{% if trgTyp == 'v' %}
+{# If view is select then we need to fetch both view and materialized view #}
+ (c.relkind = 'v' OR c.relkind = 'm')
+{% else %}
+ c.relkind = {{ trgTyp|qtLiteral(conn) }}
+{% endif %}
+ORDER BY relname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_parent_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_parent_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..50ba41e3e91b90543adf599904287d5fa002f5dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_parent_oid.sql
@@ -0,0 +1,5 @@
+SELECT s.oid as syid, synnamespace as scid
+ FROM pg_catalog.pg_synonym s
+WHERE synname = {{ data.name|qtLiteral(conn) }}
+AND synnamespace IN
+ ( SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = {{ data.schema|qtLiteral(conn) }} );
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8baf6c488f651893ad041cf778ab3c4c0a18fc90
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/get_schema.sql
@@ -0,0 +1,7 @@
+{# ===== fetch new assigned schema id ===== #}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{syid|qtLiteral(conn)}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..48cb643c9363ac8223996e86bc660de968adca7e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/nodes.sql
@@ -0,0 +1,5 @@
+SELECT s.oid, synname as name
+FROM pg_catalog.pg_synonym s
+ JOIN pg_catalog.pg_namespace ns ON s.synnamespace = ns.oid
+ AND s.synnamespace = {{scid}}::oid
+ORDER BY synname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ef7444d4d517667570e7cfe65090170012fcb366
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/properties.sql
@@ -0,0 +1,34 @@
+SELECT s.oid, synname AS name, pg_catalog.pg_get_userbyid(synowner) AS owner,
+ synobjschema, synobjname, ns.nspname as schema,
+ COALESCE(
+ (SELECT relkind
+ FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n
+ WHERE c.relnamespace = n.oid
+ AND n.nspname = synobjschema
+ AND c.relname = synobjname),
+ -- For Function/Procedure
+ (SELECT CASE WHEN p.protype = '0' THEN 'f'::"char" ELSE 'p'::"char" END
+ FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n
+ WHERE p.pronamespace = n.oid
+ AND n.nspname = synobjschema
+ AND p.proname = synobjname LIMIT 1),
+ -- For Package
+ (SELECT CASE WHEN count(*) > 0 THEN 'P'::"char" END
+ FROM pg_catalog.pg_namespace
+ WHERE nspparent IN (SELECT oid
+ FROM pg_catalog.pg_namespace
+ WHERE nspname = synobjschema LIMIT 1)
+ AND nspname = synobjname
+ AND nspobjecttype = 0),
+ -- Default s = Synonym
+ 's') AS targettype
+FROM pg_catalog.pg_synonym s JOIN pg_catalog.pg_namespace ns ON s.synnamespace = ns.oid
+ WHERE s.synnamespace={{scid}}::oid
+ {% if syid %}
+ AND s.oid={{syid}}::oid
+ {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = s.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY synname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..de91b9413c2eeed885f43352005f58cff46eb5cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/templates/synonyms/sql/default/update.sql
@@ -0,0 +1,10 @@
+{% set is_public = False %}
+{% if o_data.schema == 'public' %}
+{% set is_public = True %}
+{% endif %}
+CREATE OR REPLACE {% if is_public %}
+PUBLIC SYNONYM {{ conn|qtIdent(o_data.name) }}
+{% else %}
+SYNONYM {{ conn|qtIdent(o_data.schema, o_data.name) }}
+{% endif %}
+ FOR {{ conn|qtIdent(data.synobjschema, data.synobjname) }};
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8be2189501afaef3007968e0498d2b720efb762
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/__init__.py
@@ -0,0 +1,1770 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Table Node """
+
+import json
+import re
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify, url_for, current_app
+from flask_babel import gettext
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule, DataTypeReader, VacuumSettings
+from pgadmin.browser.server_groups.servers.utils import parse_priv_to_db
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from .utils import BaseTableView
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.foreign_key import utils as fkey_utils
+from .schema_diff_table_utils import SchemaDiffTableCompare
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ columns import utils as column_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.exclusion_constraint import utils as exclusion_utils
+from pgadmin.utils.exception import ExecuteError
+
+
+class TableModule(SchemaChildModule):
+ """
+ class TableModule(SchemaChildModule)
+
+ A module class for Table node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Table and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+ _NODE_TYPE = 'table'
+ _COLLECTION_LABEL = gettext("Tables")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the TableModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.max_ver = None
+ self.min_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=BaseTableView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ self._COLLECTION_CSS,
+ node_type=self.node_type,
+ ),
+ render_template(
+ self._NODE_CSS,
+ node_type=self.node_type,
+ ),
+ render_template(
+ self._NODE_CSS,
+ node_type='table',
+ file_name='table-inherited',
+ ),
+ render_template(
+ self._NODE_CSS,
+ node_type='table',
+ file_name='table-inherits',
+ ),
+ render_template(
+ self._NODE_CSS,
+ node_type='table',
+ file_name='table-multi-inherit',
+ ),
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+ def register(self, app, options):
+ """
+ Override the default register function to automagically register
+ sub-modules at once.
+ """
+ from .columns import blueprint as module
+ self.submodules.append(module)
+
+ from .compound_triggers import blueprint as module
+ self.submodules.append(module)
+
+ from .constraints import blueprint as module
+ self.submodules.append(module)
+
+ from .indexes import blueprint as module
+ self.submodules.append(module)
+
+ from .partitions import blueprint as module
+ self.submodules.append(module)
+
+ from .row_security_policies import blueprint as module
+ self.submodules.append(module)
+
+ from .rules import blueprint as module
+ self.submodules.append(module)
+
+ from .triggers import blueprint as module
+ self.submodules.append(module)
+
+ super().register(app, options)
+
+
+blueprint = TableModule(__name__)
+
+
+class TableView(BaseTableView, DataTypeReader, SchemaDiffTableCompare):
+ """
+ This class is responsible for generating routes for Table node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the TableView and it's base view.
+
+ * list()
+ - This function is used to list all the Table nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Table node.
+
+ * properties(gid, sid, did, scid, tid)
+ - This function will show the properties of the selected Table node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new Table object
+
+ * update(gid, sid, did, scid, tid)
+ - This function will update the data for the selected Table node
+
+ * delete(gid, sid, scid, tid):
+ - This function will drop the Table object
+
+ * truncate(gid, sid, scid, tid):
+ - This function will truncate table object
+
+ * set_trigger(gid, sid, scid, tid):
+ - This function will enable/disable trigger(s) on table object
+
+ * reset(gid, sid, scid, tid):
+ - This function will reset table object statistics
+
+ * msql(gid, sid, did, scid, tid)
+ - This function is used to return modified SQL for the selected
+ Table node
+
+ * get_sql(did, scid, tid, data)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid, tid):
+ - This function will generate sql to show it in sql pane for the
+ selected Table node.
+
+ * dependency(gid, sid, did, scid, tid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Table node.
+
+ * dependent(gid, sid, did, scid, tid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected node.
+
+ * get_types(self, gid, sid, did, scid)
+ - This function will return list of types available for columns node
+ via AJAX response
+
+ * get_oftype(self, gid, sid, did, scid, tid)
+ - This function will return list of types available for table node
+ via AJAX response
+
+ * get_inherits(self, gid, sid, did, scid, tid)
+ - This function will return list of tables availablefor inheritance
+ via AJAX response
+
+ * get_relations(self, gid, sid, did, scid, tid)
+ - This function will return list of tables available for like/relation
+ via AJAX response
+
+ * get_columns(gid, sid, did, scid, foid=None):
+ - Returns the Table Columns.
+
+ * get_table_vacuum(gid, sid, did, scid=None, tid=None):
+ - Fetch the default values for table auto-vacuum
+
+ * get_toast_table_vacuum(gid, sid, did, scid=None, tid=None)
+ - Fetch the default values for toast table auto-vacuum
+
+ * get_index_constraint_sql(self, did, tid, data):
+ - This function will generate modified sql for index constraints
+ (Primary Key & Unique)
+
+ * select_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * insert_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * update_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * delete_sql(gid, sid, did, scid, foid):
+ - Returns sql for Script
+
+ * compare(**kwargs):
+ - This function will compare the table nodes from two
+ different schemas.
+"""
+
+ node_type = blueprint.node_type
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'tid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_oftype': [{'get': 'get_oftype'}, {'get': 'get_oftype'}],
+ 'get_inherits': [{'get': 'get_inherits'}, {'get': 'get_inherits'}],
+ 'get_relations': [{'get': 'get_relations'}, {'get': 'get_relations'}],
+ 'truncate': [{'put': 'truncate'}],
+ 'reset': [{'delete': 'reset'}],
+ 'set_trigger': [{'put': 'enable_disable_triggers'}],
+ 'get_types': [{'get': 'types'}, {'get': 'types'}],
+ 'get_columns': [{'get': 'get_columns'}, {'get': 'get_columns'}],
+ 'get_table_vacuum': [{}, {'get': 'get_table_vacuum'}],
+ 'get_toast_table_vacuum': [{}, {'get': 'get_toast_table_vacuum'}],
+ 'all_tables': [{}, {'get': 'get_all_tables'}],
+ 'get_access_methods': [{}, {'get': 'get_access_methods'}],
+ 'get_table_access_methods': [{}, {'get': 'get_table_access_methods'}],
+ 'get_oper_class': [{}, {'get': 'get_oper_class'}],
+ 'get_operator': [{}, {'get': 'get_operator'}],
+ 'get_attach_tables': [
+ {'get': 'get_attach_tables'},
+ {'get': 'get_attach_tables'}],
+ 'select_sql': [{'get': 'select_sql'}],
+ 'insert_sql': [{'get': 'insert_sql'}],
+ 'update_sql': [{'get': 'update_sql'}],
+ 'delete_sql': [{'get': 'delete_sql'}],
+ 'count_rows': [{'get': 'count_rows'}],
+ 'compare': [{'get': 'compare'}, {'get': 'compare'}],
+ 'get_op_class': [{'get': 'get_op_class'}, {'get': 'get_op_class'}],
+ })
+
+ @BaseTableView.check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the table nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available table nodes
+ """
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ def get_icon_css_class(self, table_info, default_val='icon-table'):
+ if ('is_inherits' in table_info and
+ table_info['is_inherits'] > '0') or \
+ ('coll_inherits' in table_info and
+ len(table_info['coll_inherits']) > 0):
+
+ if ('is_inherited' in table_info and
+ table_info['is_inherited'] > '0')\
+ or ('relhassubclass' in table_info and
+ table_info['relhassubclass']):
+ default_val = 'icon-table-multi-inherit'
+ else:
+ default_val = 'icon-table-inherits'
+ elif ('is_inherited' in table_info and
+ table_info['is_inherited'] > '0')\
+ or ('relhassubclass' in table_info and
+ table_info['relhassubclass']):
+ default_val = 'icon-table-inherited'
+
+ return super().\
+ get_icon_css_class(table_info, default_val)
+
+ @BaseTableView.check_precondition
+ def node(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the table nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available table nodes
+ """
+ res = []
+ SQL = render_template(
+ "/".join([self.table_template_path, self._NODES_SQL]),
+ scid=scid, tid=tid
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+ if len(rset['rows']) == 0:
+ return gone(gettext("Could not find the table."))
+
+ table_information = rset['rows'][0]
+ icon = self.get_icon_css_class(table_information)
+
+ res = self.blueprint.generate_browser_node(
+ table_information['oid'],
+ scid,
+ table_information['name'],
+ icon=icon,
+ tigger_count=table_information['triggercount'],
+ has_enable_triggers=table_information['has_enable_triggers'],
+ is_partitioned=self.is_table_partitioned(table_information)
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function is used to list all the table nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+
+ Returns:
+ JSON of available table nodes
+ """
+ res = []
+ SQL = render_template(
+ "/".join([self.table_template_path, self._NODES_SQL]),
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ icon = self.get_icon_css_class(row)
+
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=icon,
+ tigger_count=row['triggercount'],
+ has_enable_triggers=row['has_enable_triggers'],
+ is_partitioned=self.is_table_partitioned(row),
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_all_tables(self, gid, sid, did, scid, tid=None):
+ """
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ Returns the lits of tables required for constraints.
+ """
+ try:
+ SQL = render_template(
+ "/".join([
+ self.table_template_path, 'get_tables_for_constraints.sql'
+ ]),
+ show_sysobj=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res['rows'],
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_table_vacuum(self, gid, sid, did, scid=None, tid=None):
+ """
+ Fetch the default values for table auto-vacuum
+ fields, return an array of
+ - label
+ - name
+ - setting
+ values
+ """
+ res = self.get_vacuum_table_settings(self.conn, sid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_toast_table_vacuum(self, gid, sid, did, scid=None, tid=None):
+ """
+ Fetch the default values for toast table auto-vacuum
+ fields, return an array of
+ - label
+ - name
+ - setting
+ values
+ """
+ res = self.get_vacuum_toast_settings(self.conn, sid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_access_methods(self, gid, sid, did, scid, tid=None):
+ """
+ This function returns access methods.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ res = exclusion_utils.get_access_methods(self.conn)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_table_access_methods(self, gid, sid, did, scid, tid=None):
+ """
+ This function returns access methods for table.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ Returns list of access methods for table
+ """
+ res = BaseTableView.get_access_methods(self)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_oper_class(self, gid, sid, did, scid, tid=None):
+ """
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ data = request.args if request.args else None
+ try:
+ if data and 'indextype' in data:
+ result = exclusion_utils.get_oper_class(
+ self.conn, data['indextype'])
+
+ return make_json_response(
+ data=result,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_operator(self, gid, sid, did, scid, tid=None):
+ """
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ data = request.args
+ try:
+ result = exclusion_utils.get_operator(
+ self.conn, data.get('col_type', None),
+ self.blueprint.show_system_objects)
+
+ return make_json_response(
+ data=result,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def properties(self, gid, sid, did, scid, tid):
+ """
+ This function will show the properties of the selected table node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of selected table node
+ """
+ status, res = self._fetch_table_properties(did, scid, tid)
+ if not status:
+ return res
+ if not res['rows']:
+ return gone(gettext(self.not_found_error_msg()))
+
+ return super().properties(
+ gid, sid, did, scid, tid, res=res
+ )
+
+ @BaseTableView.check_precondition
+ def get_op_class(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of op_class method
+ for each access methods available via AJAX response
+ """
+ res = dict()
+ try:
+
+ # for row in rset['rows']:
+ # # Fetching all the op_classes for each access method
+ SQL = render_template(
+ "/".join([self.table_template_path, 'get_op_class.sql'])
+ )
+ status, result = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ op_class_list = []
+
+ for r in result['rows']:
+ op_class_list.append({'label': r['opcname'],
+ 'value': r['opcname']})
+
+ return make_json_response(
+ data=op_class_list,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def types(self, gid, sid, did, scid, tid=None, clid=None):
+ """
+ Returns:
+ This function will return list of types available for column node
+ for node-ajax-control
+ """
+ condition = self.get_types_condition_sql(
+ self.blueprint.show_system_objects)
+
+ status, types = self.get_types(self.conn, condition, True, sid)
+
+ if not status:
+ return internal_server_error(errormsg=types)
+
+ return make_json_response(
+ data=types,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def get_columns(self, gid, sid, did, scid, tid=None):
+ """
+ Returns the Table Columns.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ JSON Array with below parameters.
+ name: Column Name
+ ctype: Column Data Type
+ inherited_from: Parent Table from which the related column
+ is inheritted.
+ """
+ res = []
+ data = request.args if request.args else None
+ try:
+ if data and 'tid' in data:
+ SQL = render_template(
+ "/".join([
+ self.table_template_path,
+ self._GET_COLUMNS_FOR_TABLE_SQL
+ ]),
+ tid=data['tid'], conn=self.conn
+ )
+ elif data and 'tname' in data:
+ SQL = render_template(
+ "/".join([
+ self.table_template_path,
+ self._GET_COLUMNS_FOR_TABLE_SQL
+ ]),
+ tname=data['tname'], conn=self.conn
+ )
+
+ if SQL:
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ res = res['rows']
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_oftype(self, gid, sid, did, scid, tid=None):
+ """
+ Returns:
+ This function will return list of types available for table node
+ for node-ajax-control
+ """
+ res = []
+ try:
+ SQL = render_template(
+ "/".join([self.table_template_path, 'get_oftype.sql']),
+ scid=scid,
+ server_type=self.manager.server_type,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ for row in rset['rows']:
+ # Get columns for all 'OF TYPES'.
+ SQL = render_template(
+ "/".join(
+ [self.table_template_path,
+ self._GET_COLUMNS_FOR_TABLE_SQL]
+ ), tid=row['oid'], conn=self.conn
+ )
+
+ status, type_cols = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=type_cols)
+
+ res.append({
+ 'label': row['typname'],
+ 'value': row['typname'],
+ 'tid': row['oid'],
+ 'oftype_columns': type_cols['rows']
+ })
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_inherits(self, gid, sid, did, scid, tid=None):
+ """
+ Returns:
+ This function will return list of tables available for inheritance
+ while creating new table
+ """
+ try:
+ res = []
+ SQL = render_template(
+ "/".join([self.table_template_path, 'get_inherits.sql']),
+ show_system_objects=self.blueprint.show_system_objects,
+ tid=tid,
+ scid=scid,
+ server_type=self.manager.server_type
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ for row in rset['rows']:
+ res.append(
+ {'label': row['inherits'], 'value': row['inherits'],
+ 'tid': row['oid']
+ }
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_attach_tables(self, gid, sid, did, scid, tid=None):
+ """
+ Returns:
+ This function will return list of tables available to be attached
+ to the partitioned table.
+ """
+ try:
+ res = []
+ SQL = render_template(
+ "/".join([
+ self.partition_template_path, 'get_attach_tables.sql'
+ ]),
+ tid=tid
+ )
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['table_name'], 'value': row['oid']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def get_relations(self, gid, sid, did, scid, tid=None):
+ """
+ Returns:
+ This function will return list of tables available for
+ like/relation combobox while creating new table
+ """
+ res = []
+ try:
+ SQL = render_template(
+ "/".join([self.table_template_path, 'get_relations.sql']),
+ show_sys_objects=self.blueprint.show_system_objects,
+ server_type=self.manager.server_type
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ for row in rset['rows']:
+ res.append(
+ {
+ 'label': row['like_relation'],
+ 'value': row['like_relation']
+ }
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _parser_data_input_from_client(self, data):
+ """
+ This function is used to parse the data.
+ :param data:
+ :return:
+ """
+ # Parse privilege data coming from client according to database format
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)
+
+ # Parse & format columns
+ data = column_utils.parse_format_columns(data)
+ data = TableView.check_and_convert_name_to_string(data)
+
+ # 'coll_inherits' is Array but it comes as string from browser
+ # We will convert it again to list
+ if 'coll_inherits' in data and \
+ isinstance(data['coll_inherits'], str):
+ data['coll_inherits'] = json.loads(
+ data['coll_inherits']
+ )
+
+ if 'foreign_key' in data:
+ for c in data['foreign_key']:
+ schema, table = fkey_utils.get_parent(
+ self.conn, c['columns'][0]['references'])
+ c['remote_schema'] = schema
+ c['remote_table'] = table
+
+ def _check_for_table_partitions(self, data):
+ """
+ This function is used to check for table partition.
+ :param data:
+ :return:
+ """
+ partitions_sql = ''
+ if self.is_table_partitioned(data):
+ data['relkind'] = 'p'
+ # create partition scheme
+ data['partition_scheme'] = self.get_partition_scheme(data)
+ partitions_sql = self.get_partitions_sql(data)
+ return partitions_sql
+
+ @BaseTableView.check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ required_args = [
+ 'name'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ # Parse privilege data coming from client according to database format
+ self._parser_data_input_from_client(data)
+
+ try:
+ partitions_sql = self._check_for_table_partitions(data)
+
+ # Update the vacuum table settings.
+ BaseTableView.update_vacuum_settings(self, 'vacuum_table', data)
+ # Update the vacuum toast table settings.
+ BaseTableView.update_vacuum_settings(self, 'vacuum_toast', data)
+
+ sql = render_template(
+ "/".join([self.table_template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+
+ # Append SQL for partitions
+ sql += '\n' + partitions_sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # PostgreSQL truncates the table name to 63 characters.
+ # Have to truncate the name like PostgreSQL to get the
+ # proper OID
+ CONST_MAX_CHAR_COUNT = 63
+
+ if len(data['name']) > CONST_MAX_CHAR_COUNT:
+ data['name'] = data['name'][0:CONST_MAX_CHAR_COUNT]
+
+ # Get updated schema oid
+ sql = render_template(
+ "/".join([self.table_template_path, self._GET_SCHEMA_OID_SQL]),
+ tname=data['name'],
+ sname=data['schema'],
+ conn=self.conn
+ )
+
+ status, new_scid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=new_scid)
+
+ # we need oid to add object in tree at browser
+ sql = render_template(
+ "/".join([self.table_template_path, self._OID_SQL]),
+ scid=new_scid, data=data, conn=self.conn
+ )
+
+ status, tid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ new_scid,
+ data['name'],
+ icon=self.get_icon_css_class(data),
+ is_partitioned=self.is_table_partitioned(data)
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def update(self, gid, sid, did, scid, tid):
+ """
+ This function will update an existing table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ try:
+ status, res = self._fetch_table_properties(did, scid, tid)
+ if not status:
+ return res
+
+ lock_on_table = self.get_table_locks(did, res['rows'][0])
+ if lock_on_table != '':
+ return ExecuteError(
+ error_msg=str(lock_on_table.json['info']))
+
+ return super().update(
+ gid, sid, did, scid, tid, data=data, res=res)
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def delete(self, gid, sid, did, scid, tid=None):
+ """
+ This function will deletes the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ if tid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [tid]}
+
+ try:
+ for tid in data['ids']:
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ self.not_found_error_msg() + '\n'
+ )
+ )
+
+ lock_on_table = self.get_table_locks(did, res['rows'][0])
+ if lock_on_table != '':
+ return lock_on_table
+
+ status, res = super().delete(gid, sid, did,
+ scid, tid, res)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Table dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def truncate(self, gid, sid, did, scid, tid):
+ """
+ This function will truncate the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+
+ try:
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ return super().truncate(
+ gid, sid, did, scid, tid, res
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def enable_disable_triggers(self, gid, sid, did, scid, tid):
+ """
+ This function will enable/disable trigger(s) on the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ # Below will decide if it's simple drop or drop with cascade call
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ # Convert str 'true' to boolean type
+ is_enable_trigger = data['is_enable_trigger']
+
+ try:
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ data = res['rows'][0]
+
+ SQL = render_template(
+ "/".join([
+ self.table_template_path, 'enable_disable_trigger.sql'
+ ]),
+ data=data, is_enable_trigger=is_enable_trigger
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template(
+ "/".join([
+ self.trigger_template_path, 'get_enabled_triggers.sql'
+ ]),
+ tid=tid
+ )
+
+ status, trigger_res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Trigger(s) have been disabled")
+ if is_enable_trigger == 'D'
+ else gettext("Trigger(s) have been enabled"),
+ data={
+ 'id': tid,
+ 'scid': scid,
+ 'has_enable_triggers': trigger_res
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def reset(self, gid, sid, did, scid, tid):
+ """
+ This function will reset statistics of table
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ return BaseTableView.reset_statistics(self, scid, tid)
+
+ @BaseTableView.check_precondition
+ def get_sql_from_table_diff(self, **kwargs):
+ """
+ This function will create sql on the basis the difference of 2 tables
+ """
+ data = dict()
+ did = kwargs['did']
+ scid = kwargs['scid']
+ tid = kwargs['tid']
+ diff_data = kwargs['diff_data'] if 'diff_data' in kwargs else None
+ json_resp = kwargs['json_resp'] if 'json_resp' in kwargs else True
+ target_schema = kwargs['target_schema'] \
+ if 'target_schema' in kwargs else None
+ if_exists_flag = kwargs['add_not_exists_clause'] \
+ if 'add_not_exists_clause' in kwargs else False
+
+ if diff_data:
+ return self._fetch_sql(did, scid, tid, diff_data, json_resp)
+ else:
+ main_sql = []
+
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ if status:
+ data = res['rows'][0]
+
+ # Update autovacuum properties
+ self.update_autovacuum_properties(data)
+
+ if target_schema:
+ data['schema'] = target_schema
+
+ sql, _ = BaseTableView.get_reverse_engineered_sql(
+ self, did=did, scid=scid, tid=tid, main_sql=main_sql,
+ data=data, json_resp=json_resp,
+ add_not_exists_clause=if_exists_flag)
+
+ return sql
+
+ @BaseTableView.check_precondition
+ def msql(self, gid, sid, did, scid, tid=None):
+ """
+ This function will create modified sql for table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ return self._fetch_sql(did, scid, tid, data)
+
+ def _fetch_sql(self, did, scid, tid, data, json_resp=True):
+ res = None
+
+ if tid is not None:
+ status, res = self._fetch_table_properties(did, scid, tid)
+ if not status:
+ return res
+
+ SQL, _ = self.get_sql(did, scid, tid, data, res)
+ SQL = re.sub('\n{2,}', '\n\n', SQL)
+ SQL = SQL.strip('\n')
+
+ if not json_resp:
+ return SQL
+
+ if SQL == '':
+ SQL = "--modified SQL"
+
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def dependents(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependents and return ajax response
+ for the table node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ return BaseTableView.get_table_dependents(self, tid)
+
+ @BaseTableView.check_precondition
+ def dependencies(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependencies and return ajax response
+ for the table node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ return BaseTableView.get_table_dependencies(self, tid)
+
+ @BaseTableView.check_precondition
+ def sql(self, gid, sid, did, scid, tid):
+ """
+ This function will creates reverse engineered sql for
+ the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ main_sql = []
+
+ status, res = self._fetch_table_properties(did, scid, tid)
+ if not status:
+ return res
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ data = res['rows'][0]
+
+ return BaseTableView.get_reverse_engineered_sql(
+ self, did=did, scid=scid, tid=tid, main_sql=main_sql, data=data,
+ add_not_exists_clause=True)
+
+ @BaseTableView.check_precondition
+ def select_sql(self, gid, sid, did, scid, tid):
+ """
+ SELECT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ SELECT Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ data = res['rows'][0]
+ data = self._formatter(did, scid, tid, data)
+
+ columns = []
+
+ # Now we have all list of columns which we need
+ if 'columns' in data:
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ else:
+ columns = '*'
+
+ sql = "SELECT {0}\n\tFROM {1};".format(
+ columns,
+ self.qtIdent(self.conn, data['schema'], data['name'])
+ )
+ return ajax_response(response=sql)
+
+ @BaseTableView.check_precondition
+ def insert_sql(self, gid, sid, did, scid, tid):
+ """
+ INSERT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ INSERT Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ data = res['rows'][0]
+ data = self._formatter(did, scid, tid, data)
+
+ columns = []
+ values = []
+
+ # Now we have all list of columns which we need
+ if 'columns' in data:
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+ values.append('?')
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ values = ", ".join(values)
+ sql = "INSERT INTO {0}(\n\t{1})\n\tVALUES ({2});".format(
+ self.qtIdent(self.conn, data['schema'], data['name']),
+ columns, values
+ )
+ else:
+ sql = gettext('-- Please create column(s) first...')
+
+ return ajax_response(response=sql)
+
+ @BaseTableView.check_precondition
+ def update_sql(self, gid, sid, did, scid, tid):
+ """
+ UPDATE script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ UPDATE Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ data = res['rows'][0]
+ data = self._formatter(did, scid, tid, data)
+
+ columns = []
+
+ # Now we have all list of columns which we need
+ if 'columns' in data:
+ for c in data['columns']:
+ columns.append(self.qtIdent(self.conn, c['name']))
+
+ if len(columns) > 0:
+ if len(columns) == 1:
+ columns = columns[0]
+ else:
+ columns = "=?, ".join(columns)
+ columns += "=?"
+
+ sql = "UPDATE {0}\n\tSET {1}\n\tWHERE ;".format(
+ self.qtIdent(self.conn, data['schema'], data['name']),
+ columns
+ )
+ else:
+ sql = gettext('-- Please create column(s) first...')
+
+ return ajax_response(response=sql)
+
+ @BaseTableView.check_precondition
+ def delete_sql(self, gid, sid, did, scid, tid, json_resp=True):
+ """
+ DELETE script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns:
+ DELETE Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(self.not_found_error_msg()))
+
+ data = res['rows'][0]
+
+ sql = "DELETE FROM {0}\n\tWHERE ;".format(
+ self.qtIdent(self.conn, data['schema'], data['name'])
+ )
+
+ if not json_resp:
+ return sql
+
+ return ajax_response(response=sql)
+
+ @BaseTableView.check_precondition
+ def statistics(self, gid, sid, did, scid, tid=None):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns the statistics for a particular table if tid is specified,
+ otherwise it will return statistics for all the tables in that
+ schema.
+ """
+ return BaseTableView.get_table_statistics(self, scid, tid)
+
+ @BaseTableView.check_precondition
+ def count_rows(self, gid, sid, did, scid, tid):
+ """
+ Count the rows of a table.
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+
+ Returns the total rows of a table.
+ """
+ data = {}
+ data['schema'], data['name'] = \
+ super().get_schema_and_table_name(tid)
+
+ if data['name'] is None:
+ return gone(gettext(self.not_found_error_msg()))
+
+ SQL = render_template(
+ "/".join(
+ [self.table_template_path, 'get_table_row_count.sql']
+ ), data=data
+ )
+
+ status, count = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=count)
+
+ return make_json_response(
+ status=200,
+ info=gettext("Table rows counted: {}").format(count),
+ data={'total_rows': count}
+ )
+
+ @BaseTableView.check_precondition
+ def get_drop_sql(self, sid, did, scid, tid):
+ SQL = render_template("/".join(
+ [self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ sql = ''
+
+ if status:
+ self.cmd = 'delete'
+ sql = super().get_delete_sql(res['rows'][0])
+ self.cmd = None
+
+ return sql
+
+ @BaseTableView.check_precondition
+ def fetch_tables(self, sid, did, scid, tid=None, with_serial_cols=False):
+ """
+ This function will fetch the list of all the tables
+ and will be used by schema diff.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :param with_serial_cols:
+ :return: Table dataset
+ """
+
+ status, res = BaseTableView.fetch_tables(self, sid, did, scid, tid,
+ with_serial_cols)
+ if not status:
+ current_app.logger.error(res)
+ return False
+
+ return res
+
+ def get_submodule_template_path(self, module_name):
+ """
+ This function is used to get the template path based on module name.
+ :param module_name:
+ :return:
+ """
+ template_path = None
+ if module_name == 'index':
+ template_path = self.index_template_path
+ elif module_name == 'trigger':
+ template_path = self.trigger_template_path
+ elif module_name == 'rule':
+ template_path = self.rules_template_path
+ elif module_name == 'compound_trigger':
+ template_path = self.compound_trigger_template_path
+ elif module_name == 'row_security_policy':
+ template_path = self.row_security_policies_template_path
+
+ return template_path
+
+ @BaseTableView.check_precondition
+ def get_table_submodules_dependencies(self, **kwargs):
+ """
+ This function is used to get the dependencies of table and it's
+ submodules.
+ :param kwargs:
+ :return:
+ """
+ tid = kwargs['tid']
+ table_dependencies = []
+ table_deps = self.get_dependencies(self.conn, tid, where=None,
+ show_system_objects=None,
+ is_schema_diff=True)
+ if len(table_deps) > 0:
+ table_dependencies.extend(table_deps)
+
+ # Fetch foreign key referenced table which is considered as
+ # dependency.
+ status, fkey_deps = fkey_utils.get_fkey_dependencies(self.conn, tid)
+ if not status:
+ return internal_server_error(errormsg=fkey_deps)
+
+ if len(fkey_deps) > 0:
+ table_dependencies.extend(fkey_deps)
+
+ # Iterate all the submodules of the table and fetch the dependencies.
+ for module in self.tables_sub_modules:
+ module_view = SchemaDiffRegistry.get_node_view(module)
+ template_path = self.get_submodule_template_path(module)
+
+ SQL = render_template("/".join([template_path,
+ 'nodes.sql']), tid=tid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ result = module_view.get_dependencies(
+ self.conn, row['oid'], where=None,
+ show_system_objects=None, is_schema_diff=True)
+ if len(result) > 0:
+ table_dependencies.extend(result)
+
+ # Remove the same table from the dependency list
+ for item in table_dependencies:
+ if 'oid' in item and item['oid'] == tid:
+ table_dependencies.remove(item)
+
+ return table_dependencies
+
+
+SchemaDiffRegistry(blueprint.node_type, TableView)
+TableView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/base_partition_table.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/base_partition_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf9686ab9f4167c393953b3d4cd302233f5a3d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/base_partition_table.py
@@ -0,0 +1,30 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+
+class BasePartitionTable:
+ def is_table_partitioned(self, table_info):
+ if (
+ getattr(self, 'node_type', '') == 'partition' or
+ ('is_partitioned' in table_info and table_info['is_partitioned'])
+ ):
+ return True
+ return False
+
+ def get_icon_css_class(self, table_info, default_val='icon-table'):
+ if self.is_table_partitioned(table_info):
+ return 'icon-partition_table'
+ return default_val
+
+ def get_partition_icon_css_class(self, table_info,
+ default_val='icon-partition'):
+ if 'is_sub_partitioned' in table_info and \
+ table_info['is_sub_partitioned']:
+ return 'icon-sub_partition_table'
+ return default_val
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..209955af9571e15786d3b8ee314471d3d4ca3087
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/__init__.py
@@ -0,0 +1,952 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Column Node """
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import DataTypeReader
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ columns import utils as column_utils
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.ajax import ColParamsJSONDecoder
+
+
+class ColumnsModule(CollectionNodeModule):
+ """
+ class ColumnsModule(CollectionNodeModule)
+
+ A module class for Column node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Column and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'column'
+ _COLLECTION_LABEL = gettext("Columns")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the ColumnModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs)
+ if self.has_nodes(sid, did, scid=scid,
+ tid=kwargs.get('tid', kwargs.get('vid', None)),
+ base_template_path=ColumnsView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ kwargs['tid'] if 'tid' in kwargs else kwargs['vid']
+ )
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return False
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = ColumnsModule(__name__)
+
+
+class ColumnsView(PGChildNodeView, DataTypeReader):
+ """
+ This class is responsible for generating routes for Column node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the ColumnView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Column nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Column node.
+
+ * properties(gid, sid, did, scid, tid, clid)
+ - This function will show the properties of the selected Column node
+
+ * create(gid, sid, did, scid, tid)
+ - This function will create the new Column object
+
+ * update(gid, sid, did, scid, tid, clid)
+ - This function will update the data for the selected Column node
+
+ * delete(self, gid, sid, scid, tid, clid):
+ - This function will drop the Column object
+
+ * msql(gid, sid, did, scid, tid, clid)
+ - This function is used to return modified SQL for the selected
+ Column node
+
+ * get_sql(data, scid, tid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Column node.
+
+ * dependency(gid, sid, did, scid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Column node.
+
+ * dependent(gid, sid, did, scid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Column node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Column"
+ BASE_TEMPLATE_PATH = 'columns/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ # Here we specify type as any because table
+ # are also has '-' in them if they are system table
+ {'type': 'string', 'id': 'clid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.qtTypeIdent = driver.qtTypeIdent
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ self.foreign_table_column_template_path = compile_template_path(
+ 'foreign_table_columns/sql', self.manager.version)
+
+ # Allowed ACL for column 'Select/Update/Insert/References'
+ self.acl = ['a', 'r', 'w', 'x']
+
+ # We need parent's name eg table name and schema name
+ schema, table = column_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the schema nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available column nodes
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ data = res['rows']
+ for column in data:
+ column_utils.column_formatter(self.conn, tid, column['attnum'],
+ column)
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid, clid=None):
+ """
+ This function will used to create all the child node within that
+ collection. Here it will create all the schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available schema child nodes
+ """
+ res = []
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ tid=tid,
+ clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects,
+ conn=self.conn
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+ if clid is not None:
+ if len(rset['rows']) == 0:
+ return gone(
+ errormsg=self.not_found_error_msg()
+ )
+ row = rset['rows'][0]
+ return make_json_response(
+ data=self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-column",
+ datatype=row['datatype'], # We need datatype somewhere in,
+ description=row['description']
+ ),
+ status=200
+ )
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-column",
+ datatype=row['datatype'], # We need datatype somewhere in
+ description=row['description']
+ )) # exclusion constraint.
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, clid):
+ """
+ This function will show the properties of the selected schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+
+ Returns:
+ JSON of selected schema node
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+ data = column_utils.column_formatter(self.conn, tid, clid, data)
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will creates new the schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ try:
+ data[k] = json.loads(v, cls=ColParamsJSONDecoder)
+ except TypeError:
+ data[k] = v
+
+ required_args = {
+ 'name': 'Name',
+ 'cltype': 'Type'
+ }
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(required_args[arg])
+ )
+
+ # Parse privilege data coming from client according to database format
+ if 'attacl' in data:
+ data['attacl'] = parse_priv_to_db(data['attacl'], self.acl)
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+ if len(data['table']) == 0:
+ return gone(gettext(self.not_found_error_msg('Table')))
+
+ # check type for '[]' in it
+ data['cltype'], data['hasSqrBracket'] = \
+ column_utils.type_formatter(data['cltype'])
+ data = column_utils.convert_length_precision_to_string(data)
+
+ # Check if node is foreign_table_column
+ template_path = self.foreign_table_column_template_path \
+ if self.node_type == 'foreign_table_column' else self.template_path
+
+ SQL = render_template("/".join([template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need oid to add object in tree at browser
+ SQL = render_template(
+ "/".join([self.template_path, 'get_position.sql']),
+ tid=tid, data=data, conn=self.conn
+ )
+ status, clid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ clid,
+ tid,
+ data['name'],
+ icon="icon-column"
+ )
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, clid=None):
+ """
+ This function will updates the existing schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+ """
+ if clid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [clid]}
+
+ # We will first fetch the column name for current request
+ # so that we create template for dropping column
+ try:
+ for clid in data['ids']:
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ data = dict(res['rows'][0])
+ # We will add table & schema as well
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ # Check if node is foreign_table_column
+ template_path = self.foreign_table_column_template_path \
+ if self.node_type == 'foreign_table_column' \
+ else self.template_path
+
+ SQL = render_template("/".join([template_path,
+ self._DELETE_SQL]),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Column is dropped"),
+ data={
+ 'id': clid,
+ 'tid': tid
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, clid):
+ """
+ This function will updates the existing schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ # check type for '[]' in it
+ if 'cltype' in data:
+ data['cltype'], data['hasSqrBracket'] = \
+ column_utils.type_formatter(data['cltype'])
+
+ SQL, name = self.get_sql(scid, tid, clid, data)
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ clid,
+ tid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, clid=None):
+ """
+ This function will generates modified sql for schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID (When working with existing column)
+ """
+ data = dict()
+ for k, v in request.args.items():
+ data[k] = json.loads(v, cls=ColParamsJSONDecoder)
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ # check type for '[]' in it
+ if 'cltype' in data:
+ data['cltype'], data['hasSqrBracket'] = \
+ column_utils.type_formatter(data['cltype'])
+
+ try:
+ SQL, _ = self.get_sql(scid, tid, clid, data)
+ if not isinstance(SQL, str):
+ return SQL
+
+ SQL = SQL.strip('\n').strip(' ')
+ if SQL == '':
+ SQL = "--modified SQL"
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _parse_acl_to_db_parsing(self, data, old_data):
+ """
+ Convert acl coming from client to required db parsing format.
+ :param data: Data.
+ :param old_data: old data for comparision and get name.
+ """
+ # If name is not present in data then
+ # we will fetch it from old data, we also need schema & table name
+ if 'name' not in data:
+ data['name'] = old_data['name']
+
+ # Convert acl coming from client in db parsing format
+ key = 'attacl'
+ if key in data and data[key] is not None:
+ if 'added' in data[key]:
+ data[key]['added'] = parse_priv_to_db(
+ data[key]['added'], self.acl
+ )
+ if 'changed' in data[key]:
+ data[key]['changed'] = parse_priv_to_db(
+ data[key]['changed'], self.acl
+ )
+ if 'deleted' in data[key]:
+ data[key]['deleted'] = parse_priv_to_db(
+ data[key]['deleted'], self.acl
+ )
+
+ def _get_sql_for_create(self, data, is_sql):
+ """
+ Get sql for create column model.
+ :param data: Data.
+ :param is_sql: flag for get sql.
+ :return: if any error return error else return sql.
+ """
+ required_args = [
+ 'name',
+ 'cltype'
+ ]
+
+ for arg in required_args:
+ if arg not in data:
+ return True, gettext('-- definition incomplete'), ''
+
+ # We will convert privileges coming from client required
+ # in server side format
+ if 'attacl' in data:
+ data['attacl'] = parse_priv_to_db(data['attacl'],
+ self.acl)
+
+ # Check if node is foreign_table_column
+ template_path = self.foreign_table_column_template_path \
+ if self.node_type == 'foreign_table_column' \
+ else self.template_path
+
+ # If the request for new object which do not have did
+ sql = render_template(
+ "/".join([template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn, is_sql=is_sql
+ )
+
+ return False, '', sql
+
+ def _check_type(self, data, old_data):
+ """
+ Check cltype and get required data form it.
+ :param data: Data.
+ :param old_data: old data for check and get default values.
+ """
+ # check type for '[]' in it
+ if 'cltype' in old_data:
+ old_data['cltype'], old_data['hasSqrBracket'] = \
+ column_utils.type_formatter(old_data['cltype'])
+
+ if 'cltype' in data and data['cltype'] != old_data['cltype']:
+ length, precision, _ = \
+ self.get_length_precision(data['cltype'])
+
+ # if new datatype does not have length or precision
+ # then we cannot apply length or precision of old
+ # datatype to new one.
+ if not length:
+ old_data['attlen'] = -1
+ if not precision:
+ old_data['attprecision'] = None
+
+ def get_sql(self, scid, tid, clid, data, is_sql=False):
+ """
+ This function will generate sql from model data
+ """
+ data = column_utils.convert_length_precision_to_string(data)
+
+ if clid is not None:
+ # Check if node is foreign_table_column
+ template_path = self.foreign_table_column_template_path \
+ if self.node_type == 'foreign_table_column' \
+ else self.template_path
+
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ old_data = dict(res['rows'][0])
+
+ is_view_only = True if 'is_view_only' in old_data and old_data[
+ 'is_view_only'] else False
+
+ if 'seqcycle' in old_data and old_data['seqcycle'] is False:
+ old_data['seqcycle'] = None
+ # We will add table & schema as well
+ old_data = column_utils.column_formatter(
+ self.conn, tid, clid, old_data)
+
+ self._check_type(data, old_data)
+ self._parse_acl_to_db_parsing(data, old_data)
+
+ sql = render_template(
+ "/".join([template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn,
+ is_view_only=is_view_only
+ )
+ else:
+ is_error, errmsg, sql = self._get_sql_for_create(data, is_sql)
+ if is_error:
+ return errmsg
+
+ return sql, data['name'] if 'name' in data else old_data['name']
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, clid):
+ """
+ This function will generates reverse engineered sql for schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+ """
+ try:
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = dict(res['rows'][0])
+ # We do not want to display length as -1 in create query
+ if 'attlen' in data and data['attlen'] == -1:
+ data['attlen'] = ''
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+ # check type for '[]' in it
+ if 'cltype' in data:
+ data['cltype'], data['hasSqrBracket'] = \
+ column_utils.type_formatter(data['cltype'])
+
+ # We will add table & schema as well
+ # Passing edit_types_list param so that it does not fetch
+ # edit types. It is not required here.
+ data = column_utils.column_formatter(self.conn, tid, clid,
+ data, [])
+
+ SQL, _ = self.get_sql(scid, tid, None, data, is_sql=True)
+ if not isinstance(SQL, str):
+ return SQL
+
+ sql_header = "-- Column: {0}\n\n-- ".format(
+ self.qtIdent(
+ self.conn, data['schema'], data['table'], data['name'])
+ )
+
+ # Join delete sql
+ template_path = self.foreign_table_column_template_path \
+ if self.node_type == 'foreign_table_column' \
+ else self.template_path
+ sql_header += render_template(
+ "/".join([template_path, self._DELETE_SQL]),
+ data=data, conn=self.conn
+ )
+ SQL = sql_header + '\n\n' + SQL
+
+ return ajax_response(response=SQL.strip('\n'))
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, clid):
+ """
+ This function get the dependents and return ajax response
+ for the column node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+ """
+ # Specific condition for column which we need to append
+ where = "WHERE dep.refobjid={0}::OID AND dep.refobjsubid={1}".format(
+ tid, clid
+ )
+
+ dependents_result = self.get_dependents(
+ self.conn, clid, where=where
+ )
+
+ # Specific sql to run againt column to fetch dependents
+ SQL = render_template("/".join([self.template_path,
+ 'depend.sql']), where=where)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in res['rows']:
+ ref_name = row['refname']
+ if ref_name is None:
+ continue
+
+ dep_type = ''
+ dep_str = row['deptype']
+ if dep_str == 'a':
+ dep_type = 'auto'
+ elif dep_str == 'n':
+ dep_type = 'normal'
+ elif dep_str == 'i':
+ dep_type = 'internal'
+
+ dependents_result.append(
+ {'type': 'sequence', 'name': ref_name, 'field': dep_type}
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, clid):
+ """
+ This function get the dependencies and return ajax response
+ for the column node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ clid: Column ID
+
+ """
+
+ # Specific condition for column which we need to append
+ where = "WHERE dep.objid={0}::OID AND dep.objsubid={1}".format(
+ tid, clid
+ )
+
+ # Specific condition for column which we need to append
+ dependencies_result = self.get_dependencies(
+ self.conn, clid, where
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, tid, clid):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ seid: Sequence Id
+
+ Returns the statistics for a particular object if seid is specified
+ """
+ # Fetch column name
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, clid=clid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = dict(res['rows'][0])
+ column = data['name']
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'stats.sql']),
+ conn=self.conn, schema=self.schema,
+ table=self.table, column=column
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+
+ColumnsView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/coll-column.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/coll-column.svg
new file mode 100644
index 0000000000000000000000000000000000000000..7688f535569dcb8daab02d27edb759e3dc42dded
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/coll-column.svg
@@ -0,0 +1 @@
+coll-column
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/column.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/column.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5afb75a9962771bc0207b56440075a4f463de57f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/img/column.svg
@@ -0,0 +1 @@
+column
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
new file mode 100644
index 0000000000000000000000000000000000000000..e4e202322e23f2cd5fe4aad384a23af201cdb0cb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.js
@@ -0,0 +1,132 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeColumnSchema } from './column.ui';
+import _ from 'lodash';
+
+define('pgadmin.node.column', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgBrowser, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-column']) {
+ pgBrowser.Nodes['coll-column'] =
+ pgBrowser.Collection.extend({
+ node: 'column',
+ label: gettext('Columns'),
+ type: 'coll-column',
+ columns: ['name', 'cltype', 'is_pk','attnotnull', 'description'],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: false,
+ });
+ }
+
+ if (!pgBrowser.Nodes['column']) {
+ pgBrowser.Nodes['column'] = pgBrowser.Node.extend({
+ // Foreign table is added in parent_type to support triggers on
+ // foreign table where we need column information.
+ parent_type: ['table', 'view', 'mview', 'foreign_table'],
+ collection_type: ['coll-table', 'coll-view', 'coll-mview'],
+ type: 'column',
+ label: gettext('Column'),
+ hasSQL: true,
+ sqlAlterHelp: 'sql-altertable.html',
+ sqlCreateHelp: 'sql-altertable.html',
+ dialogHelp: url_for('help.static', {'filename': 'column_dialog.html'}),
+ canDrop: function(itemData, item){
+ let node = pgBrowser.tree.findNodeByDomElement(item);
+
+ if (!node)
+ return false;
+
+ // Only a column of a table can be droped, and only when it is not of
+ // catalog.
+ return node.anyParent(
+ (parentNode) => (
+ parentNode.getData()._type === 'table' &&
+ !parentNode.anyParent(
+ (grandParentNode) => (
+ grandParentNode.getData()._type === 'catalog'
+ )
+ )
+ )
+ );
+ },
+ hasDepends: true,
+ hasStatistics: true,
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_column_on_coll', node: 'coll-column', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_column', node: 'column', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_column_onTable', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_column_onView', node: 'view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Column...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ ]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser);
+ },
+ // Below function will enable right click menu for creating column
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [];
+ // To iterate over tree to check parent node
+ while (i) {
+ // If it is schema then allow user to create table
+ if (_.indexOf(['schema'], d._type) > -1) {
+ return true;
+ }
+ else if (_.indexOf(['view', 'coll-view',
+ 'mview',
+ 'coll-mview'], d._type) > -1) {
+ parents.push(d._type);
+ break;
+ }
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ return !(_.indexOf(parents, 'catalog') > -1 ||
+ _.indexOf(parents, 'coll-view') > -1 ||
+ _.indexOf(parents, 'coll-mview') > -1 ||
+ _.indexOf(parents, 'mview') > -1 ||
+ _.indexOf(parents, 'view') > -1);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['column'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..ef7c0fd4a5f6bb2f7bf9cadec94cbc3abfc276f3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/static/js/column.ui.js
@@ -0,0 +1,673 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import VariableSchema from 'top/browser/server_groups/servers/static/js/variable.ui';
+import SecLabelSchema from 'top/browser/server_groups/servers/static/js/sec_label.ui';
+import _ from 'lodash';
+import { isEmptyString } from '../../../../../../../../../static/js/validators';
+import { getNodePrivilegeRoleSchema } from '../../../../../../static/js/privilege.ui';
+import { getNodeAjaxOptions } from '../../../../../../../../static/js/node_ajax';
+
+export function getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser) {
+ return new ColumnSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ treeNodeInfo,
+ ()=>getNodeAjaxOptions('get_types', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData, {
+ cacheLevel: 'table',
+ }),
+ ()=>getNodeAjaxOptions('get_collations', pgBrowser.Nodes['collation'], treeNodeInfo, itemNodeData),
+ );
+}
+
+export default class ColumnSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, nodeInfo, cltypeOptions, collspcnameOptions, inErd=false) {
+ super({
+ name: undefined,
+ attowner: undefined,
+ atttypid: undefined,
+ attnum: undefined,
+ cltype: undefined,
+ collspcname: undefined,
+ attacl: undefined,
+ description: undefined,
+ parent_tbl: undefined,
+ min_val_attlen: undefined,
+ min_val_attprecision: undefined,
+ max_val_attlen: undefined,
+ max_val_attprecision: undefined,
+ edit_types: undefined,
+ is_primary_key: false,
+ inheritedfrom: undefined,
+ attstattarget:undefined,
+ attnotnull: false,
+ attlen: null,
+ attprecision: null,
+ attidentity: 'a',
+ attoptions: [],
+ seqincrement: undefined,
+ seqstart: undefined,
+ seqmin: undefined,
+ seqmax: undefined,
+ seqcache: undefined,
+ seqcycle: undefined,
+ colconstype: 'n',
+ genexpr: undefined,
+ });
+
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.nodeInfo = nodeInfo;
+ this.cltypeOptions = cltypeOptions;
+ this.collspcnameOptions = collspcnameOptions;
+ this.inErd = inErd;
+
+ this.datatypes = [];
+ }
+
+ get idAttribute() {
+ return 'attnum';
+ }
+
+ inSchemaWithColumnCheck(state) {
+ // disable all fields if column is listed under view or mview
+ if (this.nodeInfo && (('view' in this.nodeInfo && this.nodeInfo?.server?.version < 130000) || 'mview' in this.nodeInfo)) {
+ return true;
+ }
+
+ if(this.nodeInfo && ('schema' in this.nodeInfo)) {
+ if(this.isNew(state)) {
+ return false;
+ }
+
+ // We will disable control if it's system columns
+ // inheritedfrom check is useful when we use this schema in table node
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)){
+ return true;
+ }
+
+ // ie: it's position is less than 1
+ return !(!_.isUndefined(state.attnum) && state.attnum > 0);
+ }
+ return false;
+ }
+
+ editableCheckForTable(state) {
+ return !this.inSchemaWithColumnCheck(state);
+ }
+
+ // Check whether the column is identity column or not
+ isIdentityColumn(state) {
+ let isIdentity = state.attidentity;
+ return !(!_.isUndefined(isIdentity) && !_.isNull(isIdentity) && !_.isEmpty(isIdentity));
+ }
+
+ // Check whether the column is a identity column
+ isTypeIdentity(state) {
+ let colconstype = state.colconstype;
+ return (!_.isUndefined(colconstype) && !_.isNull(colconstype) && colconstype == 'i');
+ }
+
+ // Check whether the column is a generated column
+ isTypeGenerated(state) {
+ let colconstype = state.colconstype;
+ return (!_.isUndefined(colconstype) && !_.isNull(colconstype) && colconstype == 'g');
+ }
+
+ // We will check if we are under schema node & in 'create' mode
+ inSchemaWithModelCheck(state) {
+ if(this.nodeInfo && 'schema' in this.nodeInfo)
+ {
+ // We will disable control if it's in 'edit' mode
+ return !(this.isNew(state));
+ }
+ return true;
+ }
+
+ attlenRange(state) {
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ if(o.length) return {min: o.min_val || 0, max: o.max_val};
+ }
+ }
+ return null;
+ }
+
+ attprecisionRange(state) {
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ // PostgreSQL allows negative precision
+ if(o.precision) return {min: -o.max_val, max: o.max_val};
+ }
+ }
+ return null;
+ }
+
+ attCell(state) {
+ return { cell: this.attlenRange(state) ? 'int' : '' };
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', readonly: obj.inSchemaWithColumnCheck,
+ editable: this.editableCheckForTable, noEmpty: true,
+ width: 115,
+ },{
+ // Need to show this field only when creating new table
+ // [in SubNode control]
+ id: 'is_primary_key', label: gettext('Primary key?'),
+ cell: 'switch', type: 'switch', width: 100, disableResizing: true, deps:['name', ['primary_key']],
+ visible: ()=>{
+ return obj.top?.nodeInfo && _.isUndefined(
+ obj.top.nodeInfo['table'] || obj.top.nodeInfo['view'] ||
+ obj.top?.nodeInfo['mview']
+ );
+ },
+ readonly: (state)=>{
+ // Disable it, when one of this:
+ // - Primary key already exist
+ // - Table is a partitioned table
+ if (
+ obj.top && ((
+ !_.isUndefined(obj.top.sessData['oid'])
+ && !_.isUndefined(obj.top.sessData['primary_key'])
+ && obj.top.sessData['primary_key'].length > 0
+ && !_.isUndefined(obj.top.sessData['primary_key'][0]['oid'])
+ ) || (
+ 'is_partitioned' in obj.top.sessData
+ && obj.top.sessData['is_partitioned']
+ && obj.getServerVersion() < 11000
+ ))
+ ) {
+ return true;
+ }
+
+ let name = state.name;
+
+ return (!obj.inSchemaWithColumnCheck(state)
+ && (_.isUndefined(name) || _.isNull(name) || name == ''));
+ },
+ editable: function(state) {
+ // If primary key already exist then disable.
+ if (
+ obj.top && (
+ !_.isUndefined(obj.top.sessData['oid'])
+ && !_.isUndefined(obj.top.sessData['primary_key'])
+ && obj.top.sessData['primary_key'].length > 0
+ && !_.isUndefined(obj.top.sessData['primary_key'][0]['oid'])
+ )
+ ) {
+ return false;
+ }
+
+ // If table is partitioned table then disable
+ if(
+ obj.top && (
+ 'is_partitioned' in obj.top.sessData
+ && obj.top.sessData['is_partitioned']
+ && obj.getServerVersion() < 11000)
+ ) {
+ return false;
+ }
+
+ return !obj.inSchemaWithColumnCheck(state);
+ },
+ },{
+ id: 'attnum', label: gettext('Position'), cell: 'text',
+ type: 'text', disabled: this.inCatalog, mode: ['properties'],
+ },{
+ id: 'cltype', label: gettext('Data type'),
+ readonly: obj.inSchemaWithColumnCheck, width: 150,
+ group: gettext('Definition'), noEmpty: true,
+ editable: this.editableCheckForTable,
+ options: this.cltypeOptions, optionsLoaded: (options)=>{obj.datatypes = options;},
+ type: (state)=>{
+ return {
+ type: 'select',
+ options: this.cltypeOptions,
+ controlProps: {
+ allowClear: false,
+ filter: (options)=>{
+ let result = options;
+ let edit_types = state?.edit_types || [];
+ if(!obj.isNew(state) && !this.inErd) {
+ result = _.filter(options, (o)=>edit_types.indexOf(o.value) > -1);
+ }
+ return result;
+ },
+ }
+ };
+ },
+ cell: (row)=>{
+ return {
+ cell: 'select',
+ options: this.cltypeOptions,
+ controlProps: {
+ allowClear: false,
+ filter: (options)=>{
+ let result = options;
+ let edit_types = row?.edit_types || [];
+ if(!obj.isNew(row) && !this.inErd) {
+ result = _.filter(options, (o)=>edit_types.indexOf(o.value) > -1);
+ }
+ return result;
+ },
+ }
+ };
+ }
+ },{
+ /* This field is required to send it to back end */
+ id: 'inheritedid', label: gettext(''), type: 'text', visible: false,
+ },{
+ // Need to show this field only when creating new table [in SubNode control]
+ id: 'inheritedfrom', label: gettext('Inherited from table'),
+ type: 'text', readonly: true, editable: false,
+ visible: function() {
+ if(this.nodeInfo) {
+ return _.isUndefined(this.nodeInfo['table'] || this.nodeInfo['view'] || this.nodeInfo['mview']);
+ }
+ return false;
+ },
+ },{
+ id: 'attlen', label: gettext('Length/Precision'),
+ deps: ['cltype'], type: 'int', group: gettext('Definition'), width: 120, disableResizing: true,
+ cell: (state)=>{
+ return obj.attCell(state);
+ },
+ depChange: (state)=>{
+ let range = this.attlenRange(state);
+ if(range) {
+ return {
+ ...state, min_val_attlen: range.min, max_val_attlen: range.max,
+ };
+ } else {
+ return {
+ ...state, attlen: null,
+ };
+ }
+ },
+ disabled: function(state) {
+ return !obj.attlenRange(state);
+ },
+ editable: function(state) {
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)) {
+ return false;
+ }
+ return Boolean(obj.attlenRange(state));
+ },
+ },{
+ id: 'min_val_attlen', skipChange: true, visible: false, type: '',
+ },{
+ id: 'max_val_attlen', skipChange: true, visible: false, type: '',
+ },{
+ id: 'attprecision', label: gettext('Scale'), width: 60, disableResizing: true,
+ deps: ['cltype'], type: 'int', group: gettext('Definition'),
+ cell: (state)=>{
+ return obj.attCell(state);
+ },
+ depChange: (state)=>{
+ let range = this.attprecisionRange(state);
+ if(range) {
+ return {
+ ...state, min_val_attprecision: range.min, max_val_attprecision: range.max,
+ };
+ } else {
+ return {
+ ...state, attprecision: null,
+ };
+ }
+ },
+ disabled: function(state) {
+ return !this.attprecisionRange(state);
+ },
+ editable: function(state) {
+ // inheritedfrom has value then we should disable it
+ if (!isEmptyString(state.inheritedfrom)) {
+ return false;
+ }
+ return Boolean(this.attprecisionRange(state));
+ },
+ },{
+ id: 'min_val_attprecision', skipChange: true, visible: false, type: '',
+ },{
+ id: 'max_val_attprecision', skipChange: true, visible: false, type: '',
+ },{
+ id: 'attcompression', label: gettext('Compression'),
+ group: gettext('Definition'), type: 'select', deps: ['cltype'],
+ controlProps: { placeholder: gettext('Select compression'), allowClear: false},
+ options: [
+ {label: 'PGLZ', value: 'pglz'},
+ {label: 'LZ4', value: 'lz4'}
+ ],
+ disabled: function(state) {
+ return !obj.attlenRange(state);
+ },
+ depChange: (state)=>{
+ if(!obj.attlenRange(state)) {
+ return { attcompression: '' };
+ }
+ },
+ min_version: 140000,
+ }, {
+ id: 'collspcname', label: gettext('Collation'), cell: 'select',
+ type: 'select', group: gettext('Definition'),
+ deps: ['cltype'], options: this.collspcnameOptions,
+ disabled: (state)=>{
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ if(o.is_collatable) return false;
+ }
+ }
+ return true;
+ }, depChange: (state)=>{
+ for(let o of this.datatypes) {
+ if ( state.cltype == o.value ) {
+ if(o.is_collatable) return {};
+ }
+ }
+ return {collspcname: null};
+ }
+ },{
+ id: 'attstattarget', label: gettext('Statistics'), cell: 'text',
+ type: 'text', readonly: obj.inSchemaWithColumnCheck, mode: ['properties', 'edit'],
+ group: gettext('Definition'),
+ },{
+ id: 'attstorage', label: gettext('Storage'), group: gettext('Definition'),
+ type: 'select', mode: ['properties', 'edit', 'create'],
+ cell: 'select', readonly: obj.inSchemaWithColumnCheck,
+ controlProps: { placeholder: gettext('Select storage'),
+ allowClear: false,
+ },
+ options: function() {
+ let options = [{
+ label: gettext('PLAIN'), value: 'p'
+ },{
+ label: gettext('MAIN'), value: 'm'
+ },{
+ label: gettext('EXTERNAL'), value: 'e'
+ },{
+ label: gettext('EXTENDED'), value: 'x'
+ }];
+
+ if (obj.getServerVersion() >= 160000) {
+ options.push({
+ label: gettext('DEFAULT'), value: 'd',
+ });
+ }
+ return options;
+ },
+ visible: (state) => {
+ if (obj.getServerVersion() >= 160000) {
+ return true;
+ } else if (obj.isNew(state)) {
+ return false;
+ } else {
+ return true;
+ }
+ },
+ },{
+ id: 'defval', label: gettext('Default'), cell: 'text',
+ type: 'text', group: gettext('Constraints'), deps: ['cltype', 'colconstype'],
+ readonly: obj.inSchemaWithColumnCheck,
+ disabled: function(state) {
+ let isDisabled = ['serial', 'bigserial', 'smallserial'].indexOf(state.cltype) > -1;
+ isDisabled = isDisabled || state.colconstype != 'n';
+ return isDisabled;
+ }, depChange: (state)=>{
+ let isDisabled = false;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ isDisabled = ['serial', 'bigserial', 'smallserial'].indexOf(state.cltype) > -1;
+ }
+ isDisabled = isDisabled || state.colconstype != 'n';
+ if (isDisabled && obj.isNew(state)) {
+ return {defval: undefined};
+ }
+ }, editable: function(state) {
+ // inheritedfrom has value then we should disable it
+ return !(!isEmptyString(state.inheritedfrom) || !this.editableCheckForTable(state));
+ },
+ },{
+ id: 'attnotnull', label: gettext('Not NULL?'), cell: 'switch',
+ type: 'switch', width: 80, disableResizing: true,
+ group: gettext('Constraints'), editable: this.editableCheckForTable,
+ deps: ['colconstype'],
+ readonly: (state) => {
+ return obj.inSchemaWithColumnCheck(state);
+ }, depChange:(state)=>{
+ if (state.colconstype == 'i') {
+ return {attnotnull: true};
+ }
+ }
+ }, {
+ id: 'colconstype',
+ label: gettext('Type'),
+ cell: 'text',
+ group: gettext('Constraints'),
+ type: (state)=>{
+ let options = [
+ {'label': gettext('NONE'), 'value': 'n'},
+ {'label': gettext('IDENTITY'), 'value': 'i'},
+ ];
+
+ if (this.getServerVersion() >= 120000) {
+ // You can't change the existing column to Generated column.
+ if (this.isNew(state)) {
+ options.push({
+ 'label': gettext('GENERATED'),
+ 'value': 'g',
+ });
+ } else {
+ options.push({
+ 'label': gettext('GENERATED'),
+ 'value': 'g',
+ 'disabled': true,
+ });
+ }
+ }
+
+ return {
+ type: 'toggle',
+ options: options,
+ };
+ },
+ disabled: function(state) {
+ return (!this.isNew(state) && state.colconstype == 'g');
+ }, min_version: 100000,
+ }, {
+ id: 'attidentity', label: gettext('Identity'),
+ cell: 'select', type: 'select',
+ controlProps: {placeholder: gettext('Select identity'), allowClear: false},
+ min_version: 100000, group: gettext('Constraints'),
+ options: [
+ {label: gettext('ALWAYS'), value: 'a'},
+ {label: gettext('BY DEFAULT'), value: 'd'},
+ ],
+ deps: ['colconstype'],
+ visible: this.isTypeIdentity,
+ disabled: false,
+ },{
+ id: 'seqincrement', label: gettext('Increment'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ min: 1, deps: ['attidentity', 'colconstype'], disabled: this.isIdentityColumn,
+ visible: this.isTypeIdentity,
+ },{
+ id: 'seqstart', label: gettext('Start'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ disabled: this.isIdentityColumn, deps: ['attidentity', 'colconstype'],
+ visible: this.isTypeIdentity,
+ },{
+ id: 'seqmin', label: gettext('Minimum'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ deps: ['attidentity', 'colconstype'], disabled: this.isIdentityColumn,
+ visible: this.isTypeIdentity,
+ },{
+ id: 'seqmax', label: gettext('Maximum'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ deps: ['attidentity', 'colconstype'], disabled: this.isIdentityColumn,
+ visible: this.isTypeIdentity,
+ },{
+ id: 'seqcache', label: gettext('Cache'), type: 'int',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ min: 1, deps: ['attidentity', 'colconstype'], disabled: this.isIdentityColumn,
+ visible: this.isTypeIdentity,
+ },{
+ id: 'seqcycle', label: gettext('Cycled'), type: 'switch',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ deps: ['attidentity', 'colconstype'], disabled: this.isIdentityColumn,
+ visible: this.isTypeIdentity,
+ },{
+ id: 'genexpr', label: gettext('Expression'), type: 'text',
+ mode: ['properties', 'create', 'edit'], group: gettext('Constraints'),
+ min_version: 120000, deps: ['colconstype'], visible: this.isTypeGenerated,
+ readonly: function(state) {
+ return !this.isNew(state);
+ },
+ },{
+ id: 'is_pk', label: gettext('Primary key?'),
+ type: 'switch', mode: ['properties'],
+ group: gettext('Definition'),
+ },{
+ id: 'is_fk', label: gettext('Foreign key?'),
+ type: 'switch', mode: ['properties'],
+ group: gettext('Definition'),
+ },{
+ id: 'is_inherited', label: gettext('Inherited?'),
+ type: 'switch', mode: ['properties'],
+ group: gettext('Definition'),
+ },{
+ id: 'tbls_inherited', label: gettext('Inherited from table(s)'),
+ type: 'text', mode: ['properties'], deps: ['is_inherited'],
+ group: gettext('Definition'),
+ visible: function(state) {
+ return !_.isUndefined(state.is_inherited) && state.is_inherited;
+ },
+ },{
+ id: 'is_sys_column', label: gettext('System column?'), cell: 'text',
+ type: 'switch', mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'text',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ disabled: this.inCatalog,
+ },{
+ id: 'attoptions', label: gettext('Variables'), type: 'collection',
+ group: gettext('Variables'),
+ schema: new VariableSchema([
+ {label: 'n_distinct', value: 'n_distinct', vartype: 'string'},
+ {label: 'n_distinct_inherited', value: 'n_distinct_inherited', vartype: 'string'}
+ ], null, null, ['name', 'value']),
+ uniqueCol : ['name'], mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ },{
+ id: 'security', label: gettext('Security'), type: 'group',
+ visible: !this.inErd,
+ },{
+ id: 'attacl', label: gettext('Privileges'), type: 'collection',
+ group: 'security',
+ schema: this.getPrivilegeRoleSchema(['a','r','w','x']),
+ mode: ['edit'], canAdd: true, canDelete: true,
+ uniqueCol : ['grantee'],
+ },{
+ id: 'seclabels', label: gettext('Security labels'), canAdd: true,
+ schema: new SecLabelSchema(), group: 'security',
+ mode: ['edit', 'create'], editable: false, type: 'collection',
+ min_version: 90100, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'],
+ }];
+ }
+
+ validate(state, setError) {
+ let msg = undefined;
+
+ if (!_.isUndefined(state.cltype) && !isEmptyString(state.attlen)) {
+ // Validation for Length field
+ if (state.attlen < state.min_val_attlen)
+ msg = gettext('Length/Precision should not be less than: ') + state.min_val_attlen;
+ if (state.attlen > state.max_val_attlen)
+ msg = gettext('Length/Precision should not be greater than: ') + state.max_val_attlen;
+ // If we have any error set then throw it to user
+ if(msg) {
+ setError('attlen', msg);
+ return true;
+ }
+ }
+
+ if (!_.isUndefined(state.cltype) && !isEmptyString(state.attprecision)) {
+ // Validation for precision field
+ if (state.attprecision < state.min_val_attprecision)
+ msg = gettext('Scale should not be less than: ') + state.min_val_attprecision;
+ if (state.attprecision > state.max_val_attprecision)
+ msg = gettext('Scale should not be greater than: ') + state.max_val_attprecision;
+ // If we have any error set then throw it to user
+ if(msg) {
+ setError('attprecision', msg);
+ return true;
+ }
+ }
+
+ if (state.colconstype == 'g' && isEmptyString(state.genexpr)) {
+ msg = gettext('Expression value cannot be empty.');
+ setError('genexpr', msg);
+ return true;
+ }
+
+ if (!this.isNew(state) && state.colconstype == 'i'
+ && (this.origData.attidentity == 'a' || this.origData.attidentity == 'd')
+ && (state.attidentity == 'a' || state.attidentity == 'd')) {
+ if(isEmptyString(state.seqincrement)) {
+ msg = gettext('Increment value cannot be empty.');
+ setError('seqincrement', msg);
+ return true;
+ }
+
+ if(isEmptyString(state.seqmin)) {
+ msg = gettext('Minimum value cannot be empty.');
+ setError('seqmin', msg);
+ return true;
+ }
+
+ if(isEmptyString(state.seqmax)) {
+ msg = gettext('Maximum value cannot be empty.');
+ setError('seqmax', msg);
+ return true;
+ }
+
+ if(isEmptyString(state.seqcache)) {
+ msg = gettext('Cache value cannot be empty.');
+ setError('seqcache', msg);
+ return true;
+ }
+ }
+
+ if (isEmptyString(state.seqmin) || isEmptyString(state.seqmax))
+ return false;
+
+ if ((state.seqmin == 0 && state.seqmax == 0) ||
+ (parseInt(state.seqmin, 10) >= parseInt(state.seqmax, 10))) {
+ setError('seqmin', gettext('Minimum value must be less than maximum value.'));
+ return true;
+ }
+
+ if (state.seqstart && state.seqmin && parseInt(state.seqstart) < parseInt(state.seqmin)) {
+ setError('seqstart', gettext('Start value cannot be less than minimum value.'));
+ return true;
+ }
+
+ if (state.seqstart && state.seqmax && parseInt(state.seqstart) > parseInt(state.seqmax)) {
+ setError('seqstart', gettext('Start value cannot be greater than maximum value.'));
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/privilege.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/privilege.macros
new file mode 100644
index 0000000000000000000000000000000000000000..7fe81e54be5b9fac71164dca1258e0f00b00d057
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/privilege.macros
@@ -0,0 +1,13 @@
+{% macro APPLY(conn, schema_name, table_object, column_object, role, privs, with_grant_privs) -%}
+{% if privs %}
+GRANT {% for p in privs %}{% if loop.index != 1 %}, {% endif %}{{p}}({{conn|qtIdent(column_object)}}){% endfor %}
+ ON {{ conn|qtIdent(schema_name, table_object) }} TO {{ role }};
+{% endif %}
+{% if with_grant_privs %}
+GRANT {% for p in with_grant_privs %}{% if loop.index != 1 %}, {% endif %}{{p}}({{conn|qtIdent(column_object)}}){% endfor %}
+ ON {{ conn|qtIdent(schema_name, table_object) }} TO {{ role }} WITH GRANT OPTION;
+{% endif %}
+{%- endmacro %}
+{% macro RESETALL(conn, schema_name, table_object, column_object, role) -%}
+REVOKE ALL({{ conn|qtIdent(column_object) }}) ON {{ conn|qtIdent(schema_name, table_object) }} FROM {{ role }};
+{%- endmacro %}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/security.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/security.macros
new file mode 100644
index 0000000000000000000000000000000000000000..20406ab9989795965bcd8c9008d94d8845e3817f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/templates/columns/macros/security.macros
@@ -0,0 +1,6 @@
+{% macro APPLY(conn, type, schema_name, parent_object, child_object, provider, label) -%}
+SECURITY LABEL FOR {{ conn|qtIdent(provider) }} ON {{ type }} {{ conn|qtIdent(schema_name, parent_object, child_object) }} IS {{ label|qtLiteral(conn) }};
+{%- endmacro %}
+{% macro DROP(conn, type, schema_name, parent_object, child_object, provider) -%}
+SECURITY LABEL FOR {{ conn|qtIdent(provider) }} ON {{ type }} {{ conn|qtIdent(schema_name, parent_object, child_object) }} IS NULL;
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1038282cb1bdf958df8f1ede22dfd4418b55ff9a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/columns/utils.py
@@ -0,0 +1,475 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Compound Triggers. """
+
+from flask import render_template
+from flask_babel import gettext as _
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ExecuteError
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import DataTypeReader
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.server_groups.servers.databases.utils \
+ import make_object_name
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'columns/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+def _check_primary_column(data):
+ """
+ To check if column is primary key
+ :param data: Data.
+ """
+ if 'attnum' in data and 'indkey' in data:
+ # Current column
+ attnum = str(data['attnum'])
+
+ # Single/List of primary key column(s)
+ indkey = str(data['indkey'])
+
+ # We will check if column is in primary column(s)
+ if attnum in indkey.split(" "):
+ data['is_pk'] = True
+ data['is_primary_key'] = True
+ else:
+ data['is_pk'] = False
+ data['is_primary_key'] = False
+
+
+def _fetch_inherited_tables(tid, data, fetch_inherited_tables, template_path,
+ conn):
+ """
+ This function will check for fetch inherited tables, and return inherited
+ tables.
+ :param tid: Table Id.
+ :param data: Data.
+ :param fetch_inherited_tables: flag to fetch inherited tables.
+ :param template_path: Template path.
+ :param conn: Connection.
+ """
+ if fetch_inherited_tables:
+ SQL = render_template("/".join(
+ [template_path, 'get_inherited_tables.sql']), tid=tid)
+ status, inh_res = conn.execute_dict(SQL)
+ if not status:
+ return True, internal_server_error(errormsg=inh_res)
+ for row in inh_res['rows']:
+ if row['attrname'] == data['name']:
+ data['is_inherited'] = True
+ data['tbls_inherited'] = row['inhrelname']
+ return False, ''
+
+
+@get_template_path
+def column_formatter(conn, tid, clid, data, edit_types_list=None,
+ fetch_inherited_tables=True, template_path=None):
+ """
+ This function will return formatted output of query result
+ as per client model format for column node
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param clid: Column ID
+ :param data: Data
+ :param edit_types_list:
+ :param fetch_inherited_tables:
+ :param template_path: Optional template path
+ :return:
+ """
+
+ # To check if column is primary key
+ _check_primary_column(data)
+
+ # Fetch length and precision
+ data = fetch_length_precision(data)
+
+ # We need to fetch inherited tables for each table
+ is_error, errmsg = _fetch_inherited_tables(
+ tid, data, fetch_inherited_tables, template_path, conn)
+
+ if is_error:
+ return errmsg
+
+ # We need to format variables according to client js collection
+ if 'attoptions' in data and data['attoptions'] is not None:
+ data['attoptions'] = parse_column_variables(data['attoptions'])
+
+ # Need to format security labels according to client js collection
+ if 'seclabels' in data and data['seclabels'] is not None:
+ seclabels = []
+ for seclbls in data['seclabels']:
+ k, v = seclbls.split('=')
+ seclabels.append({'provider': k, 'label': v})
+
+ data['seclabels'] = seclabels
+
+ # Get formatted Column Options
+ if 'attfdwoptions' in data and data['attfdwoptions'] != '':
+ data['coloptions'] = parse_options_for_column(data['attfdwoptions'])
+
+ # We need to parse & convert ACL coming from database to json format
+ SQL = render_template("/".join([template_path, 'acl.sql']),
+ tid=tid, clid=clid)
+ status, acl = conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ data['attacl'] = []
+
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ data.setdefault(row['deftype'], []).append(priv)
+
+ # we are receiving request when in edit mode
+ # we will send filtered types related to current type
+ type_id = data['atttypid']
+
+ if edit_types_list is None:
+ edit_types_list = []
+ SQL = render_template("/".join([template_path,
+ 'edit_mode_types.sql']),
+ type_id=type_id)
+ status, rset = conn.execute_2darray(SQL)
+ edit_types_list = [row['typname'] for row in rset['rows']]
+
+ # We will need present type in edit mode
+ edit_types_list.append(data['typname'])
+ data['edit_types'] = sorted(edit_types_list)
+ data['cltype'] = DataTypeReader.parse_type_name(data['cltype'])
+ return data
+
+
+def parse_options_for_column(db_variables):
+ """
+ Function to format the output for variables.
+
+ Args:
+ db_variables: Variable object
+
+ Expected Object Format:
+ ['option1=value1', ..]
+ where:
+ user_name and database are optional
+ Returns:
+ Variable Object in below format:
+ {
+ 'variables': [
+ {'name': 'var_name', 'value': 'var_value',
+ 'user_name': 'user_name', 'database': 'database_name'},
+ ...]
+ }
+ where:
+ user_name and database are optional
+ """
+ variables_lst = []
+
+ if db_variables is not None:
+ for row in db_variables:
+ # The value may contain equals in string, split on
+ # first equals only
+ var_name, var_value = row.split("=", 1)
+ var_dict = {'option': var_name, 'value': var_value}
+ variables_lst.append(var_dict)
+ return variables_lst
+
+
+@get_template_path
+def get_formatted_columns(conn, tid, data, other_columns,
+ table_or_type, template_path=None,
+ with_serial=False):
+ """
+ This function will iterate and return formatted data for all
+ the columns.
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param data: Data
+ :param other_columns:
+ :param table_or_type:
+ :param template_path: Optional template path
+ :return:
+ """
+ SQL = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, show_sys_objects=False)
+
+ status, res = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(res)
+
+ all_columns = res['rows']
+ edit_types = {}
+ # Add inherited from details from other columns - type, table
+ for col in all_columns:
+ edit_types[col['atttypid']] = []
+ for other_col in other_columns:
+ if col['name'] == other_col['name']:
+ col['inheritedfrom' + table_or_type] = \
+ other_col['inheritedfrom']
+
+ if with_serial:
+ # Here we assume if a column is serial
+ serial_seq_name = make_object_name(
+ data['name'], col['name'], 'seq')
+ # replace the escaped quotes for comparison
+ defval = (col.get('defval', '') or '').replace("''", "'").\
+ replace('""', '"')
+
+ if serial_seq_name in defval and defval.startswith("nextval('")\
+ and col['typname'] in ('integer', 'smallint', 'bigint'):
+
+ serial_type = {
+ 'integer': 'serial',
+ 'smallint': 'smallserial',
+ 'bigint': 'bigserial'
+ }[col['typname']]
+
+ col['displaytypname'] = serial_type
+ col['cltype'] = serial_type
+ col['typname'] = serial_type
+ col['defval'] = ''
+
+ data['columns'] = all_columns
+
+ if 'columns' in data and len(data['columns']) > 0:
+ SQL = render_template("/".join([template_path,
+ 'edit_mode_types_multi.sql']),
+ type_ids=",".join(map(lambda x: str(x),
+ edit_types.keys())))
+ status, res = conn.execute_2darray(SQL)
+ for row in res['rows']:
+ edit_types[row['main_oid']] = sorted(row['edit_types'])
+
+ for column in data['columns']:
+ column_formatter(conn, tid, column['attnum'], column,
+ edit_types[column['atttypid']], False)
+
+ return data
+
+
+def _parse_column_actions(final_columns, column_acl):
+ """
+ Check action and access for it.
+ :param final_columns: final column list
+ :param column_acl: Column access.
+ """
+ for c in final_columns:
+ if 'attacl' in c:
+ if 'added' in c['attacl']:
+ c['attacl']['added'] = parse_priv_to_db(
+ c['attacl']['added'], column_acl
+ )
+ elif 'changed' in c['attacl']:
+ c['attacl']['changed'] = parse_priv_to_db(
+ c['attacl']['changed'], column_acl
+ )
+ elif 'deleted' in c['attacl']:
+ c['attacl']['deleted'] = parse_priv_to_db(
+ c['attacl']['deleted'], column_acl
+ )
+ if 'cltype' in c:
+ # check type for '[]' in it
+ c['cltype'], c['hasSqrBracket'] = \
+ type_formatter(c['cltype'])
+
+ c = convert_length_precision_to_string(c)
+
+
+def _parse_format_col_for_edit(data, columns, column_acl):
+ """
+ This function parser columns for edit mode.
+ :param data: Data from req.
+ :param columns: Columns list from data
+ :param column_acl: Column access.
+ """
+ for action in ['added', 'changed']:
+ if action in columns:
+ final_columns = []
+ for c in columns[action]:
+ if c.get('inheritedfrom', None) is None:
+ final_columns.append(c)
+
+ _parse_column_actions(final_columns, column_acl)
+
+ data['columns'][action] = final_columns
+
+
+def parse_format_columns(data, mode=None):
+ """
+ This function will parse and return formatted list of columns
+ added by user.
+
+ :param data:
+ :param mode:
+ :return:
+ """
+ column_acl = ['a', 'r', 'w', 'x']
+ columns = data['columns']
+ # 'EDIT' mode
+ if mode is not None:
+ _parse_format_col_for_edit(data, columns, column_acl)
+ else:
+ # We need to exclude all the columns which are inherited from other
+ # tables 'CREATE' mode
+ final_columns = []
+
+ for c in columns:
+ if c.get('inheritedfrom', None) is None:
+ final_columns.append(c)
+
+ # Now we have all lis of columns which we need
+ # to include in our create definition, Let's format them
+ for c in final_columns:
+ if 'attacl' in c:
+ c['attacl'] = parse_priv_to_db(
+ c['attacl'], column_acl
+ )
+
+ if 'cltype' in c:
+ # check type for '[]' in it
+ c['cltype'], c['hasSqrBracket'] = type_formatter(c['cltype'])
+
+ c = convert_length_precision_to_string(c)
+
+ data['columns'] = final_columns
+
+ return data
+
+
+def convert_length_precision_to_string(data):
+ """
+ This function is used to convert length & precision to string
+ to handle case like when user gives 0 as length.
+
+ :param data:
+ :return:
+ """
+
+ if 'attlen' in data and data['attlen'] == '':
+ data['attlen'] = None
+ elif 'attlen' in data and data['attlen'] is not None:
+ data['attlen'] = str(data['attlen'])
+
+ if 'attprecision' in data and data['attprecision'] == '':
+ data['attprecision'] = None
+ elif 'attprecision' in data and data['attprecision'] is not None:
+ data['attprecision'] = str(data['attprecision'])
+
+ return data
+
+
+def type_formatter(data_type):
+ """
+ We need to remove [] from type and append it
+ after length/precision so we will set flag for
+ sql template.
+
+ :param data_type:
+ :param template_path: Optional template path
+ :return:
+ """
+
+ if '[]' in data_type:
+ return data_type[:-2], True
+ else:
+ return data_type, False
+
+
+def fetch_length_precision(data):
+ """
+ This function is used to fetch the length and precision.
+
+ :param data:
+ :return:
+ """
+ # Find length & precision of column data type
+ fulltype = DataTypeReader.get_full_type(
+ data['typnspname'], data['typname'],
+ data['isdup'], data['attndims'], data['atttypmod'])
+
+ length = False
+ precision = False
+ if 'elemoid' in data:
+ length, precision, _ = \
+ DataTypeReader.get_length_precision(data['elemoid'])
+
+ # Set length and precision to None
+ data['attlen'] = None
+ data['attprecision'] = None
+
+ import re
+
+ # If we have length & precision both
+ if length and precision:
+ match_obj = re.search(r'(\d+),(\d+)', fulltype)
+ if match_obj:
+ data['attlen'] = match_obj.group(1)
+ data['attprecision'] = match_obj.group(2)
+ elif length:
+ # If we have length only
+ match_obj = re.search(r'(\d+)', fulltype)
+ if match_obj:
+ data['attlen'] = match_obj.group(1)
+ data['attprecision'] = None
+
+ return data
+
+
+def parse_column_variables(col_variables):
+ # We need to format variables according to client js collection
+ spcoptions = []
+ if col_variables is not None:
+ for spcoption in col_variables:
+ k, v = spcoption.split('=')
+ spcoptions.append({'name': k, 'value': v})
+ return spcoptions
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab642ce5d0fdebfade85eee926100dd16a79be12
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/__init__.py
@@ -0,0 +1,1036 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Compound Trigger Node """
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ compound_triggers import utils as compound_trigger_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.directory_compare import directory_diff,\
+ parse_acl
+
+
+class CompoundTriggerModule(CollectionNodeModule):
+ """
+ class CompoundTriggerModule(CollectionNodeModule)
+
+ A module class for Compound Trigger node derived from
+ CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Trigger and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for compound trigger, when any of the server
+ node is initialized.
+ """
+
+ _NODE_TYPE = 'compound_trigger'
+ _COLLECTION_LABEL = gettext("Compound Triggers")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the CompoundTriggerModule and
+ it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = self.min_ppasver = 120000
+ self.max_ver = None
+ self.server_type = ['ppas']
+
+ def backend_supported(self, manager, **kwargs):
+ """
+ Load this module if vid is view, we will not load it under
+ material view
+ """
+ if super().backend_supported(
+ manager, **kwargs):
+ conn = manager.connection(did=kwargs['did'])
+
+ if 'vid' not in kwargs:
+ return True
+
+ template_path = 'compound_triggers/sql/{0}/#{1}#'.format(
+ manager.server_type, manager.version)
+ SQL = render_template("/".join(
+ [template_path, 'backend_support.sql']), vid=kwargs['vid']
+ )
+
+ status, res = conn.execute_scalar(SQL)
+
+ # check if any errors
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Check vid is view not material view
+ # then true, othewise false
+ return res
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs)
+ if self.has_nodes(
+ sid, did, scid=scid,
+ tid=kwargs.get('tid', kwargs.get('vid', None)),
+ base_template_path=CompoundTriggerView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ kwargs['tid'] if 'tid' in kwargs else kwargs['vid']
+ )
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return False
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ "compound_triggers/css/compound_trigger.css",
+ node_type=self.node_type
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+
+blueprint = CompoundTriggerModule(__name__)
+
+
+class CompoundTriggerView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Compound Trigger node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the CompoundTriggerView and it's
+ base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Compound Trigger nodes
+ within that collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Compound Trigger node.
+
+ * node()
+ - This function will used to create child node within that
+ collection, Here it will create specific the Compound Trigger node.
+
+ * properties(gid, sid, did, scid, tid, trid)
+ - This function will show the properties of the selected
+ Compound Trigger node
+
+ * create(gid, sid, did, scid, tid)
+ - This function will create the new Compound Trigger object
+
+ * update(gid, sid, did, scid, tid, trid)
+ - This function will update the data for the selected
+ Compound Trigger node
+
+ * delete(self, gid, sid, scid, tid, trid):
+ - This function will drop the Compound Trigger object
+
+ * enable(self, gid, sid, scid, tid, trid):
+ - This function will enable/disable Compound Trigger object
+
+ * msql(gid, sid, did, scid, tid, trid)
+ - This function is used to return modified SQL for the selected
+ Compound Trigger node
+
+ * sql(gid, sid, did, scid, tid, trid):
+ - This function will generate sql to show it in sql pane for the
+ selected Compound Trigger node.
+
+ * dependency(gid, sid, did, scid, tid, trid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Compound Trigger node.
+
+ * dependent(gid, sid, did, scid, tid, trid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Compound Trigger node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Compound Trigger"
+ BASE_TEMPLATE_PATH = 'compound_triggers/sql/{0}/#{1}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'trid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'enable': [{'put': 'enable_disable_trigger'}]
+ })
+
+ # Schema Diff: Keys to ignore while comparing
+ keys_to_ignore = ['oid', 'xmin', 'nspname', 'tfunction',
+ 'tgrelid', 'tgfoid', 'oid-2']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.table_template_path = compile_template_path(
+ 'tables/sql',
+ self.manager.version
+ )
+
+ # we will set template path for sql scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.server_type, self.manager.version)
+ # Store server type
+ self.server_type = self.manager.server_type
+ # We need parent's name eg table name and schema name
+ # when we create new compound trigger in update we can fetch
+ # it using property sql
+ schema, table = compound_trigger_utils.get_parent(
+ self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the compound trigger nodes
+ within that collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available compound trigger nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), tid=tid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will used to create the child node within that
+ collection.
+ Here it will create specific the compound trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ Returns:
+ JSON of available compound trigger child nodes
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid,
+ trid=trid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-compound_trigger-bad" if
+ rset['rows'][0]['is_enable_trigger'] == 'D' else
+ "icon-compound_trigger"
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the compound trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available trigger child nodes
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-compound_trigger-bad"
+ if row['is_enable_trigger'] == 'D'
+ else "icon-compound_trigger",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will show the properties of the selected
+ compound trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ Returns:
+ JSON of selected compound trigger node
+ """
+
+ status, data = self._fetch_properties(tid, trid)
+
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ if 'rows' in data and len(data['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ def _fetch_properties(self, tid, trid):
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return status, res
+
+ if len(res['rows']) == 0:
+ return True, res
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+ if len(data['tgattr']) >= 1:
+ columns = ', '.join(data['tgattr'].split(' '))
+ data['columns'] = compound_trigger_utils.get_column_details(
+ self.conn, tid, columns)
+
+ data = trigger_definition(data)
+
+ return True, data
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will creates new the compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ required_args = {
+ 'name': 'Name'
+ }
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(required_args[arg])
+ )
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need oid to add object in tree at browser
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ tid=tid, data=data, conn=self.conn)
+ status, trid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ trid,
+ tid,
+ data['name'],
+ icon="icon-compound_trigger"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will updates the existing compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ trid = kwargs.get('trid', None)
+ only_sql = kwargs.get('only_sql', False)
+
+ if trid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [trid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ try:
+ for trid in data['ids']:
+ # We will first fetch the compound trigger name for
+ # current request so that we create template for
+ # dropping compound trigger
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ data = dict(res['rows'][0])
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ conn=self.conn,
+ cascade=cascade
+ )
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Compound Trigger is dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will updates the existing compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ SQL, name = compound_trigger_utils.get_sql(
+ self.conn, data, tid, trid, self._DATABASE_LAST_SYSTEM_OID)
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need oid to add object in browser tree and if user
+ # update the compound trigger then new OID is getting generated
+ # so we need to return new OID of compound trigger.
+ SQL = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid, data=data, conn=self.conn
+ )
+ status, new_trid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=new_trid)
+ # Fetch updated properties
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=new_trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ new_trid,
+ tid,
+ name,
+ icon="icon-%s-bad" % self.node_type if
+ data['is_enable_trigger'] == 'D' else
+ "icon-%s" % self.node_type,
+ description=data['description']
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, trid=None):
+ """
+ This function will generates modified sql for compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID (When working with existing compound trigger)
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ try:
+ sql, _ = compound_trigger_utils.get_sql(
+ self.conn, data, tid, trid, self._DATABASE_LAST_SYSTEM_OID)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will generates reverse engineered sql for
+ compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ try:
+ SQL = compound_trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=self.schema, table=self.table, tid=tid,
+ trid=trid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def enable_disable_trigger(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will enable OR disable the current
+ compound trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ # Convert str 'true' to boolean type
+ is_enable_trigger = data['is_enable_trigger']
+
+ try:
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ o_data = dict(res['rows'][0])
+
+ # If enable is set to true means we need SQL to enable
+ # current compound trigger which is disabled already so we need to
+ # alter the 'is_enable_trigger' flag so that we can render
+ # correct SQL for operation
+ o_data['is_enable_trigger'] = is_enable_trigger
+
+ # Adding parent into data dict, will be using it while creating sql
+ o_data['schema'] = self.schema
+ o_data['table'] = self.table
+
+ SQL = render_template("/".join([self.template_path,
+ 'enable_disable_trigger.sql']),
+ data=o_data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info="Compound Trigger updated",
+ data={
+ 'id': trid,
+ 'tid': tid,
+ 'scid': scid
+ }
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, trid):
+ """
+ This function get the dependents and return ajax response
+ for the compound trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, trid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, trid):
+ """
+ This function get the dependencies and return ajax response
+ for the compound trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, trid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ sql, _ = compound_trigger_utils.get_sql(
+ self.conn, data, tid, oid, self._DATABASE_LAST_SYSTEM_OID)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, tid=tid,
+ trid=oid, only_sql=True)
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, trid=oid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = dict(res['rows'][0])
+ # Adding parent into data dict,
+ # will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ if len(data['tgattr']) >= 1:
+ columns = ', '.join(data['tgattr'].split(' '))
+ data['columns'] = self._column_details(tid, columns)
+
+ data = trigger_definition(data)
+ sql = self._check_and_add_compound_trigger(tid, data,
+ target_schema)
+
+ return sql
+
+ def _check_and_add_compound_trigger(self, tid, data, target_schema):
+ """
+ This get compound trigger and check for disable.
+ :param tid: Table Id.
+ :param data: Data.
+ :param target_schema: schema diff check.
+ """
+ if target_schema:
+ data['schema'] = target_schema
+
+ sql, _ = compound_trigger_utils.get_sql(
+ self.conn, data, tid, None, self._DATABASE_LAST_SYSTEM_OID)
+
+ # If compound trigger is disbaled then add sql
+ # code for the same
+ if not data['is_enable_trigger']:
+ sql += '\n\n'
+ sql += render_template("/".join([
+ self.template_path,
+ 'enable_disable_trigger.sql']),
+ data=data, conn=self.conn)
+ return sql
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, oid=None):
+ """
+ This function will fetch the list of all the triggers for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :return:
+ """
+ res = dict()
+
+ if oid:
+ status, data = self._fetch_properties(tid, oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+ res = data
+ else:
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid,
+ schema_diff=True)
+ status, triggers = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(triggers)
+ return False
+
+ for row in triggers['rows']:
+ status, data = self._fetch_properties(tid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ src_params = kwargs.get('source_params')
+ tgt_params = kwargs.get('target_params')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ comp_status = kwargs.get('comp_status')
+ target_schema = kwargs.get('target_schema', None)
+
+ diff = ''
+ if comp_status == 'source_only':
+ diff = self.get_sql_from_diff(gid=src_params['gid'],
+ sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ oid=source['oid'],
+ target_schema=target_schema)
+ elif comp_status == 'target_only':
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ drop_sql=True)
+ elif comp_status == 'different':
+ diff_dict = directory_diff(
+ source, target,
+ ignore_keys=self.keys_to_ignore, difference={}
+ )
+ parse_acl(source, target, diff_dict)
+
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ data=diff_dict)
+
+ return diff
+
+
+SchemaDiffRegistry(blueprint.node_type, CompoundTriggerView, 'table')
+CompoundTriggerView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/coll-compound_trigger.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/coll-compound_trigger.svg
new file mode 100644
index 0000000000000000000000000000000000000000..24a290208e04f1085e66655917e5d01ac8a1f10b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/coll-compound_trigger.svg
@@ -0,0 +1 @@
+coll_compound_trigger
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger-bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger-bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..ec0f8f455fc5105994bd63126f7363da26cf8182
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger-bad.svg
@@ -0,0 +1 @@
+compud_trigger_disable
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger.svg
new file mode 100644
index 0000000000000000000000000000000000000000..837cfe010d57e929294867839a9eca75230b1e29
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/img/compound_trigger.svg
@@ -0,0 +1 @@
+compund_trigger
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.js
new file mode 100644
index 0000000000000000000000000000000000000000..968b553c31303b091e5c61b54f2e6e678291fcab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.js
@@ -0,0 +1,210 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeListByName } from '../../../../../../../../static/js/node_ajax';
+import CompoundTriggerSchema from './compound_trigger.ui';
+import getApiInstance from '../../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.compound_trigger', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-compound_trigger']) {
+ pgAdmin.Browser.Nodes['coll-compound_trigger'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'compound_trigger',
+ label: gettext('Compound Triggers'),
+ type: 'coll-compound_trigger',
+ columns: ['name', 'description'],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['compound_trigger']) {
+ pgAdmin.Browser.Nodes['compound_trigger'] = pgBrowser.Node.extend({
+ parent_type: ['table', 'view', 'partition'],
+ collection_type: ['coll-table', 'coll-view'],
+ type: 'compound_trigger',
+ label: gettext('Compound Trigger'),
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.sm + 'px',
+ epasHelp: true,
+ dialogHelp: url_for('help.static', {'filename': 'compound_trigger_dialog.html'}),
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_compound_trigger_on_coll', node: 'coll-compound_trigger', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Compound Trigger...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_compound_trigger', node: 'compound_trigger', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Compound Trigger...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_compound_trigger_onTable', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Compound Trigger...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'create_compound_trigger_onPartition', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Compound Trigger...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },{
+ name: 'enable_compound_trigger', node: 'compound_trigger', module: this,
+ applies: ['object', 'context'], callback: 'enable_compound_trigger',
+ category: 'connect', priority: 3, label: gettext('Enable compound trigger'),
+ enable : 'canCreate_with_compound_trigger_enable',
+ },{
+ name: 'disable_compound_trigger', node: 'compound_trigger', module: this,
+ applies: ['object', 'context'], callback: 'disable_compound_trigger',
+ category: 'drop', priority: 3, label: gettext('Disable compound trigger'),
+ enable : 'canCreate_with_compound_trigger_disable',
+ },{
+ name: 'create_compound_trigger_onView', node: 'view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Compound Trigger...'),
+ data: {action: 'create', check: true,
+ data_disabled: gettext('This option is only available on EPAS servers.')},
+ enable: 'canCreate',
+ },
+ ]);
+ },
+ callbacks: {
+ /* Enable compound trigger */
+ enable_compound_trigger: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(
+ obj.generate_url(i, 'enable' , d, true),
+ {'is_enable_trigger' : 'O'}
+ ).then(({data: res})=> {
+ if(res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = 'icon-compound_trigger';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ }).catch(function(error) {
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ /* Disable compound trigger */
+ disable_compound_trigger: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(
+ obj.generate_url(i, 'enable' , d, true),
+ {'is_enable_trigger' : 'D'}
+ ).then(({data: res})=> {
+ if(res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = 'icon-compound_trigger-bad';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ }).catch(function(error) {
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ },
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new CompoundTriggerSchema(
+ {
+ columns: ()=>getNodeListByName('column', treeNodeInfo, itemNodeData, { cacheLevel: 'column'}),
+ },
+ treeNodeInfo,
+ );
+ },
+
+ canCreate: function(itemData, item, data) {
+ //If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ if (server && (server.server_type === 'pg' || server.version < 120000))
+ return false;
+
+ // If it is catalog then don't allow user to create package
+ return treeData['catalog'] == undefined;
+ },
+ // Check to whether trigger is disable ?
+ canCreate_with_compound_trigger_enable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-compound_trigger-bad' &&
+ this.canCreate(itemData, item, data);
+ },
+ // Check to whether trigger is enable ?
+ canCreate_with_compound_trigger_disable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-compound_trigger' &&
+ this.canCreate(itemData, item, data);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['compound_trigger'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..9de6db72827c10db672e0dfae3280596bf0b12ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/static/js/compound_trigger.ui.js
@@ -0,0 +1,208 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { isEmptyString } from 'sources/validators';
+
+
+export class ForEventsSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, initValues={}) {
+ super({
+ ...initValues,
+ });
+
+ this.fieldOptions = {
+ ...fieldOptions,
+ };
+ this.nodeInfo = nodeInfo;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'evnt_insert', label: gettext('INSERT'),
+ type: 'switch',
+ readonly: function(state) {
+ let evn_insert = state.evnt_insert;
+ if (!_.isUndefined(evn_insert) && obj.nodeInfo.server.server_type == 'ppas')
+ return false;
+ return obj.inCatalog();
+ },
+ },{
+ id: 'evnt_update', label: gettext('UPDATE'),
+ type: 'switch',
+ readonly: function(state) {
+ let evn_update = state.evnt_update;
+ if (!_.isUndefined(evn_update) && obj.nodeInfo.server.server_type == 'ppas')
+ return false;
+ return obj.inCatalog();
+ },
+ },{
+ id: 'evnt_delete', label: gettext('DELETE'),
+ type: 'switch',
+ readonly: function(state) {
+ let evn_delete = state.evnt_delete;
+ if (!_.isUndefined(evn_delete) && obj.nodeInfo.server.server_type == 'ppas')
+ return false;
+ return obj.inCatalog();
+ },
+ },{
+ id: 'evnt_truncate', label: gettext('TRUNCATE'),
+ type: 'switch',
+ readonly: function(state) {
+ let evn_truncate = state.evnt_truncate;
+ // Views cannot have TRUNCATE triggers.
+ if ('view' in obj.nodeInfo)
+ return true;
+
+ if (!_.isUndefined(evn_truncate) && obj.nodeInfo.server.server_type == 'ppas')
+ return false;
+ return obj.inCatalog();
+ },
+ }
+ ];
+ }
+}
+
+export default class CompoundTriggerSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, initValues={}) {
+ super({
+ name: undefined,
+ ...initValues,
+ });
+
+ this.fieldOptions = {
+ columns: [],
+ ...fieldOptions,
+ };
+ this.nodeInfo = nodeInfo;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', noEmpty: true,
+ disabled: obj.inCatalog(),
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'int', mode: ['properties'],
+ },{
+ id: 'is_enable_trigger', label: gettext('Trigger enabled?'),
+ mode: ['edit', 'properties'],
+ disabled: obj.inCatalog(),
+ type: 'select', controlProps: { allowClear: false },
+ options: [
+ {label: gettext('Enable'), value: 'O'},
+ {label: gettext('Enable Replica'), value: 'R'},
+ {label: gettext('Enable Always'), value: 'A'},
+ {label: gettext('Disable'), value: 'D'},
+ ],
+ },{
+ type: 'nested-fieldset', label: gettext('FOR Events'), group: gettext('Events'),
+ schema: new ForEventsSchema({}, this.nodeInfo),
+ },{
+ id: 'whenclause', label: gettext('When'), group: gettext('Events'),
+ type: 'sql', disabled: obj.inCatalog(),
+ readonly: function(state) { return !obj.isNew(state); },
+ },{
+ id: 'columns', label: gettext('Columns'), group: gettext('Events'),
+ editable: false, type: 'select', options: this.fieldOptions.columns,
+ controlProps: { allowClear: false, multiple: true }, deps: ['evnt_update'],
+ disabled: function(state) {
+ if(obj.inCatalog()) {
+ return true;
+ }
+ // Enable column only if update event is set true
+ let isUpdate = state.evnt_update;
+ if(!_.isUndefined(isUpdate) && isUpdate) {
+ return false;
+ }
+ return true;
+ },
+ readonly: function(state) { return !obj.isNew(state); },
+ },{
+ id: 'prosrc', label: gettext('Code'), group: gettext('Code'),
+ type: 'sql', mode: ['create', 'edit'],
+ isFullTab: true,
+ disabled: function(state) {
+ if(obj.isNew(state) && _.isUndefined(state.prosrc)) {
+ state.prosrc = obj.getCodeTemplate();
+ }
+ return false;
+ },
+ },{
+ id: 'is_sys_trigger', label: gettext('System trigger?'),
+ type: 'switch', disabled: obj.inCatalog(), mode: ['properties'],
+ readonly: function(state) { return !obj.isNew(state); },
+ },{
+ id: 'description', label: gettext('Comment'), type: 'multiline',
+ disabled: obj.inCatalog(),
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ if(!state.evnt_truncate && !state.evnt_delete && !state.evnt_update && !state.evnt_insert) {
+ setError('evnt_insert', gettext('Specify at least one event.'));
+ return true;
+ } else {
+ setError('evnt_insert', null);
+ }
+
+ if(isEmptyString(state.prosrc)) {
+ setError(state.prosrc, gettext('Code cannot be empty.'));
+ return true;
+ } else {
+ setError(state.prosrc, null);
+ }
+ }
+
+ // This function returns the code template for compound trigger
+ getCodeTemplate() {
+ return gettext('-- Enter any global declarations below:\n\n' +
+ '-- BEFORE STATEMENT block. Delete if not required.\n' +
+ 'BEFORE STATEMENT IS\n' +
+ ' -- Enter any local declarations here\n' +
+ 'BEGIN\n' +
+ ' -- Enter any required code here\n' +
+ 'END;\n\n' +
+ '-- AFTER STATEMENT block. Delete if not required.\n' +
+ 'AFTER STATEMENT IS\n' +
+ ' -- Enter any local declarations here\n' +
+ 'BEGIN\n' +
+ ' -- Enter any required code here\n' +
+ 'END;\n\n' +
+ '-- BEFORE EACH ROW block. Delete if not required.\n' +
+ 'BEFORE EACH ROW IS\n' +
+ ' -- Enter any local declarations here\n' +
+ 'BEGIN\n' +
+ ' -- Enter any required code here\n' +
+ 'END;\n\n' +
+ '-- AFTER EACH ROW block. Delete if not required.\n' +
+ 'AFTER EACH ROW IS\n' +
+ ' -- Enter any local declarations here\n' +
+ 'BEGIN\n' +
+ ' -- Enter any required code here\n' +
+ 'END;\n\n' +
+ '-- INSTEAD OF EACH ROW block. Delete if not required.\n' +
+ 'INSTEAD OF EACH ROW IS\n' +
+ ' -- Enter any local declarations here\n' +
+ 'BEGIN\n' +
+ ' -- Enter any required code here\n' +
+ 'END;');
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/templates/compound_triggers/css/compound_trigger.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/templates/compound_triggers/css/compound_trigger.css
new file mode 100644
index 0000000000000000000000000000000000000000..198a1845adfca368d31f2445bda983647453a98d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/templates/compound_triggers/css/compound_trigger.css
@@ -0,0 +1,23 @@
+.icon-coll-compound_trigger {
+ background-image: url('{{ url_for('NODE-compound_trigger.static', filename='img/coll-compound_trigger.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-compound_trigger {
+ background-image: url('{{ url_for('NODE-compound_trigger.static', filename='img/compound_trigger.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-compound_trigger-bad {
+ background-image: url('{{ url_for('NODE-compound_trigger.static', filename='img/compound_trigger-bad.svg') }}') !important;
+ background-size: 20px !important;
+ border-radius: 10px
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b69a143cfff92a202162a3e40270397d47a8cc23
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/utils.py
@@ -0,0 +1,197 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Compound Triggers. """
+
+from flask import render_template
+from flask_babel import gettext
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'compound_triggers/sql/{0}/#{1}#'.format(
+ conn_obj.manager.server_type, conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_column_details(conn, tid, clist, template_path=None):
+ """
+ This functional will fetch list of column for trigger.
+ :param conn:
+ :param tid:
+ :param clist:
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_columns.sql']),
+ tid=tid, clist=clist)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+ columns = []
+ for row in rset['rows']:
+ columns.append(row['name'])
+
+ return columns
+
+
+@get_template_path
+def get_sql(conn, data, tid, trid, datlastsysoid, template_path=None):
+ """
+ This function will generate sql from model data
+ :param conn: Connection Object
+ :param data: Data
+ :param tid: Table ID
+ :param trid: Trigger ID
+ :param datlastsysoid:
+ :param template_path: Optional template path
+ :return:
+ """
+ name = data['name'] if 'name' in data else None
+ if trid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, trid=trid,
+ datlastsysoid=datlastsysoid)
+
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+ elif len(res['rows']) == 0:
+ raise ObjectGone(
+ gettext('Could not find the compound trigger in the table.'))
+
+ old_data = dict(res['rows'][0])
+ # If name is not present in data then
+ # we will fetch it from old data, we also need schema & table name
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ if len(old_data['tgattr']) > 1:
+ columns = ', '.join(old_data['tgattr'].split(' '))
+ old_data['columns'] = get_column_details(conn, tid, columns)
+
+ old_data = trigger_definition(old_data)
+
+ SQL = render_template(
+ "/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn
+ )
+ else:
+ required_args = {
+ 'name': 'Name'
+ }
+
+ for arg in required_args:
+ if arg not in data:
+ return gettext('-- definition incomplete')
+
+ # If the request for new object which do not have did
+ SQL = render_template("/".join([template_path, 'create.sql']),
+ data=data, conn=conn)
+ return SQL, name
+
+
+@get_template_path
+def get_reverse_engineered_sql(conn, **kwargs):
+ """
+ This function will return reverse engineered sql for trigger(s).
+ :param conn: Connection Object
+ :param kwargs
+ :return:
+ """
+ schema = kwargs.get('schema')
+ table = kwargs.get('table')
+ tid = kwargs.get('tid')
+ trid = kwargs.get('trid')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ template_path = kwargs.get('template_path', None)
+
+ SQL = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, trid=trid,
+ datlastsysoid=datlastsysoid)
+
+ status, res = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(
+ gettext('Could not find the compound trigger in the table.'))
+
+ data = dict(res['rows'][0])
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = schema
+ data['table'] = table
+
+ if len(data['tgattr']) >= 1:
+ columns = ', '.join(data['tgattr'].split(' '))
+ data['columns'] = get_column_details(conn, tid, columns)
+
+ data = trigger_definition(data)
+
+ SQL, _ = get_sql(conn, data, tid, None, datlastsysoid)
+
+ sql_header = "-- Compound Trigger: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([template_path, 'delete.sql']),
+ data=data, conn=conn)
+
+ SQL = sql_header + '\n\n' + SQL.strip('\n')
+
+ # If trigger is disabled then add sql code for the same
+ if data['is_enable_trigger'] != 'O':
+ SQL += '\n\n'
+ SQL += render_template("/".join([template_path,
+ 'enable_disable_trigger.sql']),
+ data=data, conn=conn)
+ return SQL
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b90086de0f27233970be12e24ea7266e4e61f933
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/__init__.py
@@ -0,0 +1,205 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Constraint Node"""
+
+import json
+from flask import request
+from functools import wraps
+from pgadmin.utils.driver import get_driver
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, make_response
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.utils.ajax import make_json_response, \
+ make_response as ajax_response, internal_server_error
+
+from config import PG_DEFAULT_DRIVER
+from .type import ConstraintRegistry
+
+
+class ConstraintsModule(CollectionNodeModule):
+ """
+ class ConstraintsModule(CollectionNodeModule)
+
+ A module class for Constraint node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the ConstraintsModule and it's base
+ module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for constraint node, when any of the database
+ node is initialized.
+ """
+
+ _NODE_TYPE = 'constraints'
+ _COLLECTION_LABEL = gettext("Constraints")
+
+ def __init__(self, *args, **kwargs):
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs or 'foid' in kwargs)
+ tid = kwargs.get('tid', kwargs.get('vid', kwargs.get('foid', None)))
+ nodes = []
+ for name in ConstraintRegistry.registry:
+ view = (ConstraintRegistry.registry[name])['nodeview']
+ nodes.append(view.node_type)
+ node = self.generate_browser_collection_node(tid)
+ node['nodes'] = nodes
+ yield node
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for constraints, when any of the table node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ def register(self, app, options):
+ """
+ Override the default register function to automagically register
+ sub-modules at once.
+ """
+ from .check_constraint import blueprint as module
+ self.submodules.append(module)
+
+ from .exclusion_constraint import blueprint as module
+ self.submodules.append(module)
+
+ from .foreign_key import blueprint as module
+ self.submodules.append(module)
+
+ from .index_constraint import primary_key_blueprint as module
+ self.submodules.append(module)
+
+ from .index_constraint import unique_constraint_blueprint as module
+ self.submodules.append(module)
+
+ super().register(app, options)
+
+
+blueprint = ConstraintsModule(__name__)
+
+
+@blueprint.route('/nodes//////')
+def nodes(**kwargs):
+ """
+ Returns all constraint as a tree node.
+
+ Args:
+ **kwargs:
+
+ Returns:
+
+ """
+
+ cmd = {"cmd": "nodes"}
+ res = []
+ for name in ConstraintRegistry.registry:
+ module = (ConstraintRegistry.registry[name])['nodeview']
+ view = module(**cmd)
+ res = res + view.get_nodes(**kwargs)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+
+@blueprint.route('/obj//////')
+def proplist(**kwargs):
+ """
+ Returns all constraint with properties.
+ Args:
+ **kwargs:
+
+ Returns:
+
+ """
+
+ cmd = {"cmd": "obj"}
+ res = []
+ for name in ConstraintRegistry.registry:
+ module = (ConstraintRegistry.registry[name])['nodeview']
+ view = module(**cmd)
+ res = res + view.get_node_list(**kwargs)
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+
+@blueprint.route('/obj//////',
+ methods=['DELETE'])
+@blueprint.route('/delete//////',
+ methods=['DELETE'])
+def delete(**kwargs):
+ """
+ Delete multiple constraints under the table.
+ Args:
+ **kwargs:
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data)
+
+ if 'delete' in request.base_url:
+ cmd = {"cmd": "delete"}
+ else:
+ cmd = {"cmd": "obj"}
+ res = []
+ module_wise_data = {}
+
+ for d in data['ids']:
+ if d['_type'] in module_wise_data:
+ module_wise_data[d['_type']].append(d['id'])
+ else:
+ module_wise_data[d['_type']] = [d['id']]
+
+ for name in ConstraintRegistry.registry:
+ if name in module_wise_data:
+ module = (ConstraintRegistry.registry[name])['nodeview']
+ view = module(**cmd)
+ request.data = json.dumps({'ids': module_wise_data[name]})
+ response = view.delete(**kwargs)
+ res = json.loads(response.data.decode('utf-8'))
+ if not res['success']:
+ return response
+
+ return make_json_response(
+ success=1,
+ info=gettext("Constraints dropped.")
+ )
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c03e4675ff1c2b74f0d4bd6f7a8bcd6e48b75b6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py
@@ -0,0 +1,899 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements the Check Constraint Module."""
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.type import ConstraintRegistry
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.check_constraint import utils as check_utils
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+
+
+class CheckConstraintModule(CollectionNodeModule):
+ """
+ class CheckConstraintModule(CollectionNodeModule):
+
+ This class represents The Check Constraint Module.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Initialize the Check Constraint Module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Generate the Check Constraint collection node.
+
+ * node_inode(gid, sid, did, scid)
+ - Returns Check Constraint node as leaf node.
+
+ * script_load()
+ - Load the module script for the Check Constraint, when any of the
+ Check node is initialized.
+ """
+ _NODE_TYPE = 'check_constraint'
+ _COLLECTION_LABEL = gettext("Check Constraints")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid, doid):
+ """
+ Generate the Check Constraint collection node.
+ """
+ yield self.generate_browser_collection_node(doid)
+
+ @property
+ def node_inode(self):
+ """
+ Returns Check Constraint node as leaf node.
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for the Check Constraint, when any of the
+ Check node is initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ return [
+ render_template(
+ "check_constraint/css/check_constraint.css",
+ node_type=self.node_type
+ )
+ ]
+
+
+blueprint = CheckConstraintModule(__name__)
+
+
+class CheckConstraintView(PGChildNodeView):
+ """
+ class CheckConstraintView(PGChildNodeView):
+
+ This class inherits PGChildNodeView to get the different routes for
+ the module.
+
+ The class is responsible to Create, Read, Update and Delete operations for
+ the Check Constraint.
+
+ Methods:
+ -------
+
+ * check_precondition(f):
+ - Works as a decorator.
+ - Checks database connection status.
+ - Attach connection object and template path.
+
+ * list(gid, sid, did, scid, doid):
+ - List the Check Constraints.
+
+ * nodes(gid, sid, did, scid):
+ - Returns all the Check Constraints to generate Nodes in the browser.
+
+ * properties(gid, sid, did, scid, doid):
+ - Returns the Check Constraint properties.
+
+ * create(gid, sid, did, scid):
+ - Creates a new Check Constraint object.
+
+ * update(gid, sid, did, scid, doid):
+ - Updates the Check Constraint object.
+
+ * delete(gid, sid, did, scid, doid):
+ - Drops the Check Constraint object.
+
+ * sql(gid, sid, did, scid, doid=None):
+ - Returns the SQL for the Check Constraint object.
+
+ * msql(gid, sid, did, scid, doid=None):
+ - Returns the modified SQL.
+
+ * dependents(gid, sid, did, scid, tid, cid):
+ - Returns the dependents for the Check Constraint object.
+
+ * dependencies(gid, sid, did, scid, tid, cid):
+ - Returns the dependencies for the Check Constraint object.
+
+ * validate_check_constraint(gid, sid, did, scid, tid, cid):
+ - Validate check constraint.
+ """
+ node_type = blueprint.node_type
+ CHECK_CONSTRAINT_PATH = 'check_constraint/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'cid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'validate': [{'get': 'validate_check_constraint'}],
+ })
+
+ def check_precondition(f):
+ """
+ Works as a decorator.
+ Checks database connection status.
+ Attach connection object and template path.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.CHECK_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ schema, table = check_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ def end_transaction(self):
+ """
+ End database transaction.
+ Returns:
+
+ """
+ SQL = "END;"
+ self.conn.execute_scalar(SQL)
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid, cid=None):
+ """
+ List the Check Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Id
+ """
+ try:
+ res = self.get_node_list(gid, sid, did, scid, tid, cid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_node_list(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns all check constraints
+ nodes within that collection as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Cehck constraint ID
+
+ Returns:
+
+ """
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.qtIdent = driver.qtIdent
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.CHECK_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ schema, table = check_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), tid=tid)
+ _, res = self.conn.execute_dict(SQL)
+
+ for row in res['rows']:
+ row['_type'] = self.node_type
+
+ return res['rows']
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, cid):
+ """
+ Returns all the Check Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check constraint Id.
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid,
+ cid=cid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ if len(rset['rows']) == 0:
+ return gone(gettext("""Could not find the check constraint."""))
+
+ if "convalidated" in rset['rows'][0] and \
+ rset['rows'][0]["convalidated"]:
+ icon = "icon-check_constraint_bad"
+ valid = False
+ else:
+ icon = "icon-check_constraint"
+ valid = True
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon=icon,
+ valid=valid
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ Returns all the Check Constraints.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check constraint Id.
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ if "convalidated" in row and row["convalidated"]:
+ icon = "icon-check_constraint_bad"
+ valid = False
+ else:
+ icon = "icon-check_constraint"
+ valid = True
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=icon,
+ valid=valid,
+ description=row['comment']
+ ))
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_nodes(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns all event check constraint as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Check constraint ID
+
+ Returns:
+
+ """
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ self.manager = driver.connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.qtIdent = driver.qtIdent
+
+ # Set the template path for the SQL scripts
+ self.template_path = self.CHECK_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ schema, table = check_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ if "convalidated" in row and row["convalidated"]:
+ icon = "icon-check_constraint_bad"
+ valid = False
+ else:
+ icon = "icon-check_constraint"
+ valid = True
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=icon,
+ valid=valid
+ ))
+ return res
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, cid):
+ """
+ Returns the Check Constraints property.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Check Id
+ cid: Check Constraint Id
+ """
+
+ status, res = check_utils.get_check_constraints(self.conn, tid, cid)
+ if not status:
+ return res
+
+ if len(res) == 0:
+ return gone(gettext(
+ """Could not find the check constraint in the table."""
+ ))
+
+ result = res
+ if cid:
+ result = res[0]
+ result['is_sys_obj'] = (
+ result['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return ajax_response(
+ response=result,
+ status=200
+ )
+
+ @staticmethod
+ def _get_req_data():
+ """
+ Get all required data from request data attribute.
+ :return: Request data and Error if any.
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ required_args = ['consrc']
+
+ for arg in required_args:
+ if arg not in data or data[arg] == '':
+ return True, make_json_response(
+ status=400,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg),
+ ), data
+ return False, '', data
+
+ @staticmethod
+ def _check_valid_icon(res):
+ """
+ Check and return icon value and is valid value.
+ :param res: Response data.
+ :return: icon value and valid flag.
+ """
+ if "convalidated" in res['rows'][0] and res['rows'][0]["convalidated"]:
+ icon = "icon-check_constraint_bad"
+ valid = False
+ else:
+ icon = "icon-check_constraint"
+ valid = True
+
+ return icon, valid
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function will create a primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Check constraint ID
+
+ Returns:
+
+ """
+ is_error, errmsg, data = CheckConstraintView._get_req_data()
+ if is_error:
+ return errmsg
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ # Checking whether the table is deleted via query tool
+ if len(data['table']) == 0:
+ return gone(gettext(self.not_found_error_msg('Table')))
+
+ try:
+ if 'name' not in data or data['name'] == "":
+ sql = "BEGIN;"
+ # Start transaction.
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ # The below SQL will execute CREATE DDL only
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+
+ status, msg = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=msg)
+
+ if 'name' not in data or data['name'] == "":
+ sql = render_template(
+ "/".join([self.template_path,
+ 'get_oid_with_transaction.sql'],
+ ),
+ tid=tid)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ self.end_transaction()
+
+ data['name'] = res['rows'][0]['name']
+
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid,
+ name=data['name'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ icon, valid = CheckConstraintView._check_valid_icon(res)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['rows'][0]['oid'],
+ tid,
+ data['name'],
+ icon=icon,
+ valid=valid
+ )
+ )
+
+ except Exception as e:
+ self.end_transaction()
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=e
+ )
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, cid=None):
+ """
+ Drops the Check Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Check Id
+ cid: Check Constraint Id
+ """
+ if cid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [cid]}
+
+ try:
+ for cid in data['ids']:
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, cid=cid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified check constraint '
+ 'could not be found.\n'
+ )
+ )
+
+ data = res['rows'][0]
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Check constraint dropped.")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, cid):
+ """
+ Updates the Check Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ SQL, name = check_utils.get_sql(self.conn, data, tid, cid)
+ if not SQL:
+ return name
+ SQL = SQL.strip('\n').strip(' ')
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']), cid=cid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if "convalidated" in res['rows'][0] and \
+ res['rows'][0]["convalidated"]:
+ icon = 'icon-check_constraint_bad'
+ valid = False
+ else:
+ icon = 'icon-check_constraint'
+ valid = True
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ cid,
+ tid,
+ name,
+ icon=icon,
+ valid=valid,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, cid=None):
+ """
+ Returns the SQL for the Check Constraint object.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, cid=cid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the object on the server.")
+ )
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+
+ sql_header = "-- Constraint: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data)
+ sql_header += "\n"
+
+ SQL = sql_header + SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, cid=None):
+ """
+ Returns the modified SQL.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+
+ Returns:
+ Check Constraint object in json format.
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ sql, name = check_utils.get_sql(self.conn, data, tid, cid)
+ if not sql:
+ return name
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, cid):
+ """
+ This function get the dependents and return ajax response
+ for the Check Constraint node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+ """
+ dependents_result = self.get_dependents(self.conn, cid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, cid):
+ """
+ This function get the dependencies and return ajax response
+ for the Check Constraint node.
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+ """
+ dependencies_result = self.get_dependencies(self.conn, cid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def validate_check_constraint(self, gid, sid, did, scid, tid, cid):
+ """
+ Validate check constraint.
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ cid: Check Constraint Id
+
+ Returns:
+
+ """
+ data = {}
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']), cid=cid)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ data['name'] = res
+ sql = render_template(
+ "/".join([self.template_path, 'validate.sql']), data=data)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Check constraint updated."),
+ data={
+ 'id': cid,
+ 'tid': tid,
+ 'scid': scid,
+ 'did': did
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+
+constraint = ConstraintRegistry(
+ 'check_constraint', CheckConstraintModule, CheckConstraintView
+)
+CheckConstraintView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint-bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint-bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..33970e18820546a5381dd8ebdbb62bcbe34dac9c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint-bad.svg
@@ -0,0 +1 @@
+check-constraints-bad
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint.svg
new file mode 100644
index 0000000000000000000000000000000000000000..2e6f008bab7bda2d17877b0ed7cfb9993140718a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/img/check-constraint.svg
@@ -0,0 +1 @@
+check-constraints
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.js
new file mode 100644
index 0000000000000000000000000000000000000000..992339d073db3a8682bf46f43babce533ee5b813
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.js
@@ -0,0 +1,120 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import CheckConstraintSchema from './check_constraint.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../../../static/js/api_instance';
+
+// Check Constraint Module: Node
+define('pgadmin.node.check_constraint', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, schemaChildTreeNode) {
+
+ // Check Constraint Node
+ if (!pgBrowser.Nodes['check_constraint']) {
+ pgAdmin.Browser.Nodes['check_constraint'] = pgBrowser.Node.extend({
+ type: 'check_constraint',
+ label: gettext('Check'),
+ collection_type: 'coll-constraints',
+ sqlAlterHelp: 'ddl-alter.html',
+ sqlCreateHelp: 'ddl-constraints.html',
+ dialogHelp: url_for('help.static', {'filename': 'check_dialog.html'}),
+ hasSQL: true,
+ hasDepends: true,
+ parent_type: ['table','partition','foreign_table'],
+ url_jump_after_node: 'schema',
+ Init: function() {
+ // Avoid mulitple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_check_constraint_on_coll', node: 'coll-constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Check...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'validate_check_constraint', node: 'check_constraint', module: this,
+ applies: ['object', 'context'], callback: 'validate_check_constraint',
+ category: 'validate', priority: 4, label: gettext('Validate check constraint'),
+ enable : 'is_not_valid', data: {action: 'edit', check: true},
+ },
+ ]);
+
+ },
+ is_not_valid: function(itemData, item, data) {
+ if (this.canCreate(itemData, item, data)) {
+ return (itemData && !itemData.valid);
+ } else {
+ return false;
+ }
+ },
+ callbacks: {
+ validate_check_constraint: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (d) {
+ let data = d;
+ getApiInstance().get(obj.generate_url(i, 'validate', d, true))
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.valid = true;
+ data.icon = 'icon-check_constraint';
+ t.addIcon(i, {icon: data.icon});
+ setTimeout(function() {t.deselect(i);}, 10);
+ setTimeout(function() {t.select(i);}, 100);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.unload(i);
+ });
+ }
+ return false;
+ },
+ },
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ getSchema: function(){
+ return new CheckConstraintSchema();
+ },
+ // Below function will enable right click menu for creating check constraint.
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [];
+ // To iterate over tree to check parent node
+ while (i) {
+ // If it is schema then allow user to c reate table
+ if (_.indexOf(['schema'], d._type) > -1)
+ return true;
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ return (_.indexOf(parents, 'catalog') <= -1);
+ },
+ });
+
+ }
+
+ return pgBrowser.Nodes['check_constraint'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..57046b0d4c129f62f230ac18faf5c359270f2ea5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/static/js/check_constraint.ui.js
@@ -0,0 +1,102 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+export default class CheckConstraintSchema extends BaseUISchema {
+ constructor() {
+ super({
+ name: undefined,
+ oid: undefined,
+ description: undefined,
+ consrc: undefined,
+ connoinherit: undefined,
+ convalidated: true,
+ });
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get inTable() {
+ if(_.isUndefined(this.nodeInfo)) {
+ return true;
+ }
+ return _.isUndefined(this.nodeInfo['check_constraint']);
+ }
+
+ isReadonly(state) {
+ // If we are in table edit mode then
+ if(this.top) {
+ return !_.isUndefined(state.oid);
+ }
+ return !this.isNew(state);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type:'text', cell:'text',
+ mode: ['properties', 'create', 'edit'], editable:true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'is_sys_obj', label: gettext('System check constraint?'),
+ cell:'boolean', type: 'switch', mode: ['properties'],
+ },{
+ id: 'comment', label: gettext('Comment'), type: 'multiline', cell: 'text',
+ mode: ['properties', 'create', 'edit'],
+ deps:['name'], disabled: function(state) {
+ return isEmptyString(state.name);
+ },
+ depChange: (state)=>{
+ if(isEmptyString(state.name)) {
+ return {comment: ''};
+ }
+ },
+ },{
+ id: 'consrc', label: gettext('Check'), type: 'multiline', cell: 'text',
+ group: gettext('Definition'), mode: ['properties', 'create', 'edit'],
+ readonly: obj.isReadonly, noEmpty: true, editable: (state) => {return obj.isNew(state);},
+ },{
+ id: 'connoinherit', label: gettext('No inherit?'), type: 'switch', cell: 'switch',
+ group: gettext('Definition'), mode: ['properties', 'create', 'edit'], min_version: 90200,
+ deps: [['is_partitioned']],
+ disabled: function() {
+ // Disabled if table is a partitioned table.
+ return obj.inTable && obj.top?.sessData.is_partitioned;
+ },
+ depChange: ()=>{
+ if(obj.inTable && obj.top?.sessData.is_partitioned) {
+ return {connoinherit: false};
+ }
+ },
+ readonly: obj.isReadonly,
+ },{
+ id: 'convalidated', label: gettext('Don\'t validate?'), type: 'switch', cell: 'switch',
+ group: gettext('Definition'), min_version: 90200,
+ readonly: (state)=>{
+ // If we are in table edit mode then
+ if(obj.inTable && obj.top && !obj.top.isNew()) {
+ return !(_.isUndefined(state.oid) || state.convalidated);
+ }
+ return !obj.isNew(state) && !obj.origData.convalidated;
+ },
+ mode: ['properties', 'create', 'edit'],
+ }];
+ }
+
+ validate() {
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/templates/check_constraint/css/check_constraint.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/templates/check_constraint/css/check_constraint.css
new file mode 100644
index 0000000000000000000000000000000000000000..6e4e7e9eaee18cd63984edbd8b62ab52f2c76a76
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/templates/check_constraint/css/check_constraint.css
@@ -0,0 +1,17 @@
+.icon-check_bad, .icon-check_constraint_bad {
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/check-constraint-bad.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-check, .icon-check_constraint {
+ background-image: url('{{ url_for('NODE-%s.static' % node_type, filename='img/check-constraint.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8a7f0db2856b7f4a9a95537a9d847b2263783e0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/utils.py
@@ -0,0 +1,186 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Check Constraint. """
+
+from flask import render_template
+from flask_babel import gettext as _
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'check_constraint/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_check_constraints(conn, tid, cid=None, template_path=None):
+ """
+ This function is used to fetch information of the
+ check constraint(s) for the given table.
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param cid: Check Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = render_template("/".join(
+ [template_path, 'properties.sql']), tid=tid, cid=cid)
+
+ status, result = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=result)
+
+ return True, result['rows']
+
+
+def _check_delete_constraint(constraint, data, template_path, conn, sql):
+ """
+ This function if user deleted any constraint.
+ :param constraint: Constraint list in data.
+ :param data: Data.
+ :param template_path: sql template path for delete.
+ :param conn: connection.
+ :param sql: list for append delete constraint sql.
+ """
+ if 'deleted' in constraint:
+ for c in constraint['deleted']:
+ c['schema'] = data['schema']
+ c['nspname'] = data['schema']
+ c['table'] = data['name']
+
+ # Sql for drop
+ sql.append(
+ render_template("/".join(
+ [template_path, 'delete.sql']),
+ data=c, conn=conn).strip("\n")
+ )
+
+
+@get_template_path
+def get_check_constraint_sql(conn, tid, data, template_path=None):
+ """
+ This function will return sql for check constraints.
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param data: Data
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = []
+ # Check if constraint is in data
+ # If yes then we need to check for add/change/delete
+ if 'check_constraint' in data:
+ constraint = data['check_constraint']
+ # If constraint(s) is/are deleted
+ _check_delete_constraint(constraint, data, template_path, conn, sql)
+
+ if 'changed' in constraint:
+ for c in constraint['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ modified_sql, _ = get_sql(conn, c, tid, c['oid'])
+ sql.append(modified_sql.strip('\n'))
+
+ if 'added' in constraint:
+ for c in constraint['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ add_sql, _ = get_sql(conn, c, tid)
+ sql.append(add_sql.strip("\n"))
+
+ if len(sql) > 0:
+ # Join all the sql(s) as single string
+ return '\n\n'.join(sql)
+ else:
+ return None
+
+
+@get_template_path
+def get_sql(conn, data, tid, cid=None, template_path=None):
+ """
+ This function will generate sql from model data.
+ :param conn: Connection Object
+ :param data: data
+ :param tid: Table id
+ :param cid: Check Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+ name = data['name'] if 'name' in data else None
+ if cid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, cid=cid)
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(
+ _('Could not find the check constraint in the table.'))
+
+ old_data = res['rows'][0]
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ sql = render_template("/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn)
+ else:
+ if 'consrc' not in data or \
+ (isinstance(data['consrc'], list) and len(data['consrc']) < 1):
+ return _('-- definition incomplete'), name
+
+ sql = render_template("/".join([template_path, 'create.sql']),
+ data=data, conn=conn)
+
+ return sql, name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ae4f2f72d354b4e7d6bc40cfb1b3de4700582b5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/__init__.py
@@ -0,0 +1,933 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Exclusion constraint Node"""
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.type import ConstraintRegistry, ConstraintTypeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.exclusion_constraint import utils as exclusion_utils
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+
+
+class ExclusionConstraintModule(ConstraintTypeModule):
+ """
+ class ForeignKeyConstraintModule(CollectionNodeModule)
+
+ A module class for Exclusion constraint node derived from
+ ConstraintTypeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the ForeignKeyConstraintModule and
+ it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for language, when any of the database node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'exclusion_constraint'
+ _COLLECTION_LABEL = gettext("Exclusion Constraints")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the ForeignKeyConstraintModule and
+ it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+
+ Returns:
+
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, tid):
+ """
+ Generate the collection node
+ """
+ pass
+
+ @property
+ def node_inode(self):
+ """
+ Override this property to make the node a leaf node.
+
+ Returns: False as this is the leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for exclusion_constraint, when any of the
+ table node is initialized.
+
+ Returns: node type of the server module.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = ExclusionConstraintModule(__name__)
+
+
+class ExclusionConstraintView(PGChildNodeView):
+ """
+ class ExclusionConstraintView(PGChildNodeView)
+
+ A view class for Exclusion constraint node derived from
+ PGChildNodeView. This class is responsible for all the stuff related
+ to view like creating, updating Exclusion constraint node, showing
+ properties, showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the ForeignKeyConstraintView and
+ it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * end_transaction()
+ - To end any existing database transaction.
+
+ * list()
+ - This function returns Exclusion constraint nodes within that
+ collection as http response.
+
+ * get_list()
+ - This function is used to list all the language nodes within that
+ collection and return list of Exclusion constraint nodes.
+
+ * nodes()
+ - This function returns child node within that collection.
+ Here return all Exclusion constraint node as http response.
+
+ * get_nodes()
+ - returns all Exclusion constraint nodes' list.
+
+ * properties()
+ - This function will show the properties of the selected Exclusion.
+
+ * update()
+ - This function will update the data for the selected Exclusion.
+
+ * msql()
+ - This function is used to return modified SQL for the selected
+ Exclusion.
+
+ * get_sql()
+ - This function will generate sql from model data.
+
+ * sql():
+ - This function will generate sql to show it in sql pane for the
+ selected Exclusion.
+
+ * get_access_methods():
+ - Returns access methods for exclusion constraint.
+
+ * get_oper_class():
+ - Returns operator classes for selected access method.
+
+ * get_operator():
+ - Returns operators for selected column.
+
+ * dependency():
+ - This function will generate dependency list show it in dependency
+ pane for the selected Exclusion.
+
+ * dependent():
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Exclusion.
+ """
+
+ node_type = 'exclusion_constraint'
+ EXCLUSION_CONSTRAINT_PATH = 'exclusion_constraint/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [{'type': 'int', 'id': 'exid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = exclusion_utils.get_parent(self.conn,
+ kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+ return wrap
+
+ def end_transaction(self):
+ SQL = render_template(
+ "/".join([self.template_path, 'end.sql']))
+ # End transaction if any.
+ self.conn.execute_scalar(SQL)
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function is used to list all the Exclusion constraint
+ nodes within that collection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ status, res = exclusion_utils.get_exclusion_constraints(
+ self.conn, did, tid, exid)
+ if not status:
+ return res
+
+ if len(res) == 0:
+ return gone(gettext(
+ """Could not find the exclusion constraint in the table."""
+ ))
+
+ result = res
+ if exid:
+ result = res[0]
+ result['is_sys_obj'] = (
+ result['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return ajax_response(
+ response=result,
+ status=200
+ )
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function returns all exclusion constraints
+ nodes within that collection as a http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ try:
+ res = self.get_node_list(gid, sid, did, scid, tid, exid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_node_list(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function returns all exclusion constraints
+ nodes within that collection as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+
+ self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = exclusion_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ did=did,
+ tid=tid)
+ _, res = self.conn.execute_dict(SQL)
+
+ for row in res['rows']:
+ row['_type'] = self.node_type
+
+ return res['rows']
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, exid):
+ """
+ This function returns all Exclusion constraint nodes as a
+ http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid,
+ exid=exid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ if len(rset['rows']) == 0:
+ return gone(
+ gettext("""Could not find the exclusion constraint."""))
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-exclusion_constraint"
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function returns all Exclusion constraint nodes as a
+ http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-exclusion_constraint",
+ description=row['comment']
+ ))
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_nodes(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function returns all Exclusion constraint nodes as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+
+ self.template_path = self.EXCLUSION_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = exclusion_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-exclusion_constraint"
+ ))
+ return res
+
+ @staticmethod
+ def parse_input_data(data):
+ """
+ This function is used to parse the input data.
+ :param data:
+ :return:
+ """
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ return data
+
+ @staticmethod
+ def check_required_args(data, required_args):
+ """
+ This function is used to check the required arguments.
+ :param data:
+ :param required_args:
+ :return:
+ """
+ for arg in required_args:
+ if arg not in data or \
+ (isinstance(data[arg], list) and len(data[arg]) < 1):
+ return arg
+
+ return None
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function will create a Exclusion constraint.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ required_args = ['columns']
+
+ data = json.loads(request.data)
+ data = self.parse_input_data(data)
+ arg_missing = self.check_required_args(data, required_args)
+ if arg_missing is not None:
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=gettext(
+ "Could not find required parameter ({})."
+ ).format(arg_missing)
+ )
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ if data.get('name', '') == "":
+ SQL = render_template(
+ "/".join([self.template_path, 'begin.sql']))
+ # Start transaction.
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ # The below SQL will execute CREATE DDL only
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ if data.get('name', '') == "":
+ sql = render_template(
+ "/".join([self.template_path,
+ 'get_oid_with_transaction.sql']),
+ tid=tid)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ self.end_transaction()
+
+ data['name'] = res['rows'][0]['name']
+
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ name=data['name'], conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['rows'][0]['oid'],
+ tid,
+ data['name'],
+ icon="icon-exclusion_constraint"
+ )
+ )
+
+ except Exception as e:
+ self.end_transaction()
+
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=str(e)
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function will update the data for the selected
+ Exclusion constraint.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql, name = \
+ exclusion_utils.get_sql(self.conn, data, did, tid, exid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ name=data['name'], conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ exid,
+ tid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function will delete an existing Exclusion.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ if exid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [exid]}
+
+ # Below code will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+ try:
+ for exid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']),
+ cid=exid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified exclusion constraint could not '
+ 'be found.\n'
+ )
+ )
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ cascade=cascade)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Exclusion constraint dropped.")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function returns modified SQL for the selected
+ Exclusion constraint.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ sql, _ = \
+ exclusion_utils.get_sql(self.conn, data, did, tid, exid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, exid=None):
+ """
+ This function generates sql to show in the sql pane for the selected
+ Exclusion constraint.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ Returns:
+
+ """
+ try:
+ status, rows = exclusion_utils.get_exclusion_constraints(
+ self.conn, did, tid, exid, template_path=self.template_path
+ )
+ if not status:
+ return rows
+ if len(rows) == 0:
+ return gone(
+ gettext("Could not find the exclusion constraint."))
+
+ data = rows[0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]), data=data,
+ conn=self.conn)
+
+ sql_header = "-- Constraint: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data)
+ sql_header += "\n"
+
+ SQL = sql_header + SQL
+
+ return ajax_response(response=SQL)
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, tid, exid):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Exclusion constraint ID
+
+ Returns the statistics for a particular object if cid is specified
+ """
+
+ # Check if pgstattuple extension is already created?
+ # if created then only add extended stats
+ status, is_pgstattuple = self.conn.execute_scalar("""
+ SELECT (pg_catalog.count(extname) > 0) AS is_pgstattuple
+ FROM pg_catalog.pg_extension
+ WHERE extname='pgstattuple'
+ """)
+ if not status:
+ return internal_server_error(errormsg=is_pgstattuple)
+
+ if is_pgstattuple:
+ # Fetch index details only if extended stats available
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did, tid=tid, conn=self.conn, cid=exid)
+ status, result = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=result)
+ if len(result['rows']) == 0:
+ return gone(
+ gettext("Could not find the exclusion constraint."))
+
+ data = result['rows'][0]
+ name = data['name']
+ else:
+ name = None
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'stats.sql']),
+ conn=self.conn, schema=self.schema,
+ name=name, exid=exid, is_pgstattuple=is_pgstattuple
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, exid):
+ """
+ This function get the dependents and return ajax response
+ for the constraint node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, exid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, exid):
+ """
+ This function get the dependencies and return ajax response
+ for the constraint node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ exid: Exclusion constraint ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, exid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+
+constraint = ConstraintRegistry(
+ 'exclusion_constraint', ExclusionConstraintModule, ExclusionConstraintView
+)
+ExclusionConstraintView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/img/exclusion_constraint.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/img/exclusion_constraint.svg
new file mode 100644
index 0000000000000000000000000000000000000000..421f851899c097bb84594aaa6fb71ca7891ae58a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/img/exclusion_constraint.svg
@@ -0,0 +1 @@
+exclusion_constraint
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js
new file mode 100644
index 0000000000000000000000000000000000000000..487d0ae7dc064a6b717cd5aa5a3cf7052ed43879
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.js
@@ -0,0 +1,97 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeExclusionConstraintSchema } from './exclusion_constraint.ui';
+import _ from 'lodash';
+
+define('pgadmin.node.exclusion_constraint', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser
+) {
+ // Extend the browser's node class for exclusion constraint node
+ if (!pgBrowser.Nodes['exclusion_constraint']) {
+ pgAdmin.Browser.Nodes['exclusion_constraint'] = pgBrowser.Node.extend({
+ type: 'exclusion_constraint',
+ label: gettext('Exclusion constraint'),
+ collection_type: 'coll-constraints',
+ sqlAlterHelp: 'ddl-alter.html',
+ sqlCreateHelp: 'ddl-constraints.html',
+ dialogHelp: url_for('help.static', {'filename': 'exclusion_constraint_dialog.html'}),
+ hasSQL: true,
+ parent_type: ['table','partition'],
+ canDrop: true,
+ canDropCascade: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Index size')],
+ url_jump_after_node: 'schema',
+ width: pgBrowser.stdW.md + 'px',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_exclusion_constraint_on_coll', node: 'coll-constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Exclusion constraint...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ }]);
+ },
+ is_not_valid: function(node) {
+ return (node && !node.valid);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return getNodeExclusionConstraintSchema(treeNodeInfo, itemNodeData, pgAdmin.Browser);
+ },
+
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [],
+ immediate_parent_table_found = false,
+ is_immediate_parent_table_partitioned = false;
+ // To iterate over tree to check parent node
+ while (i) {
+ // If table is partitioned table then return false
+ if (!immediate_parent_table_found && (d._type == 'table' || d._type == 'partition')) {
+ immediate_parent_table_found = true;
+ if ('is_partitioned' in d && d.is_partitioned) {
+ is_immediate_parent_table_partitioned = true;
+ }
+ }
+
+ // If it is schema then allow user to create table
+ if (_.indexOf(['schema'], d._type) > -1)
+ {return !is_immediate_parent_table_partitioned;}
+ else if (_.indexOf(['foreign_table', 'coll-foreign_table'], d._type) > -1) {
+ return false;
+ }
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ if (_.indexOf(parents, 'catalog') > -1) {
+ return false;
+ } else {
+ return !is_immediate_parent_table_partitioned;
+ }
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['exclusion_constraint'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..c78268c9bb2aa3aaf9f57d95d4749b3ba4aee876
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/static/js/exclusion_constraint.ui.js
@@ -0,0 +1,443 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import { SCHEMA_STATE_ACTIONS } from '../../../../../../../../../../static/js/SchemaView';
+import DataGridViewWithHeaderForm from '../../../../../../../../../../static/js/helpers/DataGridViewWithHeaderForm';
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../../../static/js/node_ajax';
+import TableSchema from '../../../../static/js/table.ui';
+import pgAdmin from 'sources/pgadmin';
+
+function getData(data) {
+ let res = [];
+ if (data && _.isArray(data)) {
+ _.each(data, function(d) {
+ res.push({label: d[0], value: d[1]});
+ });
+ }
+ return res;
+}
+
+export function getNodeExclusionConstraintSchema(treeNodeInfo, itemNodeData, pgBrowser, noColumns=false) {
+ let tableNode = pgBrowser.Nodes['table'];
+ return new ExclusionConstraintSchema({
+ columns: noColumns ? [] : ()=>getNodeListByName('column', treeNodeInfo, itemNodeData, {includeItemKeys: ['datatype']}),
+ amname: ()=>getNodeAjaxOptions('get_access_methods', tableNode, treeNodeInfo, itemNodeData),
+ spcname: ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ }),
+ getOperClass: (urlParams)=>getNodeAjaxOptions('get_oper_class', tableNode, treeNodeInfo, itemNodeData, {urlParams: urlParams, useCache:false}, (data)=>{
+ return getData(data);
+ }),
+ getOperator: (urlParams)=>getNodeAjaxOptions('get_operator', tableNode, treeNodeInfo, itemNodeData, {urlParams: urlParams, useCache:false}, (data)=>{
+ return getData(data);
+ }),
+ }, treeNodeInfo);
+}
+
+class ExclusionColHeaderSchema extends BaseUISchema {
+ constructor(columns) {
+ super({
+ is_exp: undefined,
+ column: undefined,
+ expression: undefined,
+ });
+
+ this.columns = columns;
+ }
+
+ changeColumnOptions(columns) {
+ this.columns = columns;
+ }
+
+ addDisabled(state) {
+ return !(state.is_exp ? state.expression : state.column);
+ }
+
+ /* Data to ExclusionColumnSchema will added using the header form */
+ getNewData(data) {
+ const column = _.find(this.columnOptions, (col)=>col.value==data.column);
+ return this.exColumnSchema.getNewData({
+ is_exp: data.is_exp,
+ column: data.is_exp ? data.expression : data.column,
+ column_cid: data.is_exp ? null : column?.cid,
+ col_type: data.is_exp ? null : column?.datatype,
+ });
+ }
+
+ get baseFields() {
+ return [{
+ id: 'is_exp', label: gettext('Is expression'), type:'switch', editable: false,
+ },{
+ id: 'column', label: gettext('Column'), type: 'select', editable: false,
+ options: this.columns, deps: ['is_exp'],
+ optionsReloadBasis: this.columns?.map ? _.join(this.columns.map((c)=>c.label), ',') : null,
+ optionsLoaded: (res)=>this.columnOptions=res,
+ disabled: (state)=>state.is_exp,
+ },{
+ id: 'expression', label: gettext('Expression'), editable: false, deps: ['is_exp'],
+ type: 'text', disabled: (state)=>!state.is_exp,
+ }];
+ }
+}
+
+class ExclusionColumnSchema extends BaseUISchema {
+ constructor(getOperator) {
+ super({
+ column: undefined,
+ is_exp: false,
+ oper_class: undefined,
+ order: false,
+ nulls_order: false,
+ operator:undefined,
+ col_type:undefined,
+ is_sort_nulls_applicable: false,
+ });
+
+ this.operClassOptions = [];
+ this.operatorOptions = [];
+ this.getOperator = getOperator;
+ this.isNewExCons = true;
+ this.amname = null;
+ }
+
+ isEditable() {
+ if(!this.isNewExCons) {
+ return false;
+ } else if(this.amname === 'btree') {
+ return true;
+ }
+ return false;
+ }
+
+ setOperClassOptions(options) {
+ this.operClassOptions = options;
+ }
+
+ changeDefaults(data) {
+ this.defaultColVals = data;
+ }
+
+ getNewData(data) {
+ return {
+ ...super.getNewData(data),
+ ...this.defaultColVals,
+ };
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'is_exp', label: '', type:'', cell: '', editable: false, width: 20,
+ disableResizing: true,
+ controlProps: {
+ formatter: {
+ fromRaw: function (rawValue) {
+ return rawValue ? 'E' : 'C';
+ },
+ }
+ }, visible: false,
+ },{
+ id: 'column', label: gettext('Col/Exp'), type:'', editable: false,
+ cell:'', width: 125,
+ },{
+ id: 'oper_class', label: gettext('Operator class'), cell:'select',
+ options: this.operClassOptions,
+ width: 185,
+ editable: obj.isEditable,
+ controlProps: {
+ allowClear: true, placeholder: gettext('Select the operator class'),
+ },
+ },{
+ id: 'order', label: gettext('Order'), type: 'select', cell: 'select',
+ options: [
+ {label: 'ASC', value: true},
+ {label: 'DESC', value: false},
+ ],
+ editable: obj.isEditable, width: 110, disableResizing: true,
+ controlProps: {
+ allowClear: false,
+ },
+ },{
+ id: 'nulls_order', label: gettext('NULLs order'), type:'select', cell: 'select',
+ options: [
+ {label: 'FIRST', value: true},
+ {label: 'LAST', value: false},
+ ], controlProps: {allowClear: false},
+ editable: obj.isEditable, width: 110, disableResizing: true,
+ },{
+ id: 'operator', label: gettext('Operator'), type: 'select',
+ width: 95,
+ editable: function() {
+ return obj.isNewExCons;
+ },
+ cell: (state)=>{
+ return {
+ cell: 'select',
+ options: ()=>obj.getOperator({col_type: state.col_type}),
+ controlProps: {
+ allowClear: false,
+ },
+ };
+ },
+ }];
+ }
+}
+
+export default class ExclusionConstraintSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ is_sys_obj: undefined,
+ comment: undefined,
+ spcname: undefined,
+ amname: 'gist',
+ fillfactor: undefined,
+ condeferrable: undefined,
+ condeferred: undefined,
+ columns: [],
+ include: [],
+ });
+
+ this.nodeInfo = nodeInfo;
+ this.fieldOptions = fieldOptions;
+ this.exHeaderSchema = new ExclusionColHeaderSchema(fieldOptions.columns);
+ this.exColumnSchema = new ExclusionColumnSchema(fieldOptions.getOperator);
+ this.exHeaderSchema.exColumnSchema = this.exColumnSchema;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get inTable() {
+ return this.top && this.top instanceof TableSchema;
+ }
+
+ initialise(data) {
+ this.exColumnSchema.isNewExCons = this.isNew(data);
+ this.amname = data.amname;
+ if(data.amname === 'btree') {
+ this.exColumnSchema.setOperClassOptions(this.fieldOptions.getOperClass({indextype: data.amname}));
+ }
+ }
+
+ changeColumnOptions(columns) {
+ this.exHeaderSchema.changeColumnOptions(columns);
+ this.fieldOptions.columns = columns;
+ }
+
+ isReadonly(state) {
+ // If we are in table edit mode then
+ if(this.top) {
+ return !_.isUndefined(state.oid);
+ }
+ return !this.isNew(state);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text', cell: 'text',
+ mode: ['properties', 'create', 'edit'], editable:true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'is_sys_obj', label: gettext('System exclusion constraint?'),
+ type: 'switch', mode: ['properties'],
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'text',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ deps:['name'], disabled:function(state) {
+ return isEmptyString(state.name);
+ }, depChange: (state)=>{
+ if(isEmptyString(state.name)) {
+ return {comment: ''};
+ }
+ }
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ type: 'select', group: gettext('Definition'),
+ controlProps: {allowClear:false}, options: this.fieldOptions.spcname,
+ },{
+ id: 'amname', label: gettext('Access method'),
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.amname,
+ deferredDepChange: (state, source, topState, actionObj)=>{
+ return new Promise((resolve)=>{
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Change access method?'),
+ gettext('Changing access method will clear columns collection'),
+ function () {
+ if(state.amname == 'btree' || isEmptyString(state.amname)) {
+ let indextype = 'btree';
+ obj.exColumnSchema.setOperClassOptions(obj.fieldOptions.getOperClass({indextype:indextype}));
+ obj.exColumnSchema.changeDefaults({
+ order: true,
+ nulls_order: true,
+ is_sort_nulls_applicable: true,
+ });
+ } else {
+ obj.exColumnSchema.setOperClassOptions([]);
+ obj.exColumnSchema.changeDefaults({
+ order: false,
+ nulls_order: false,
+ is_sort_nulls_applicable: false,
+ });
+ }
+ obj.exColumnSchema.amname = state.amname;
+ resolve(()=>({
+ columns: [],
+ }));
+ },
+ function() {
+ resolve(()=>{
+ return {
+ amname: actionObj.oldState.amname,
+ };
+ });
+ }
+ );
+ });
+ },
+ controlProps: {allowClear:true},
+ readonly: obj.isReadonly,
+ },{
+ id: 'fillfactor', label: gettext('Fill factor'),
+ type: 'int', group: gettext('Definition'), allowNull: true,
+ },{
+ id: 'condeferrable', label: gettext('Deferrable?'),
+ type: 'switch', group: gettext('Definition'),
+ readonly: obj.isReadonly,
+ },{
+ id: 'condeferred', label: gettext('Deferred?'),
+ type: 'switch', group: gettext('Definition'),
+ deps: ['condeferrable'],
+ disabled: function(state) {
+ // Disable if condeferred is false or unselected.
+ return !state.condeferrable;
+ },
+ readonly: obj.isReadonly,
+ depChange: (state)=>{
+ if(!state.condeferrable) {
+ return {condeferred: false};
+ }
+ }
+ },{
+ id: 'indconstraint', label: gettext('Constraint'), cell: 'text',
+ type: 'multiline', mode: ['create', 'edit', 'properties'], editable: false,
+ group: gettext('Definition'), readonly: obj.isReadonly,
+ },{
+ id: 'columns', label: gettext('Columns/Expressions'),
+ group: gettext('Columns'), type: 'collection',
+ mode: ['create', 'edit', 'properties'],
+ editable: false, schema: this.exColumnSchema,
+ headerSchema: this.exHeaderSchema, headerVisible: (state)=>obj.isNew(state),
+ CustomControl: DataGridViewWithHeaderForm,
+ uniqueCol: ['column'],
+ canAdd: false, canDelete: function(state) {
+ // We can't update columns of existing
+ return obj.isNew(state);
+ },
+ readonly: obj.isReadonly, cell: ()=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: (rawValue)=>{
+ return _.map(rawValue || [], 'column').join(', ');
+ },
+ }
+ },
+ width: 245,
+ }),
+ deps: ()=>{
+ let ret = [];
+ if(obj.inTable) {
+ ret.push(['columns']);
+ }
+ return ret;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ /* If in table, sync up value with columns in table */
+ if(obj.inTable && !state) {
+ /* the constraint is removed by some other dep, this can be a no-op */
+ return;
+ }
+
+ let currColumns = state.columns || [];
+ if(obj.inTable && source[0] == 'columns') {
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.DELETE_ROW) {
+ let column = _.get(actionObj.oldState, actionObj.path.concat(actionObj.value));
+ currColumns = _.filter(currColumns, (cc)=>cc.column_cid != column.cid);
+ } else if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE) {
+ let tabColPath = _.slice(actionObj.path, 0, -1);
+ let column = _.get(topState, tabColPath);
+ let idx = _.findIndex(currColumns, (cc)=>cc.column_cid == column.cid);
+ if(idx > -1) {
+ currColumns[idx].column = column.name;
+ }
+ }
+ }
+ return {columns: currColumns};
+ },
+ },
+ {
+ id: 'include', label: gettext('Include columns'), group: gettext('Columns'),
+ type: ()=>({
+ type: 'select',
+ options: this.fieldOptions.columns,
+ optionsReloadBasis: this.fieldOptions.columns?.map ? _.join(this.fieldOptions.columns.map((c)=>c.label), ',') : null,
+ controlProps: {
+ multiple: true,
+ },
+ }),
+ editable: false,
+ canDelete: true, canAdd: true,
+ mode: ['properties', 'create', 'edit'], min_version: 110000,
+ deps: ['index'],
+ readonly: function() {
+ if(!obj.isNew()) {
+ return true;
+ }
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {include: []};
+ }
+ }
+ }];
+ }
+
+ validate(state, setError) {
+ if ((_.isUndefined(state.columns) || _.isNull(state.columns) || state.columns.length < 1)) {
+ setError('columns', gettext('Please specify columns for exclusion constraint.'));
+ return true;
+ }
+
+ if (this.isNew(state)){
+ if (state.autoindex && isEmptyString(state.coveringindex)) {
+ setError('coveringindex', gettext('Please specify covering index name.'));
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cde3adbb717d699e55b99c206319586694cfd0b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/exclusion_constraint/utils.py
@@ -0,0 +1,314 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Exclusion Constraint. """
+
+from flask import render_template
+from flask_babel import gettext as _
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'exclusion_constraint/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+def _get_columns(res):
+ """
+ Get columns form response and return in required format.
+ :param res: response form constraints.
+ :return: column list.
+ """
+ columns = []
+ for row in res['rows']:
+ if row['options'] & 1:
+ order = False
+ nulls_order = True if (row['options'] & 2) else False
+ else:
+ order = True
+ nulls_order = True if (row['options'] & 2) else False
+
+ columns.append({"column": row['coldef'].strip('"'),
+ "oper_class": row['opcname'],
+ "order": order,
+ "nulls_order": nulls_order,
+ "operator": row['oprname'],
+ "col_type": row['datatype'],
+ "is_exp": row['is_exp']
+ })
+ return columns
+
+
+@get_template_path
+def get_exclusion_constraints(conn, did, tid, exid=None, template_path=None):
+ """
+ This function is used to fetch information of the
+ exclusion constraint(s) for the given table.
+ :param conn: Connection Object
+ :param did: Database ID
+ :param tid: Table ID
+ :param exid: Exclusion Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, cid=exid)
+
+ status, result = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=result)
+
+ for ex in result['rows']:
+ sql = render_template("/".join([template_path,
+ 'get_constraint_cols.sql']),
+ cid=ex['oid'], colcnt=ex['col_count'])
+
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=res)
+
+ columns = _get_columns(res)
+
+ ex['columns'] = columns
+
+ # INCLUDE clause in index is supported from PG-11+
+ if conn.manager.version >= 110000:
+ sql = render_template("/".join([template_path,
+ 'get_constraint_include.sql']),
+ cid=ex['oid'])
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=res)
+
+ ex['include'] = [col['colname'] for col in res['rows']]
+
+ if ex.get('amname', '') == "":
+ ex['amname'] = 'btree'
+
+ return True, result['rows']
+
+
+def _get_delete_constraint(data, constraint, sql, template_path, conn):
+ """
+ Check for delete constraints and return sql for it.
+ :param data: Data req.
+ :param constraint: Constraint list for check.
+ :param sql: sql list to append delete constraint sql.
+ :param template_path: Template path to fetch sql for delete constraint.
+ :param conn: Connection.
+ """
+ if 'deleted' in constraint:
+ for c in constraint['deleted']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ # Sql for drop
+ sql.append(
+ render_template("/".join(
+ [template_path, 'delete.sql']),
+ data=c, conn=conn).strip("\n")
+ )
+
+
+@get_template_path
+def get_exclusion_constraint_sql(conn, did, tid, data, template_path=None):
+ """
+ This function will return sql for exclusion constraints.
+ :param conn: Connection Object
+ :param did: Database ID
+ :param tid: Table ID
+ :param data: Data
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = []
+ # Check if constraint is in data
+ # If yes then we need to check for add/change/delete
+ if 'exclude_constraint' in data:
+ constraint = data['exclude_constraint']
+ # If constraint(s) is/are deleted
+ _get_delete_constraint(data, constraint, sql, template_path, conn)
+
+ if 'changed' in constraint:
+ for c in constraint['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ modified_sql, _ = get_sql(conn, c, did, tid, c['oid'])
+ sql.append(modified_sql.strip('\n'))
+
+ if 'added' in constraint:
+ for c in constraint['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ add_sql, _ = get_sql(conn, c, did, tid)
+ sql.append(add_sql.strip("\n"))
+
+ if len(sql) > 0:
+ # Join all the sql(s) as single string
+ return '\n\n'.join(sql)
+ else:
+ return None
+
+
+@get_template_path
+def get_sql(conn, data, did, tid, exid=None, template_path=None):
+ """
+ This function will generate sql from model data.
+ :param conn: Connection Object
+ :param data: data
+ :param did: Database ID
+ :param tid: Table id
+ :param exid: Exclusion Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+ name = data['name'] if 'name' in data else None
+ if exid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, cid=exid)
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(
+ _('Could not find the exclusion constraint in the table.'))
+
+ old_data = res['rows'][0]
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ sql = render_template("/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn)
+ else:
+ if 'columns' not in data or \
+ (isinstance(data['columns'], list) and
+ len(data['columns']) < 1):
+ return _('-- definition incomplete'), name
+
+ sql = render_template("/".join([template_path, 'create.sql']),
+ data=data, conn=conn)
+
+ return sql, name
+
+
+@get_template_path
+def get_access_methods(conn, template_path=None):
+ """
+ This function is used to get the access methods.
+
+ :param conn:
+ :param template_path:
+ :return:
+ """
+ res = []
+ sql = render_template("/".join([template_path, 'get_access_methods.sql']))
+
+ status, rest = conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rest)
+
+ for row in rest['rows']:
+ res.append(
+ {'label': row['amname'], 'value': row['amname']}
+ )
+
+ return res
+
+
+@get_template_path
+def get_oper_class(conn, indextype, template_path=None):
+ """
+ This function is used to get the operator class methods.
+
+ :param conn:
+ :param indextype:
+ :param template_path:
+ :return:
+ """
+ SQL = render_template("/".join([template_path, 'get_oper_class.sql']),
+ indextype=indextype, conn=conn)
+
+ status, res = conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ result = []
+ for row in res['rows']:
+ result.append([row['opcname'], row['opcname']])
+
+ return result
+
+
+@get_template_path
+def get_operator(conn, coltype, show_sysobj, template_path=None):
+ """
+ This function is used to get the operator.
+
+ :param conn:
+ :param coltype:
+ :param show_sysobj:
+ :param template_path:
+ :return:
+ """
+ SQL = render_template("/".join([template_path, 'get_operator.sql']),
+ type=coltype, show_sysobj=show_sysobj, conn=conn)
+
+ status, res = conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ result = []
+ for row in res['rows']:
+ result.append([row['oprname'], row['oprname']])
+
+ return result
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0d8cb2037c9623fa37aeeb2c07c80d55bedc2e2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/__init__.py
@@ -0,0 +1,1024 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Foreign key constraint Node"""
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.type import ConstraintRegistry, ConstraintTypeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.foreign_key import utils as fkey_utils
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+
+FOREIGN_KEY_NOT_FOUND = gettext("Could not find the foreign key.")
+
+
+class ForeignKeyConstraintModule(ConstraintTypeModule):
+ """
+ class ForeignKeyConstraintModule(CollectionNodeModule)
+
+ A module class for Foreign key constraint node derived from
+ ConstraintTypeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the ForeignKeyConstraintModule and
+ it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for language, when any of the database node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'foreign_key'
+ _COLLECTION_LABEL = gettext("Foreign Keys")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the ForeignKeyConstraintModule and
+ it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+
+ Returns:
+
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, tid):
+ """
+ Generate the collection node
+ """
+ pass
+
+ @property
+ def node_inode(self):
+ """
+ Override this property to make the node a leaf node.
+
+ Returns: False as this is the leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for foreign_key, when any of the table node is
+ initialized.
+
+ Returns: node type of the server module.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ self._COLLECTION_CSS,
+ node_type=self.node_type,
+ ),
+ render_template(
+ "foreign_key/css/foreign_key.css",
+ node_type=self.node_type,
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+
+blueprint = ForeignKeyConstraintModule(__name__)
+
+
+class ForeignKeyConstraintView(PGChildNodeView):
+ """
+ class ForeignKeyConstraintView(PGChildNodeView)
+
+ A view class for Foreign key constraint node derived from
+ PGChildNodeView. This class is responsible for all the stuff related
+ to view like creating, updating Foreign key constraint
+ node, showing properties, showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the ForeignKeyConstraintView and
+ it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function returns foreign key constraint nodes within that
+ collection as http response.
+
+ * get_list()
+ - This function is used to list all the language nodes within that
+ collection and return list of foreign key constraint nodes.
+
+ * nodes()
+ - This function returns child node within that collection.
+ Here return all foreign key constraint node as http response.
+
+ * get_nodes()
+ - returns all foreign key constraint nodes' list.
+
+ * properties()
+ - This function will show the properties of the selected foreign key.
+
+ * update()
+ - This function will update the data for the selected foreign key.
+
+ * msql()
+ - This function is used to return modified SQL for the selected
+ foreign key.
+
+ * sql():
+ - This function will generate sql to show it in sql pane for the
+ selected foreign key.
+
+ * get_indices():
+ - This function returns indices for current table.
+
+ """
+
+ node_type = 'foreign_key'
+ FOREIGN_KEY_PATH = 'foreign_key/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [{'type': 'int', 'id': 'fkid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'indices': [{}, {'get': 'get_indices'}],
+ 'validate': [{'get': 'validate_foreign_key'}],
+ 'get_coveringindex': [{}, {'get': 'get_coveringindex'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.template_path = self.FOREIGN_KEY_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = fkey_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+ return wrap
+
+ def end_transaction(self):
+ SQL = render_template(
+ "/".join([self.template_path, 'end.sql']))
+ # End transaction if any.
+ self.conn.execute_scalar(SQL)
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function is used to list all the foreign key
+ nodes within that collection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ status, res = fkey_utils.get_foreign_keys(self.conn, tid, fkid)
+ if not status:
+ return res
+
+ if len(res) == 0:
+ return gone(gettext(FOREIGN_KEY_NOT_FOUND))
+
+ result = res
+ if fkid:
+ result = res[0]
+ result['is_sys_obj'] = (
+ result['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return ajax_response(
+ response=result,
+ status=200
+ )
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function returns all foreign keys
+ nodes within that collection as a http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ try:
+ res = self.get_node_list(gid, sid, did, scid, tid)
+ if fkid is not None:
+ for foreign_key in res:
+ if foreign_key['oid'] == fkid:
+ return ajax_response(
+ response=foreign_key,
+ status=200
+ )
+ else:
+ return ajax_response(
+ response=foreign_key,
+ status=200
+ )
+ return gone(gettext(FOREIGN_KEY_NOT_FOUND))
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_node_list(self, gid, sid, did, scid, tid):
+ """
+ This function returns all foreign keys
+ nodes within that collection as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.template_path = self.FOREIGN_KEY_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = fkey_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid)
+ _, res = self.conn.execute_dict(SQL)
+
+ for row in res['rows']:
+ row['_type'] = self.node_type
+
+ return res['rows']
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function returns all foreign key nodes as a
+ http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]), tid=tid
+ )
+ _, rset = self.conn.execute_2darray(SQL)
+
+ if len(rset['rows']) == 0:
+ return gone(gettext(FOREIGN_KEY_NOT_FOUND))
+
+ if rset['rows'][0]["convalidated"]:
+ icon = "icon-foreign_key_no_validate"
+ valid = False
+ else:
+ icon = "icon-foreign_key"
+ valid = True
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon=icon,
+ valid=valid
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function returns all foreign key nodes as a
+ http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+ res = []
+ for row in rset['rows']:
+ if row["convalidated"]:
+ icon = "icon-foreign_key_no_validate"
+ valid = False
+ else:
+ icon = "icon-foreign_key"
+ valid = True
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=icon,
+ valid=valid,
+ description=row['comment']
+ ))
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_nodes(self, gid, sid, did, scid, tid):
+ """
+ This function returns all foreign key nodes as a list.
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.template_path = self.FOREIGN_KEY_PATH.format(self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = fkey_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ if row["convalidated"]:
+ icon = "icon-foreign_key_no_validate"
+ valid = False
+ else:
+ icon = "icon-foreign_key"
+ valid = True
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=icon,
+ valid=valid,
+ description=row['comment']
+ ))
+ return res
+
+ @staticmethod
+ def _get_reqes_data():
+ """
+ Get data from request.
+ return: Data.
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ return data
+
+ @staticmethod
+ def _check_for_req_data(data):
+ required_args = ['columns']
+ for arg in required_args:
+ if arg not in data or \
+ (isinstance(data[arg], list) and len(data[arg]) < 1):
+ return True, make_json_response(
+ status=400,
+ success=0,
+ errormsg=gettext(
+ "Could not find required parameter ({})."
+ ).format(arg)
+ )
+
+ return False, ''
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function will create a foreign key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ data = ForeignKeyConstraintView._get_reqes_data()
+
+ is_arg_error, errmsg = ForeignKeyConstraintView._check_for_req_data(
+ data)
+ if is_arg_error:
+ return errmsg
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ # Get the parent schema and table.
+ schema, table = fkey_utils.get_parent(
+ self.conn, data['columns'][0]['references'])
+ data['remote_schema'] = schema
+ data['remote_table'] = table
+
+ if 'name' not in data or data['name'] == "":
+ sql = render_template(
+ "/".join([self.template_path, 'begin.sql']))
+ # Start transaction.
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ # The below SQL will execute CREATE DDL only
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(sql)
+
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+ elif 'name' not in data or data['name'] == "":
+ sql = render_template(
+ "/".join([self.template_path,
+ 'get_oid_with_transaction.sql']),
+ tid=tid)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ self.end_transaction()
+
+ data['name'] = res['rows'][0]['name']
+
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ name=data['name'], conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ is_error, errmsg, icon, valid = self._create_index(data, res)
+ if is_error:
+ return errmsg
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['rows'][0]['oid'],
+ tid,
+ data['name'],
+ valid=valid,
+ icon=icon,
+ **other_node_info
+ )
+ )
+
+ except Exception as e:
+ self.end_transaction()
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=e
+ )
+
+ def _create_index(self, data, res):
+ """
+ Create index for foreign key.
+ data: Data.
+ res: Response form transaction.
+ Return: if error in create index return error, else return icon
+ and valid status
+ """
+ if res['rows'][0]["convalidated"]:
+ icon = "icon-foreign_key_no_validate"
+ valid = False
+ else:
+ icon = "icon-foreign_key"
+ valid = True
+
+ if data['autoindex']:
+ sql = render_template(
+ "/".join([self.template_path, 'create_index.sql']),
+ data=data, conn=self.conn)
+ sql = sql.strip('\n').strip(' ')
+
+ if sql != '':
+ status, idx_res = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return True, internal_server_error(
+ errormsg=idx_res), icon, valid
+
+ return False, '', icon, valid
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function will update the data for the selected
+ foreign key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql, name = fkey_utils.get_sql(self.conn, data, tid, fkid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid,
+ name=data['name'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if res['rows'][0]["convalidated"]:
+ icon = "icon-foreign_key_no_validate"
+ valid = False
+ else:
+ icon = "icon-foreign_key"
+ valid = True
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ fkid,
+ tid,
+ name,
+ icon=icon,
+ valid=valid,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function will delete an existing foreign key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ if fkid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [fkid]}
+
+ # Below code will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+ try:
+ for fkid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']), fkid=fkid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified foreign key could not be found.\n'
+ )
+ )
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ sql = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data, cascade=cascade)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Foreign key dropped.")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function returns modified SQL for the selected
+ foreign key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ sql, _ = fkey_utils.get_sql(self.conn, data, tid, fkid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function generates sql to show in the sql pane for the selected
+ foreign key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ fkid: Foreign key constraint ID
+
+ Returns:
+
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, conn=self.conn, cid=fkid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(gettext(FOREIGN_KEY_NOT_FOUND))
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ sql = render_template("/".join([self.template_path,
+ 'get_constraint_cols.sql']),
+ tid=tid,
+ keys=zip(data['confkey'], data['conkey']),
+ confrelid=data['confrelid'])
+
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ columns = []
+ for row in res['rows']:
+ columns.append({"local_column": row['conattname'],
+ "references": data['confrelid'],
+ "referenced": row['confattname']})
+
+ data['columns'] = columns
+
+ # Get the parent schema and table.
+ schema, table = fkey_utils.get_parent(self.conn,
+ data['columns'][0]['references'])
+ data['remote_schema'] = schema
+ data['remote_table'] = table
+
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]), data=data,
+ conn=self.conn)
+
+ sql_header = "-- Constraint: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data)
+ sql_header += "\n"
+
+ SQL = sql_header + SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function gets the dependents and returns an ajax response
+ for the event trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ etid: Event trigger ID
+ """
+ dependents_result = self.get_dependents(self.conn, fkid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, fkid=None):
+ """
+ This function gets the dependencies and returns an ajax response
+ for the event trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ etid: Event trigger ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, fkid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def validate_foreign_key(self, gid, sid, did, scid, tid, fkid):
+ """
+
+ Args:
+ gid:
+ sid:
+ did:
+ scid:
+ tid:
+ fkid:
+
+ Returns:
+
+ """
+ data = {}
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']), fkid=fkid)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ data['name'] = res
+ sql = render_template(
+ "/".join([self.template_path, 'validate.sql']), data=data)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Foreign key updated."),
+ data={
+ 'id': fkid,
+ 'tid': tid,
+ 'scid': scid,
+ 'did': did
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_coveringindex(self, gid, sid, did, scid, tid=None):
+ """
+
+ Args:
+ gid:
+ sid:
+ did:
+ scid:
+ tid:
+
+ Returns:
+
+ """
+ data = request.args if request.args else None
+ index = None
+ try:
+ if data and 'cols' in data:
+ cols = set(json.loads(data['cols']))
+ index = fkey_utils.search_coveringindex(self.conn, tid, cols)
+
+ return make_json_response(
+ data=index,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+
+constraint = ConstraintRegistry(
+ 'foreign_key', ForeignKeyConstraintModule, ForeignKeyConstraintView
+)
+ForeignKeyConstraintView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key.svg
new file mode 100644
index 0000000000000000000000000000000000000000..23d7d1ee8e0c7b9ca6d5808232f921c3e59a88a9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key.svg
@@ -0,0 +1 @@
+foreign_key
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key_no_validate.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key_no_validate.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5637aa80fff46ef8bb738d3561cecd5be49e404d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/img/foreign_key_no_validate.svg
@@ -0,0 +1 @@
+foreign_key_no_validate
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
new file mode 100644
index 0000000000000000000000000000000000000000..729b307de3a9c91643eec7f2b52b2db6a5053ed2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.js
@@ -0,0 +1,133 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeForeignKeySchema } from './foreign_key.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.foreign_key', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser
+) {
+ // Extend the browser's node class for foreign key node
+ if (!pgBrowser.Nodes['foreign_key']) {
+ pgAdmin.Browser.Nodes['foreign_key'] = pgBrowser.Node.extend({
+ type: 'foreign_key',
+ label: gettext('Foreign key'),
+ collection_type: 'coll-constraints',
+ sqlAlterHelp: 'ddl-alter.html',
+ sqlCreateHelp: 'ddl-constraints.html',
+ dialogHelp: url_for('help.static', {'filename': 'foreign_key_dialog.html'}),
+ hasSQL: true,
+ parent_type: ['table','partition'],
+ canDrop: true,
+ canDropCascade: true,
+ hasDepends: true,
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_foreign_key_on_coll', node: 'coll-constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Foreign key...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'validate_foreign_key', node: 'foreign_key', module: this,
+ applies: ['object', 'context'], callback: 'validate_foreign_key',
+ category: 'validate', priority: 4, label: gettext('Validate foreign key'),
+ enable : 'is_not_valid',
+ },
+ ]);
+ },
+ is_not_valid: function(node) {
+ return (node && !node.valid);
+ },
+ callbacks: {
+ validate_foreign_key: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (d) {
+ let data = d;
+ getApiInstance().get(obj.generate_url(i, 'validate', d, true))
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.valid = true;
+ data.icon = 'icon-foreign_key';
+ t.addIcon(i, {icon: data.icon});
+ setTimeout(function() {t.deselect(i);}, 10);
+ setTimeout(function() {t.select(i);}, 100);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.unload(i);
+ });
+ }
+ return false;
+ },
+ },
+ getSchema: (treeNodeInfo, itemNodeData)=>{
+ return getNodeForeignKeySchema(treeNodeInfo, itemNodeData, pgAdmin.Browser);
+ },
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [],
+ immediate_parent_table_found = false,
+ is_immediate_parent_table_partitioned = false,
+ s_version = t.getTreeNodeHierarchy(i).server.version;
+
+ // To iterate over tree to check parent node
+ while (i) {
+ // If table is partitioned table then return false
+ if (!immediate_parent_table_found && (d._type == 'table' || d._type == 'partition')) {
+ immediate_parent_table_found = true;
+ if ('is_partitioned' in d && d.is_partitioned && s_version < 110000) {
+ is_immediate_parent_table_partitioned = true;
+ }
+ }
+
+ // If it is schema then allow user to c reate table
+ if (_.indexOf(['schema'], d._type) > -1){
+ return !is_immediate_parent_table_partitioned;
+ }else if (_.indexOf(['foreign_table', 'coll-foreign_table'], d._type) > -1) {
+ return false;
+ }
+
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ if (_.indexOf(parents, 'catalog') > -1) {
+ return false;
+ } else {
+ return !is_immediate_parent_table_partitioned;
+ }
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['foreign_key'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..22eead1669abedc4a993ada4e1bbf4d6828824c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/static/js/foreign_key.ui.js
@@ -0,0 +1,409 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import { SCHEMA_STATE_ACTIONS } from '../../../../../../../../../../static/js/SchemaView';
+import DataGridViewWithHeaderForm from '../../../../../../../../../../static/js/helpers/DataGridViewWithHeaderForm';
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../../../static/js/node_ajax';
+import TableSchema from '../../../../static/js/table.ui';
+
+export function getNodeForeignKeySchema(treeNodeInfo, itemNodeData, pgBrowser, noColumns=false, initData={}) {
+ return new ForeignKeySchema({
+ local_column: noColumns ? [] : ()=>getNodeListByName('column', treeNodeInfo, itemNodeData),
+ references: ()=>getNodeAjaxOptions('all_tables', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData, {cacheLevel: 'server'}, (rows)=>{
+ return rows.map((r)=>({
+ 'value': r.value,
+ 'image': 'icon-table',
+ 'label': r.label,
+ oid: r.oid,
+ }));
+ }),
+ },
+ treeNodeInfo,
+ (params)=>{
+ return getNodeAjaxOptions('get_columns', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData, {urlParams: params, useCache:false}, (rows)=>{
+ return rows.map((r)=>({
+ 'value': r.name,
+ 'image': 'icon-column',
+ 'label': r.name,
+ }));
+ });
+ }, initData);
+}
+
+class ForeignKeyHeaderSchema extends BaseUISchema {
+ constructor(fieldOptions, getColumns) {
+ super({
+ local_column: undefined,
+ references: undefined,
+ referenced: undefined,
+ _disable_references: false,
+ });
+
+ this.fieldOptions = fieldOptions;
+ this.getColumns = getColumns;
+ }
+
+ changeColumnOptions(columns) {
+ this.fieldOptions.local_column = columns;
+ }
+
+ addDisabled(state) {
+ return !(state.local_column && (state.references || this.origData.references) && state.referenced);
+ }
+
+ /* Data to ForeignKeyColumnSchema will added using the header form */
+ getNewData(data) {
+ let references_table_name = _.find(this.refTables, (t)=>t.value==data.references || t.value == this.origData.references)?.label;
+ return {
+ local_column: data.local_column,
+ local_column_cid: _.find(this.fieldOptions.local_column, (c)=>c.value == data.local_column)?.cid,
+ referenced: data.referenced,
+ references: data.references,
+ references_table_name: references_table_name,
+ };
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'local_column', label: gettext('Local column'), type:'select', editable: false,
+ options: this.fieldOptions.local_column,
+ optionsReloadBasis: this.fieldOptions.local_column?.map ? _.join(this.fieldOptions.local_column.map((c)=>c.label), ',') : null,
+ },{
+ id: 'references', label: gettext('References'), type: 'select', editable: false,
+ options: this.fieldOptions.references,
+ optionsReloadBasis: this.fieldOptions.references?.map ? _.join(this.fieldOptions.references.map((c)=>c.label), ',') : null,
+ optionsLoaded: (rows)=>obj.refTables=rows,
+ disabled: (state) => {
+ return state._disable_references;
+ }
+ },{
+ id: 'referenced', label: gettext('Referencing'), editable: false, deps: ['references'],
+ type: (state)=>{
+ return {
+ type: 'select',
+ options: state.references ? ()=>this.getColumns({tid: state.references}) : [],
+ optionsReloadBasis: state.references,
+ };
+ },
+ },
+ {
+ id: '_disable_references', label: '', type: 'switch', visible: false
+ }];
+ }
+}
+
+export class ForeignKeyColumnSchema extends BaseUISchema {
+ constructor() {
+ super({
+ local_column: undefined,
+ referenced: undefined,
+ references: undefined,
+ references_table_name: undefined,
+ });
+ }
+
+ get baseFields() {
+ return [{
+ id: 'local_column', label: gettext('Local'), type:'text', editable: false,
+ cell:'',
+ },{
+ id: 'referenced', label: gettext('Referenced'), type: 'text', editable: false,
+ cell:'',
+ },{
+ id: 'references_table_name', label: gettext('Referenced Table'), type: 'text', editable: false,
+ cell:'',
+ }];
+ }
+}
+
+export default class ForeignKeySchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, getColumns=()=>[], initValues={}, inErd=false) {
+ super({
+ name: undefined,
+ reftab: undefined,
+ oid: undefined,
+ is_sys_obj: undefined,
+ comment: undefined,
+ condeferrable: undefined,
+ condeferred: undefined,
+ confmatchtype: false,
+ convalidated: undefined,
+ columns: undefined,
+ confupdtype: 'a',
+ confdeltype: 'a',
+ autoindex: true,
+ coveringindex: undefined,
+ hasindex:undefined,
+ ...initValues,
+ });
+
+ this.nodeInfo = nodeInfo;
+
+ this.fkHeaderSchema = new ForeignKeyHeaderSchema(fieldOptions, getColumns);
+ this.fkHeaderSchema.fkObj = this;
+ this.fkColumnSchema = new ForeignKeyColumnSchema();
+ this.inErd = inErd;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get inTable() {
+ return this.top && this.top instanceof TableSchema;
+ }
+
+ changeColumnOptions(columns) {
+ this.fkHeaderSchema.changeColumnOptions(columns);
+ }
+
+ isReadonly(state) {
+ // If we are in table edit mode then
+ if(this.top) {
+ return !_.isUndefined(state.oid);
+ }
+ return !this.isNew(state);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text', cell: 'text',
+ mode: ['properties', 'create', 'edit'], editable:true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'is_sys_obj', label: gettext('System foreign key?'),
+ type: 'switch', mode: ['properties'],
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'text',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ deps:['name'], disabled:function(state) {
+ return isEmptyString(state.name);
+ }, depChange: (state)=>{
+ if(isEmptyString(state.name)) {
+ return {comment: ''};
+ }
+ }
+ },{
+ id: 'condeferrable', label: gettext('Deferrable?'),
+ type: 'switch', group: gettext('Definition'),
+ readonly: obj.isReadonly,
+ },{
+ id: 'condeferred', label: gettext('Deferred?'),
+ type: 'switch', group: gettext('Definition'),
+ deps: ['condeferrable'],
+ disabled: function(state) {
+ // Disable if condeferred is false or unselected.
+ return !state.condeferrable;
+ },
+ readonly: obj.isReadonly,
+ depChange: (state)=>{
+ if(!state.condeferrable) {
+ return {condeferred: false};
+ }
+ }
+ },{
+ id: 'confmatchtype', label: gettext('Match type'),
+ type: 'toggle', group: gettext('Definition'),
+ options: [
+ {label: 'FULL', value: true},
+ {label: 'SIMPLE', value: false},
+ ], readonly: obj.isReadonly,
+ },{
+ id: 'convalidated', label: gettext('Validated?'),
+ type: 'switch', group: gettext('Definition'),
+ readonly: (state)=>{
+ if(!obj.isNew(state)) {
+ let origData = {};
+ if(obj.inTable && obj.top) {
+ origData = _.find(obj.top.origData['foreign_key'], (r)=>r.cid == state.cid);
+ } else {
+ origData = obj.origData;
+ }
+ return origData.convalidated;
+ }
+ return false;
+ },
+ },{
+ id: 'autoindex', label: gettext('Auto FK index?'),
+ type: 'switch', group: gettext('Definition'),
+ deps: ['name', 'hasindex'],
+ readonly: (state)=>{
+ if(!obj.isNew(state)) {
+ return true;
+ }
+ // If we are in table edit mode then
+ return state.hasindex;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ if(!obj.isNew(state)) {
+ return {};
+ }
+ // If we are in table edit mode
+ if(obj.inTable && !this.inErd) {
+ if(obj.isNew(state) && obj.top.isNew()) {
+ return {autoindex: false, coveringindex: ''};
+ }
+ }
+
+ let oldindex;
+ if(obj.inTable) {
+ let oldFk = _.get(actionObj.oldState, _.slice(actionObj.path, 0, -1));
+ oldindex = 'fki_'+oldFk.name;
+ } else {
+ oldindex = 'fki_'+actionObj.oldState.name;
+ }
+ if(state.hasindex) {
+ return {};
+ } else if(!state.autoindex) {
+ return {coveringindex: ''};
+ } else if(state.autoindex && !isEmptyString(state.name) &&
+ (isEmptyString(state.coveringindex) || oldindex == state.coveringindex)){
+ return {coveringindex: 'fki_'+state.name};
+ }
+ },
+ },{
+ id: 'coveringindex', label: gettext('Covering index'), type: 'text',
+ mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
+ deps:['autoindex', 'hasindex'],
+ disabled: (state)=>{
+ return !state.autoindex && !state.hasindex;
+ },
+ readonly: this.isReadonly,
+ },{
+ id: 'references_table_name', label: gettext('Referenced Table'),
+ type: 'text', group: gettext('Columns'), editable: false, visible:false, deps: ['columns'],
+ cell: (state)=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: ()=>{
+ if(state.columns?.length > 0) {
+ return _.join(_.map(state.columns, 'references_table_name'), ',');
+ }
+ return '';
+ }
+ }
+ }
+ }),
+ },{
+ id: 'columns', label: gettext('Columns'),
+ group: gettext('Columns'), type: 'collection',
+ mode: ['create', 'edit', 'properties'],
+ editable: false, schema: this.fkColumnSchema,
+ headerSchema: this.fkHeaderSchema, headerVisible: (state)=>obj.isNew(state),
+ CustomControl: DataGridViewWithHeaderForm,
+ uniqueCol: ['local_column', 'references', 'referenced'],
+ canAdd: false, canDelete: function(state) {
+ // We can't update columns of existing foreign key.
+ return obj.isNew(state);
+ },
+ readonly: obj.isReadonly, cell: ()=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: (rawValue)=>{
+ let cols = [],
+ remoteCols = [];
+ if (rawValue?.length > 0) {
+ rawValue.forEach((col)=>{
+ cols.push(col.local_column);
+ remoteCols.push(col.referenced);
+ });
+ return '('+cols.join(', ')+') -> ('+ remoteCols.join(', ')+')';
+ }
+ return '';
+ },
+ }
+ },
+ }),
+ deps: ()=>{
+ let ret = [];
+ if(obj.inTable) {
+ ret.push(['columns']);
+ }
+ return ret;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ /* If in table, sync up value with columns in table */
+ if(obj.inTable && !state) {
+ /* the FK is removed by some other dep, this can be a no-op */
+ return;
+ }
+ let currColumns = state.columns || [];
+ if(obj.inTable && source[0] == 'columns') {
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.DELETE_ROW) {
+ let column = _.get(actionObj.oldState, actionObj.path.concat(actionObj.value));
+ currColumns = _.filter(currColumns, (cc)=>cc.local_column_cid != column.cid);
+ } else if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE) {
+ let tabColPath = _.slice(actionObj.path, 0, -1);
+ let column = _.get(actionObj.oldState, tabColPath);
+ let idx = _.findIndex(currColumns, (cc)=>cc.local_column_cid == column.cid);
+ if(idx > -1) {
+ currColumns[idx].local_column = _.get(topState, tabColPath).name;
+ }
+ }
+ }
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.ADD_ROW) {
+ obj.fkHeaderSchema.origData.references = null;
+ // Set references value.
+ obj.fkHeaderSchema.origData.references = obj.fkHeaderSchema.sessData.references;
+ obj.fkHeaderSchema.origData._disable_references = true;
+ }
+ return {columns: currColumns};
+ },
+ },{
+ id: 'confupdtype', label: gettext('On update'),
+ type:'select', group: gettext('Action'), mode: ['edit','create'],
+ controlProps:{allowClear: false},
+ options: [
+ {label: 'NO ACTION', value: 'a'},
+ {label: 'RESTRICT', value: 'r'},
+ {label: 'CASCADE', value: 'c'},
+ {label: 'SET NULL', value: 'n'},
+ {label: 'SET DEFAULT', value: 'd'},
+ ], readonly: obj.isReadonly,
+ },{
+ id: 'confdeltype', label: gettext('On delete'),
+ type:'select', group: gettext('Action'), mode: ['edit','create'],
+ select2:{allowClear: false},
+ options: [
+ {label: 'NO ACTION', value: 'a'},
+ {label: 'RESTRICT', value: 'r'},
+ {label: 'CASCADE', value: 'c'},
+ {label: 'SET NULL', value: 'n'},
+ {label: 'SET DEFAULT', value: 'd'},
+ ], readonly: obj.isReadonly,
+ }];
+ }
+
+ validate(state, setError) {
+ if ((_.isUndefined(state.columns) || _.isNull(state.columns) || state.columns.length < 1)) {
+ setError('columns', gettext('Please specify columns for Foreign key.'));
+ return true;
+ }
+
+ if (this.isNew(state)){
+ if (state.autoindex && isEmptyString(state.coveringindex)) {
+ setError('coveringindex', gettext('Please specify covering index name.'));
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/templates/foreign_key/css/foreign_key.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/templates/foreign_key/css/foreign_key.css
new file mode 100644
index 0000000000000000000000000000000000000000..35f6884d62bd2378aa004081f5997c0bf4b3e466
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/templates/foreign_key/css/foreign_key.css
@@ -0,0 +1,18 @@
+.icon-foreign_key {
+ background-image: url('{{ url_for('NODE-foreign_key.static', filename='img/foreign_key.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-foreign_key_no_validate {
+ background-image: url('{{ url_for('NODE-foreign_key.static', filename='img/foreign_key_no_validate.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ border-radius: 10px;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..892d58af4b24e3c616acab14aefe1ed90297c92c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/utils.py
@@ -0,0 +1,403 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Foreign Keys. """
+
+from flask import render_template
+from flask_babel import gettext as _
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+FKEY_PROPERTIES_SQL = 'properties.sql'
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'foreign_key/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_foreign_keys(conn, tid, fkid=None, template_path=None):
+ """
+ This function is used to fetch information of the
+ foreign key(s) for the given table.
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param fkid: Foreign Key ID
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = render_template("/".join(
+ [template_path, FKEY_PROPERTIES_SQL]), tid=tid, cid=fkid)
+
+ status, result = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=result)
+
+ for fk in result['rows']:
+ sql = render_template("/".join([template_path,
+ 'get_constraint_cols.sql']),
+ tid=tid,
+ keys=zip(fk['confkey'], fk['conkey']),
+ confrelid=fk['confrelid'])
+
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=res)
+
+ columns = []
+ cols = []
+ for row in res['rows']:
+ columns.append({"local_column": row['conattname'],
+ "references": fk['confrelid'],
+ "referenced": row['confattname'],
+ "references_table_name":
+ fk['refnsp'] + '.' + fk['reftab']})
+ cols.append(row['conattname'])
+
+ fk['columns'] = columns
+
+ if not fkid:
+ schema, table = get_parent(conn, fk['columns'][0]['references'])
+ fk['remote_schema'] = schema
+ fk['remote_table'] = table
+
+ coveringindex = search_coveringindex(conn, tid, cols)
+ fk['coveringindex'] = coveringindex
+ if coveringindex:
+ fk['autoindex'] = False
+ fk['hasindex'] = True
+ else:
+ fk['autoindex'] = True
+ fk['hasindex'] = False
+
+ return True, result['rows']
+
+
+@get_template_path
+def search_coveringindex(conn, tid, cols, template_path=None):
+ """
+ This function is used to search the covering index
+ :param conn: Connection Object
+ :param tid: Table id
+ :param cols: Columns
+ :param template_path: Template Path
+ :return:
+ """
+
+ cols = set(cols)
+ SQL = render_template("/".join([template_path,
+ 'get_constraints.sql']),
+ tid=tid)
+ status, constraints = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(constraints)
+
+ for constraint in constraints['rows']:
+ sql = render_template(
+ "/".join([template_path, 'get_cols.sql']),
+ cid=constraint['oid'],
+ colcnt=constraint['col_count'])
+ status, rest = conn.execute_dict(sql)
+
+ if not status:
+ raise ExecuteError(rest)
+
+ index_cols = set()
+ for r in rest['rows']:
+ index_cols.add(r['column'].strip('"'))
+
+ if len(cols - index_cols) == len(index_cols - cols) == 0:
+ return constraint["idxname"]
+
+ return None
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_delete_sql(conn, fk_data, template_path=None):
+ """
+ This function will generate sql from model data.
+ :param conn: Connection Object
+ :param data: data
+ :param template_path: Template Path
+ :return:
+ """
+ return render_template("/".join(
+ [template_path,
+ 'delete.sql']),
+ data=fk_data, conn=conn).strip('\n')
+
+
+def _get_sql_for_delete_fk_constraint(data, constraint, sql, template_path,
+ conn):
+ """
+ Get sql for delete foreign key constraints.
+ :param data:
+ :param constraint:
+ :param sql: sql for append
+ :param template_path: template path for sql.
+ :param conn:
+ :return:
+ """
+ if 'deleted' in constraint:
+ for c in constraint['deleted']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ # Sql for drop
+ sql.append(
+ render_template("/".join(
+ [template_path,
+ 'delete.sql']),
+ data=c, conn=conn).strip('\n')
+ )
+
+
+@get_template_path
+def get_foreign_key_sql(conn, tid, data, template_path=None):
+ """
+ This function will return sql for foreign keys.
+ :param conn: Connection Object
+ :param tid: Table ID
+ :param data: Data
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = []
+ # Check if constraint is in data
+ # If yes then we need to check for add/change/delete
+ if 'foreign_key' in data:
+ constraint = data['foreign_key']
+ # If constraint(s) is/are deleted
+ _get_sql_for_delete_fk_constraint(data, constraint, sql, template_path,
+ conn)
+
+ if 'changed' in constraint:
+ for c in constraint['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ modified_sql, _ = get_sql(conn, c, tid, c['oid'])
+ sql.append(modified_sql.strip("\n"))
+
+ if 'added' in constraint:
+ for c in constraint['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ add_sql, _ = get_sql(conn, c, tid)
+ sql.append(add_sql.strip("\n"))
+
+ if len(sql) > 0:
+ # Join all the sql(s) as single string
+ return '\n\n'.join(sql)
+ else:
+ return None
+
+
+@get_template_path
+def get_sql(conn, data, tid, fkid=None, template_path=None):
+ """
+ This function will generate sql from model data.
+ :param conn: Connection Object
+ :param data: data
+ :param tid: Table id
+ :param fkid: Foreign Key
+ :param template_path: Template Path
+ :return:
+ """
+ if fkid is not None:
+ old_data, name = _get_properties_for_fk_const(tid, fkid, data,
+ template_path, conn)
+
+ sql = render_template("/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn)
+
+ if 'autoindex' in data and data['autoindex'] and \
+ ('coveringindex' in data and data['coveringindex'] != ''):
+ col_sql = render_template(
+ "/".join([template_path, 'get_constraint_cols.sql']),
+ tid=tid,
+ keys=zip(old_data['confkey'], old_data['conkey']),
+ confrelid=old_data['confrelid']
+ )
+
+ status, res = conn.execute_dict(col_sql)
+ if not status:
+ raise ExecuteError(res)
+
+ columns = []
+ for row in res['rows']:
+ columns.append({"local_column": row['conattname'],
+ "references": old_data['confrelid'],
+ "referenced": row['confattname']})
+
+ data['columns'] = columns
+
+ sql += render_template(
+ "/".join([template_path, 'create_index.sql']),
+ data=data, conn=conn)
+ else:
+ is_error, errmsg, name, sql = _get_sql_for_create_fk_const(
+ data, conn, template_path)
+ if is_error:
+ return _(errmsg), name
+
+ return sql, name
+
+
+def _get_properties_for_fk_const(tid, fkid, data, template_path, conn):
+ """
+ Get property data for fk constraint.
+ tid: table Id
+ fkid: Foreign key constraint ID.
+ data: Data.
+ template_path: template path for get sql.
+ conn: Connection.
+ """
+ name = data['name'] if 'name' in data else None
+ sql = render_template("/".join([template_path, FKEY_PROPERTIES_SQL]),
+ tid=tid, cid=fkid)
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(
+ _('Could not find the foreign key constraint in the table.'))
+
+ old_data = res['rows'][0]
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ return old_data, name
+
+
+def _get_sql_for_create_fk_const(data, conn, template_path):
+ """
+ Get SQL for create new foreign key constrains.
+ data: Data.
+ conn: Connection
+ template_path: template path for get template.
+ """
+ name = data['name'] if 'name' in data else None
+ if 'columns' not in data or \
+ (isinstance(data['columns'], list) and
+ len(data['columns']) < 1):
+ return True, '-- definition incomplete', name, ''
+
+ if data.get('autoindex', False) and \
+ ('coveringindex' not in data or data['coveringindex'] == ''):
+ return True, '-- definition incomplete', name, ''
+
+ if 'references' in data['columns'][0]:
+ # Get the parent schema and table.
+ schema, table = get_parent(conn,
+ data['columns'][0]['references'])
+
+ # Below handling will be used in Schema diff in case
+ # of different database comparison
+ _checks_for_schema_diff(table, schema, data)
+
+ sql = render_template("/".join([template_path, 'create.sql']),
+ data=data, conn=conn)
+
+ if data.get('autoindex', False):
+ sql += render_template(
+ "/".join([template_path, 'create_index.sql']),
+ data=data, conn=conn)
+
+ return False, '', '', sql
+
+
+def _checks_for_schema_diff(table, schema, data):
+ """
+ Check for schema diff in case of different database comparisons.
+ table: table data
+ schema: schema data
+ data:Data
+ """
+ if schema and table:
+ data['remote_schema'] = schema
+ data['remote_table'] = table
+
+ if 'remote_schema' not in data:
+ data['remote_schema'] = None
+ if 'schema' in data and (schema is None or schema == ''):
+ data['remote_schema'] = data['schema']
+
+ if 'remote_table' not in data:
+ data['remote_table'] = None
+
+
+@get_template_path
+def get_fkey_dependencies(conn, tid, template_path=None):
+ """
+ This function is used to get the references table of all the foreign
+ keys of the given table.
+
+ :param conn:
+ :param tid:
+ :param template_path:
+ :return:
+ """
+ deps = []
+ sql = render_template("/".join(
+ [template_path, FKEY_PROPERTIES_SQL]), tid=tid)
+
+ status, result = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=result)
+
+ for fk in result['rows']:
+ ref_name = fk['refnsp'] + '.' + fk['reftab']
+ deps.append({'type': 'table', 'name': ref_name})
+
+ return True, deps
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..15a8d180d7fe82c86f71fa88f773868c081ee7aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/__init__.py
@@ -0,0 +1,1062 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Primary key constraint Node"""
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, make_response, request, jsonify
+from flask_babel import gettext as _
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.type import ConstraintRegistry, ConstraintTypeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.index_constraint import utils as idxcons_utils
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+
+
+class IndexConstraintModule(ConstraintTypeModule):
+ """
+ class IndexConstraintModule(CollectionNodeModule)
+
+ A module class for Primary key constraint node derived from
+ ConstraintTypeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the PrimaryKeyConstraintModule and
+ it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for language, when any of the database node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'index_constraint'
+ _COLLECTION_LABEL = _('Index constraint')
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the PrimaryKeyConstraintModule and
+ it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+
+ Returns:
+
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def get_nodes(self, gid, sid, did, scid, tid):
+ """
+ Generate the collection node
+ """
+ pass
+
+ @property
+ def node_inode(self):
+ """
+ Override this property to make the node a leaf node.
+
+ Returns: False as this is the leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for primary_key, when any of the table node is
+ initialized.
+
+ Returns: node type of the server module.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+class PrimaryKeyConstraintModule(IndexConstraintModule):
+ """
+ class PrimaryKeyConstraintModule(IndexConstraintModule)
+
+ A module class for the catalog schema node derived from
+ IndexConstraintModule.
+ """
+
+ _NODE_TYPE = 'primary_key'
+ _COLLECTION_LABEL = _("Primary Key")
+
+
+primary_key_blueprint = PrimaryKeyConstraintModule(__name__)
+
+
+class UniqueConstraintModule(IndexConstraintModule):
+ """
+ class UniqueConstraintModule(IndexConstraintModule)
+
+ A module class for the catalog schema node derived from
+ IndexConstraintModule.
+ """
+
+ _NODE_TYPE = 'unique_constraint'
+ _COLLECTION_LABEL = _("Unique Constraint")
+
+
+unique_constraint_blueprint = UniqueConstraintModule(__name__)
+
+
+class IndexConstraintView(PGChildNodeView):
+ """
+ class PrimaryKeyConstraintView(PGChildNodeView)
+
+ A view class for Primary key constraint node derived from
+ PGChildNodeView. This class is responsible for all the stuff related
+ to view like creating, updating Primary key constraint
+ node, showing properties, showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the PrimaryKeyConstraintView and
+ it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function returns primary key constraint nodes within that
+ collection as http response.
+
+ * get_list()
+ - This function is used to list all the language nodes within that
+ collection and return list of primary key constraint nodes.
+
+ * nodes()
+ - This function returns child node within that collection.
+ Here return all primary key constraint node as http response.
+
+ * get_nodes()
+ - returns all primary key constraint nodes' list.
+
+ * properties()
+ - This function will show the properties of the selected primary key.
+
+ * update()
+ - This function will update the data for the selected primary key.
+
+ * msql()
+ - This function is used to return modified SQL for the selected primary
+ key.
+
+ * get_sql()
+ - This function will generate sql from model data.
+
+ * sql():
+ - This function will generate sql to show it in sql pane for the
+ selected primary key.
+
+ * get_indices():
+ - This function returns indices for current table.
+
+ * dependency():
+ - This function will generate dependency list show it in dependency
+ pane for the selected Index constraint.
+
+ * dependent():
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Index constraint.
+ """
+
+ node_type = 'index_constraint'
+
+ node_label = _('Index constraint')
+ INDEX_CONSTRAINT_PATH = 'index_constraint/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [{'type': 'int', 'id': 'cid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.datistemplate = False
+ if (
+ self.manager.db_info is not None and
+ kwargs['did'] in self.manager.db_info and
+ 'datistemplate' in self.manager.db_info[kwargs['did']]
+ ):
+ self.datistemplate = self.manager.db_info[
+ kwargs['did']]['datistemplate']
+
+ self.template_path = self.INDEX_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = idxcons_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ def end_transaction(self):
+ SQL = render_template(
+ "/".join([self.template_path, 'end.sql']))
+ # End transaction if any.
+ self.conn.execute_scalar(SQL)
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function is used to list all the primary key
+ nodes within that collection.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ status, res = idxcons_utils.get_index_constraints(self.conn, did, tid,
+ self.constraint_type,
+ cid)
+ if not status:
+ return res
+
+ if len(res) == 0:
+ return gone(self.key_not_found_error_msg())
+
+ result = res
+ if cid:
+ result = res[0]
+ result['is_sys_obj'] = (
+ result['oid'] <= self._DATABASE_LAST_SYSTEM_OID or
+ self.datistemplate)
+
+ return ajax_response(
+ response=result,
+ status=200
+ )
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns all primary keys
+ nodes within that collection as a http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ try:
+ res = self.get_node_list(gid, sid, did, scid, tid, cid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_node_list(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns all primary keys
+ nodes within that collection as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.template_path = self.INDEX_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = idxcons_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), did=did,
+ tid=tid,
+ constraint_type=self.constraint_type)
+ _, res = self.conn.execute_dict(SQL)
+
+ for row in res['rows']:
+ row['_type'] = self.node_type
+
+ return res['rows']
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, cid):
+ """
+ This function returns all event trigger nodes as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ SQL = render_template("/".join([self.template_path, self._NODES_SQL]),
+ cid=cid,
+ tid=tid,
+ constraint_type=self.constraint_type)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.key_not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon=self.node_icon
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function returns all event trigger nodes as a
+ http response.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ SQL = render_template("/".join([self.template_path, self._NODES_SQL]),
+ tid=tid,
+ constraint_type=self.constraint_type)
+ status, rset = self.conn.execute_2darray(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ res = []
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['comment']
+ )
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_nodes(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns all event trigger nodes as a list.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+ self.conn = self.manager.connection(did=did)
+ self.template_path = self.INDEX_CONSTRAINT_PATH.format(
+ self.manager.version)
+
+ # We need parent's name eg table name and schema name
+ schema, table = idxcons_utils.get_parent(self.conn, tid)
+ self.schema = schema
+ self.table = table
+
+ res = []
+ SQL = render_template("/".join([self.template_path, self._NODES_SQL]),
+ tid=tid,
+ constraint_type=self.constraint_type)
+ _, rset = self.conn.execute_2darray(SQL)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=self.node_icon,
+ description=row['comment']
+ ))
+ return res
+
+ @staticmethod
+ def _get_req_data():
+ """
+ Get data from request.
+ return: data.
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ return data
+
+ @staticmethod
+ def _check_required_args(data):
+ required_args = [
+ ['columns', 'index'] # Either of one should be there.
+ ]
+
+ def is_key_list(key, data):
+ return isinstance(data[key], list) and len(data[param]) > 0
+
+ for arg in required_args:
+ if isinstance(arg, list):
+ for param in arg:
+ if param in data and (param != 'columns' or
+ is_key_list(param, data)):
+ break
+ else:
+ return True, make_json_response(
+ status=400,
+ success=0,
+ errormsg=_(
+ "Could not find at least one required "
+ "parameter ({}).".format(str(param)))
+ )
+
+ elif arg not in data:
+ return True, make_json_response(
+ status=400,
+ success=0,
+ errormsg=_(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+
+ return False, ''
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function will create a primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ data = IndexConstraintView._get_req_data()
+
+ is_error, errmsg = IndexConstraintView._check_required_args(data)
+
+ if is_error:
+ return errmsg
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ if 'name' not in data or data['name'] == "":
+ sql = render_template(
+ "/".join([self.template_path, 'begin.sql']))
+ # Start transaction.
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ # The below SQL will execute CREATE DDL only
+ sql = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn,
+ constraint_name=self.constraint_name
+ )
+ status, msg = self.conn.execute_scalar(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=msg)
+ elif 'name' not in data or data['name'] == "":
+ sql = render_template(
+ "/".join([self.template_path,
+ 'get_oid_with_transaction.sql'],
+ ),
+ constraint_type=self.constraint_type,
+ tid=tid)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ self.end_transaction()
+
+ data['name'] = res['rows'][0]['name']
+
+ else:
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid,
+ constraint_type=self.constraint_type,
+ name=data['name'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ self.end_transaction()
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ res['rows'][0]['oid'],
+ tid,
+ data['name'],
+ icon=self.node_icon,
+ **other_node_info
+ )
+ )
+
+ except Exception as e:
+ self.end_transaction()
+ return make_json_response(
+ status=400,
+ success=0,
+ errormsg=e
+ )
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function will update the data for the selected
+ primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql, name = idxcons_utils.get_sql(self.conn, data, did, tid,
+ self.constraint_type, cid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ sql = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid,
+ constraint_type=self.constraint_type,
+ name=data['name'],
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ cid,
+ tid,
+ name,
+ icon=self.node_icon,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function will delete an existing primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ if cid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [cid]}
+
+ # Below code will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+ try:
+ for cid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path, 'get_name.sql']),
+ tid=tid,
+ constraint_type=self.constraint_type,
+ cid=cid
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=_(
+ 'Error: Object not found.'
+ ),
+ info=_(
+ 'The specified constraint could not be found.\n'
+ )
+ )
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ cascade=cascade)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=_("{0} dropped.").format(self.node_label),
+ data={
+ 'id': cid,
+ 'sid': sid,
+ 'gid': gid,
+ 'did': did
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function returns modified SQL for the selected
+ primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ sql, _ = idxcons_utils.get_sql(self.conn, data, did, tid,
+ self.constraint_type, cid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, cid=None):
+ """
+ This function generates sql to show in the sql pane for the selected
+ primary key.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key constraint ID
+
+ Returns:
+
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did,
+ tid=tid,
+ conn=self.conn,
+ cid=cid,
+ constraint_type=self.constraint_type)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.key_not_found_error_msg())
+
+ data = res['rows'][0]
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ sql = render_template(
+ "/".join([self.template_path, 'get_constraint_cols.sql']),
+ cid=cid, colcnt=data['col_count'])
+
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ columns = []
+ for row in res['rows']:
+ columns.append({"column": row['column'].strip('"')})
+
+ data['columns'] = columns
+
+ # Add Include details of the index supported for PG-11+
+ if self.manager.version >= 110000:
+ sql = render_template(
+ "/".join([self.template_path, 'get_constraint_include.sql']),
+ cid=cid)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ data['include'] = [col['colname'] for col in res['rows']]
+
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data,
+ constraint_name=self.constraint_name,
+ conn=self.conn
+ )
+
+ sql_header = "-- Constraint: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data)
+ sql_header += "\n"
+
+ SQL = sql_header + SQL
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, tid, cid):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Primary key/Unique constraint ID
+
+ Returns the statistics for a particular object if cid is specified
+ """
+
+ # Check if pgstattuple extension is already created?
+ # if created then only add extended stats
+ status, is_pgstattuple = self.conn.execute_scalar("""
+ SELECT (pg_catalog.count(extname) > 0) AS is_pgstattuple
+ FROM pg_catalog.pg_extension
+ WHERE extname='pgstattuple'
+ """)
+ if not status:
+ return internal_server_error(errormsg=is_pgstattuple)
+
+ if is_pgstattuple:
+ # Fetch index details only if extended stats available
+ sql = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did,
+ tid=tid,
+ cid=cid,
+ constraint_type=self.constraint_type
+ )
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.key_not_found_error_msg())
+
+ result = res['rows'][0]
+ name = result['name']
+ else:
+ name = None
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'stats.sql']),
+ conn=self.conn, schema=self.schema,
+ name=name, cid=cid, is_pgstattuple=is_pgstattuple
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, cid):
+ """
+ This function get the dependents and return ajax response
+ for the constraint node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Index constraint ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, cid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, cid):
+ """
+ This function get the dependencies and return ajax response
+ for the constraint node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ cid: Index constraint ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, cid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ def key_not_found_error_msg(self):
+ return _("""Could not find the {} in the table.""").format(
+ _("primary key") if self.constraint_type == "p"
+ else _("unique key")
+ )
+
+
+class PrimaryKeyConstraintView(IndexConstraintView):
+ node_type = 'primary_key'
+
+ node_label = _('Primary key')
+
+ constraint_name = "PRIMARY KEY"
+
+ constraint_type = "p"
+
+ node_icon = "icon-%s" % node_type
+
+
+class UniqueConstraintView(IndexConstraintView):
+ node_type = 'unique_constraint'
+
+ node_label = _('Unique constraint')
+
+ constraint_name = "UNIQUE"
+
+ constraint_type = "u"
+
+ node_icon = "icon-%s" % node_type
+
+
+primary_key_constraint = ConstraintRegistry(
+ 'primary_key', PrimaryKeyConstraintModule, PrimaryKeyConstraintView
+)
+
+unique_constraint = ConstraintRegistry(
+ 'unique_constraint', UniqueConstraintModule, UniqueConstraintView
+)
+
+PrimaryKeyConstraintView.register_node_view(primary_key_blueprint)
+UniqueConstraintView.register_node_view(unique_constraint_blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/primary_key.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/primary_key.svg
new file mode 100644
index 0000000000000000000000000000000000000000..e1864243c1a021cbfa3ab0e1107eec1de6ae675c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/primary_key.svg
@@ -0,0 +1 @@
+primary_key
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/unique_constraint.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/unique_constraint.svg
new file mode 100644
index 0000000000000000000000000000000000000000..7a1f42b88847a254be92d38817a2012d7214da7e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/img/unique_constraint.svg
@@ -0,0 +1 @@
+unique_constraint 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.js
new file mode 100644
index 0000000000000000000000000000000000000000..91646a874fbed3599f83430f7661ec2b0325e5b5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.js
@@ -0,0 +1,116 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeListByName } from '../../../../../../../../../static/js/node_ajax';
+import PrimaryKeySchema from './primary_key.ui';
+import _ from 'lodash';
+
+define('pgadmin.node.primary_key', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser) {
+
+ // Extend the browser's node class for index constraint node
+ if (!pgBrowser.Nodes['primary_key']) {
+ pgAdmin.Browser.Nodes['primary_key'] = pgBrowser.Node.extend({
+ type: 'primary_key',
+ label: gettext('Primary key'),
+ collection_type: 'coll-constraints',
+ sqlAlterHelp: 'ddl-alter.html',
+ sqlCreateHelp: 'ddl-constraints.html',
+ dialogHelp: url_for('help.static', {filename: 'primary_key_dialog.html'}),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Index size')],
+ parent_type: ['table','partition'],
+ canDrop: true,
+ canDropCascade: true,
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_primary_key_on_coll', node: 'coll-constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Primary key'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ ]);
+ },
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [],
+ immediate_parent_table_found = false,
+ is_immediate_parent_table_partitioned = false,
+ s_version = t.getTreeNodeHierarchy(i).server.version;
+
+ // To iterate over tree to check parent node
+ while (i) {
+ // If table is partitioned table then return false
+ if (!immediate_parent_table_found && (d._type == 'table' || d._type == 'partition')) {
+ immediate_parent_table_found = true;
+ if ('is_partitioned' in d && d.is_partitioned && s_version < 110000) {
+ is_immediate_parent_table_partitioned = true;
+ }
+ }
+
+ // If it is schema then allow user to c reate table
+ if (_.indexOf(['schema'], d._type) > -1) {
+ if (is_immediate_parent_table_partitioned) {
+ return false;
+ }
+
+ // There should be only one primary key per table.
+ let children = t.children(arguments[1], false),
+ primary_key_found = false;
+
+ _.each(children, function(child){
+ data = pgBrowser.tree.itemData(child);
+ if (!primary_key_found && data._type == 'primary_key') {
+ primary_key_found = true;
+ }
+ });
+ return !primary_key_found;
+ }else if (_.indexOf(['foreign_table', 'coll-foreign_table'], d._type) > -1) {
+ return false;
+ }
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ if (_.indexOf(parents, 'catalog') > -1) {
+ return false;
+ } else {
+ return !is_immediate_parent_table_partitioned;
+ }
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new PrimaryKeySchema({
+ columns: ()=>getNodeListByName('column', treeNodeInfo, itemNodeData),
+ spcname: ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ }),
+ index: ()=>getNodeListByName('index', treeNodeInfo, itemNodeData, {jumpAfterNode: 'schema'}),
+ }, treeNodeInfo);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['primary_key'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..b0bc8c01dab39a607a78f406201ada33c33b0cf1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/primary_key.ui.js
@@ -0,0 +1,273 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import { SCHEMA_STATE_ACTIONS } from '../../../../../../../../../../static/js/SchemaView';
+import TableSchema from '../../../../static/js/table.ui';
+export default class PrimaryKeySchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ is_sys_obj: undefined,
+ comment: undefined,
+ spcname: undefined,
+ index: undefined,
+ fillfactor: undefined,
+ condeferrable: undefined,
+ condeferred: undefined,
+ columns: [],
+ include: [],
+ });
+
+ this.fieldOptions = fieldOptions;
+ this.nodeInfo = nodeInfo;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get inTable() {
+ return this.top && this.top instanceof TableSchema;
+ }
+
+ changeColumnOptions(columns) {
+ this.fieldOptions.columns = columns;
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text',
+ mode: ['properties', 'create', 'edit'], editable:true,
+ cell: 'text',
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'], editable: false,
+ },{
+ id: 'is_sys_obj', label: gettext('System primary key?'),
+ cell:'switch', type: 'switch', mode: ['properties'],
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'multiline',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ deps:['name'], disabled: (state)=>{
+ return isEmptyString(state.name);
+ }, depChange: (state)=>{
+ if(isEmptyString(state.name)){
+ return {comment: ''};
+ }
+ }
+ },{
+ id: 'columns', label: gettext('Columns'),
+ deps: ()=>{
+ let ret = ['index'];
+ if(obj.inTable) {
+ ret.push(['columns']);
+ }
+ return ret;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ /* If in table, sync up value with columns in table */
+ if(obj.inTable && !state) {
+ /* the FK is removed by some other dep, this can be a no-op */
+ return;
+ }
+ let currColumns = state.columns || [];
+ if(obj.inTable && source[0] == 'columns') {
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.DELETE_ROW) {
+ let oldColumn = _.get(actionObj.oldState, actionObj.path.concat(actionObj.value));
+ currColumns = _.filter(currColumns, (cc)=>cc.cid != oldColumn.cid);
+ } else if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE) {
+ let tabColPath = _.slice(actionObj.path, 0, -1);
+ let oldCol = _.get(actionObj.oldState, tabColPath);
+ let idx = _.findIndex(currColumns, (cc)=>cc.cid == oldCol.cid);
+ if(idx > -1) {
+ currColumns[idx].column = _.get(topState, tabColPath).name;
+ }
+ }
+ }
+ return {columns: currColumns};
+ },
+ cell: ()=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: (backendVal)=>{
+ /* remove the column key and pass as array */
+ return _.join((backendVal||[]).map((singleVal)=>singleVal.column));
+ },
+ },
+ }
+ }),
+ type: ()=>({
+ type: 'select',
+ optionsReloadBasis: obj.fieldOptions.columns?.map ? _.join(obj.fieldOptions.columns.map((c)=>c.label), ',') : null,
+ options: obj.fieldOptions.columns,
+ controlProps: {
+ allowClear:false,
+ multiple: true,
+ formatter: {
+ fromRaw: (backendVal, allOptions)=>{
+ /* remove the column key and pass as array */
+ let optValues = (backendVal||[]).map((singleVal)=>singleVal.column);
+ return _.filter(allOptions, (opt)=>optValues.indexOf(opt.value)>-1);
+ },
+ toRaw: (value)=>{
+ /* take the array and convert to column key collection */
+ return (value||[]).map((singleVal)=>({column: singleVal.value}));
+ },
+ },
+ },
+ }), group: gettext('Definition'),
+ editable: false,
+ readonly: function(state) {
+ if(!obj.isNew(state)) {
+ return true;
+ }
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ },{
+ id: 'include', label: gettext('Include columns'),
+ type: ()=>({
+ type: 'select',
+ options: this.fieldOptions.columns,
+ controlProps: {
+ multiple: true,
+ },
+ }), group: gettext('Definition'),
+ editable: false,
+ canDelete: true, canAdd: true,
+ mode: ['properties', 'create', 'edit'],
+ min_version: 110000,
+ deps: ['index'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {include: []};
+ }
+ }
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.spcname,
+ deps: ['index'],
+ controlProps:{allowClear:false},
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {spcname: ''};
+ }
+ }
+ },{
+ id: 'index', label: gettext('Index'),
+ mode: ['create'],
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.index,
+ controlProps:{
+ allowClear:true,
+ },
+ readonly: function() {
+ if(!obj.isNew()) {
+ return true;
+ }
+ },
+ // We will not show this field in Create Table mode
+ visible: function() {
+ return !obj.inTable;
+ },
+ },{
+ id: 'fillfactor', label: gettext('Fill factor'), deps: ['index'],
+ type: 'int', group: gettext('Definition'), min: 10, max: 100,
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {fillfactor: null};
+ }
+ }
+ },{
+ id: 'condeferrable', label: gettext('Deferrable?'),
+ type: 'switch', group: gettext('Definition'), deps: ['index'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {condeferrable: false};
+ }
+ }
+ },{
+ id: 'condeferred', label: gettext('Deferred?'),
+ type: 'switch', group: gettext('Definition'),
+ deps: ['condeferrable'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '') || !state.condeferrable;
+ },
+ depChange: (state)=>{
+ if(!state.condeferrable) {
+ return {condeferred: false};
+ } else if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {condeferred: false};
+ }
+ }
+ }];
+ }
+
+ validate(state, setError) {
+ if (!this.isNew(state) && isEmptyString(state.name)) {
+ setError('name', gettext('Name cannot be empty in edit mode.'));
+ return true;
+ } else {
+ setError('name', null);
+ }
+
+ if(isEmptyString(state.index)
+ && (_.isUndefined(state.columns) || _.isNull(state.columns) || state.columns.length < 1)) {
+ setError('columns', gettext('Please specify columns for %s.', gettext('Primary key')));
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.js
new file mode 100644
index 0000000000000000000000000000000000000000..947f55df5bfcac76e77e7e1a36bc5256021a7df9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.js
@@ -0,0 +1,102 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeListByName } from '../../../../../../../../../static/js/node_ajax';
+import UniqueConstraintSchema from './unique_constraint.ui';
+import _ from 'lodash';
+
+define('pgadmin.node.unique_constraint', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser) {
+
+ // Extend the browser's node class for index constraint node
+ if (!pgBrowser.Nodes['unique_constraint']) {
+ pgAdmin.Browser.Nodes['unique_constraint'] = pgBrowser.Node.extend({
+ type: 'unique_constraint',
+ label: gettext('Unique constraint'),
+ collection_type: 'coll-constraints',
+ sqlAlterHelp: 'ddl-alter.html',
+ sqlCreateHelp: 'ddl-constraints.html',
+ dialogHelp: url_for('help.static', {filename: 'unique_constraint_dialog.html'}),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Index size')],
+ parent_type: ['table','partition'],
+ canDrop: true,
+ canDropCascade: true,
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_unique_constraint_on_coll', node: 'coll-constraints', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Unique constraint'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ ]);
+ },
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [],
+ immediate_parent_table_found = false,
+ is_immediate_parent_table_partitioned = false,
+ s_version = pgBrowser.tree.getTreeNodeHierarchy(i).server.version;
+
+ // To iterate over tree to check parent node
+ while (i) {
+ // If table is partitioned table then return false
+ if (!immediate_parent_table_found && (d._type == 'table' || d._type == 'partition')) {
+ immediate_parent_table_found = true;
+ if ('is_partitioned' in d && d.is_partitioned && s_version < 110000) {
+ is_immediate_parent_table_partitioned = true;
+ }
+ }
+
+ // If it is schema then allow user to c reate table
+ if (_.indexOf(['schema'], d._type) > -1) {
+ return !is_immediate_parent_table_partitioned;
+ }else if (_.indexOf(['foreign_table', 'coll-foreign_table'], d._type) > -1) {
+ return false;
+ }
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ if (_.indexOf(parents, 'catalog') > -1) {
+ return false;
+ } else {
+ return !is_immediate_parent_table_partitioned;
+ }
+ },
+
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new UniqueConstraintSchema({
+ columns: ()=>getNodeListByName('column', treeNodeInfo, itemNodeData),
+ spcname: ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ }),
+ index: ()=>getNodeListByName('index', treeNodeInfo, itemNodeData, {jumpAfterNode: 'schema'}),
+ }, treeNodeInfo);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['unique_constraint'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..632193db5555438f29ce789370f77524358ddcad
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/static/js/unique_constraint.ui.js
@@ -0,0 +1,273 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import { SCHEMA_STATE_ACTIONS } from '../../../../../../../../../../static/js/SchemaView';
+import TableSchema from '../../../../static/js/table.ui';
+
+export default class UniqueConstraintSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ is_sys_obj: undefined,
+ comment: undefined,
+ spcname: undefined,
+ index: undefined,
+ fillfactor: undefined,
+ condeferrable: undefined,
+ condeferred: undefined,
+ indnullsnotdistinct: undefined,
+ columns: [],
+ include: [],
+ });
+
+ this.fieldOptions = fieldOptions;
+ this.nodeInfo = nodeInfo;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get inTable() {
+ return this.top && this.top instanceof TableSchema;
+ }
+
+ changeColumnOptions(columns) {
+ this.fieldOptions.columns = columns;
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text',
+ mode: ['properties', 'create', 'edit'], editable:true,
+ cell: 'text',
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text' , mode: ['properties'], editable: false,
+ },{
+ id: 'is_sys_obj', label: gettext('System primary key?'),
+ cell:'switch', type: 'switch', mode: ['properties'],
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'multiline',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ deps:['name'], disabled: (state)=>{
+ return isEmptyString(state.name);
+ }, depChange: (state)=>{
+ if(isEmptyString(state.name)){
+ return {comment: ''};
+ }
+ }
+ },{
+ id: 'columns', label: gettext('Columns'),
+ deps: ()=>{
+ let ret = ['index'];
+ if(obj.inTable) {
+ ret.push(['columns']);
+ }
+ return ret;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ /* If in table, sync up value with columns in table */
+ if(obj.inTable && !state) {
+ /* the FK is removed by some other dep, this can be a no-op */
+ return;
+ }
+ let currColumns = state.columns || [];
+ if(obj.inTable && source[0] == 'columns') {
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.DELETE_ROW) {
+ let oldColumn = _.get(actionObj.oldState, actionObj.path.concat(actionObj.value));
+ currColumns = _.filter(currColumns, (cc)=>cc.cid != oldColumn.cid);
+ } else if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE) {
+ let tabColPath = _.slice(actionObj.path, 0, -1);
+ let oldCol = _.get(actionObj.oldState, tabColPath);
+ let idx = _.findIndex(currColumns, (cc)=>cc.cid == oldCol.cid);
+ if(idx > -1) {
+ currColumns[idx].column = _.get(topState, tabColPath).name;
+ }
+ }
+ }
+ return {columns: currColumns};
+ },
+ cell: ()=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: (backendVal)=>{
+ /* remove the column key and pass as array */
+ return _.join((backendVal||[]).map((singleVal)=>singleVal.column));
+ },
+ },
+ }
+ }),
+ type: ()=>({
+ type: 'select',
+ optionsReloadBasis: obj.fieldOptions.columns?.map ? _.join(obj.fieldOptions.columns.map((c)=>c.label), ',') : null,
+ options: obj.fieldOptions.columns,
+ controlProps: {
+ allowClear:false,
+ multiple: true,
+ formatter: {
+ fromRaw: (backendVal, allOptions)=>{
+ /* remove the column key and pass as array */
+ let optValues = (backendVal||[]).map((singleVal)=>singleVal.column);
+ return _.filter(allOptions, (opt)=>optValues.indexOf(opt.value)>-1);
+ },
+ toRaw: (value)=>{
+ /* take the array and convert to column key collection */
+ return (value||[]).map((singleVal)=>({column: singleVal.value}));
+ },
+ },
+ },
+ }), group: gettext('Definition'),
+ editable: false,
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ },{
+ id: 'include', label: gettext('Include columns'),
+ type: ()=>({
+ type: 'select',
+ options: this.fieldOptions.columns,
+ controlProps: {
+ multiple: true,
+ },
+ }), group: gettext('Definition'),
+ editable: false,
+ canDelete: true, canAdd: true,
+ mode: ['properties', 'create', 'edit'],
+ min_version: 110000,
+ deps: ['index'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {include: []};
+ }
+ }
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.spcname,
+ deps: ['index'],
+ controlProps:{allowClear:false},
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {spcname: ''};
+ }
+ }
+ },{
+ id: 'index', label: gettext('Index'),
+ mode: ['create'],
+ type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.index,
+ controlProps:{
+ allowClear:true,
+ },
+ readonly: function() {
+ if(!obj.isNew()) {
+ return true;
+ }
+ },
+ // We will not show this field in Create Table mode
+ visible: function() {
+ return !obj.inTable;
+ },
+ },{
+ id: 'fillfactor', label: gettext('Fill factor'), deps: ['index'],
+ type: 'int', group: gettext('Definition'),
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {fillfactor: null};
+ }
+ }
+ },{
+ id: 'condeferrable', label: gettext('Deferrable?'),
+ type: 'switch', group: gettext('Definition'), deps: ['index'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '');
+ },
+ depChange: (state)=>{
+ if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {condeferrable: false};
+ }
+ }
+ },{
+ id: 'condeferred', label: gettext('Deferred?'),
+ type: 'switch', group: gettext('Definition'),
+ deps: ['condeferrable'],
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ disabled: function(state) {
+ // Disable if index is selected.
+ return !(_.isUndefined(state.index) || state.index == '') || !state.condeferrable;
+ },
+ depChange: (state)=>{
+ if(!state.condeferrable) {
+ return {condeferred: false};
+ } else if(_.isUndefined(state.index) || state.index == '') {
+ return {};
+ } else {
+ return {condeferred: false};
+ }
+ }
+ },{
+ id: 'indnullsnotdistinct', label: gettext('NULLs not distinct?'),
+ type: 'switch', group: gettext('Definition'),
+ readonly: function(state) {
+ return obj.isReadOnly(state);
+ },
+ min_version: 150000
+ }];
+ }
+
+ validate(state, setError) {
+ if(isEmptyString(state.index)
+ && (_.isUndefined(state.columns) || _.isNull(state.columns) || state.columns.length < 1)) {
+ setError('columns', gettext('Please specify columns for %s.', gettext('Unique constraint')));
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1404209a196c1ba5429505cb91db86a780b7d7a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/index_constraint/utils.py
@@ -0,0 +1,304 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Index Constraint. """
+
+from flask import render_template
+from flask_babel import gettext as _
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs:
+ kwargs['template_path'] = 'index_constraint/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_index_constraints(conn, did, tid, ctype, cid=None, template_path=None):
+ """
+ This function is used to fetch information of the
+ index constraint(s) for the given table.
+ :param conn: Connection Object
+ :param did: Database ID
+ :param tid: Table ID
+ :param ctype: Constraint Type
+ :param cid: index Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, cid=cid, constraint_type=ctype)
+ status, result = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=result)
+
+ for idx_cons in result['rows']:
+ sql = render_template("/".join([template_path,
+ 'get_constraint_cols.sql']),
+ cid=idx_cons['oid'],
+ colcnt=idx_cons['col_count'])
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=res)
+
+ columns = []
+ for r in res['rows']:
+ columns.append({"column": r['column'].strip('"')})
+
+ idx_cons['columns'] = columns
+
+ # INCLUDE clause in index is supported from PG-11+
+ if conn.manager.version >= 110000:
+ sql = render_template("/".join([template_path,
+ 'get_constraint_include.sql']),
+ cid=idx_cons['oid'])
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return status, internal_server_error(errormsg=res)
+
+ idx_cons['include'] = [col['colname'] for col in res['rows']]
+
+ return True, result['rows']
+
+
+def _get_sql_to_delete_constraints(data, constraint, sql, template_path, conn):
+ """
+ Check for delete constraints.
+ :param data: data.
+ :param constraint: constraint according to it's type from data.
+ :param sql: sql list for all sql statements.
+ :param template_path: Template path.
+ :param conn: connection.
+ :return:
+ """
+ if 'deleted' in constraint:
+ for c in constraint['deleted']:
+ del_cols = []
+ if 'columns_to_be_dropped' in data:
+ del_cols = list(map(lambda x, y: x['column'] in y,
+ c['columns'],
+ data['columns_to_be_dropped'])
+ )
+
+ if len(del_cols) == 0:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ # Sql for drop
+ sql.append(render_template("/".join([template_path,
+ 'delete.sql']),
+ data=c,
+ conn=conn).strip('\n'))
+
+
+def _get_sql_to_change_constraints(did, tid, ctype, data, constraint,
+ sql, conn):
+ """
+ Check for chnage constraints.
+ :param did: data base id.
+ :param tid: table id.
+ :param ctype: constraint type.
+ :param data: data.
+ :param constraint: constraint according to it's type from data.
+ :param sql: sql list for all sql statements.
+ :param conn: connection.
+ :return:
+ """
+ if 'changed' in constraint:
+ for c in constraint['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ modified_sql, _ = get_sql(conn, c, did, tid, ctype, c['oid'])
+ if modified_sql:
+ sql.append(modified_sql.strip('\n'))
+
+
+def _get_sql_to_add_constraints(did, tid, ctype, data, constraint,
+ sql, conn):
+ """
+ Check for add constraints.
+ :param did: data base id.
+ :param tid: table id.
+ :param ctype: constraint type.
+ :param data: data.
+ :param constraint: constraint according to it's type from data.
+ :param sql: sql list for all sql statements.
+ :param conn: connection.
+ :return:
+ """
+ if 'added' in constraint:
+ for c in constraint['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ add_sql, _ = get_sql(conn, c, did, tid, ctype)
+ sql.append(add_sql.strip("\n"))
+
+
+@get_template_path
+def get_index_constraint_sql(conn, did, tid, data, template_path=None):
+ """
+ This function will return sql for index constraints.
+ :param conn: Connection Object
+ :param did: Database ID
+ :param tid: Table ID
+ :param data: Data
+ :param template_path: Template Path
+ :return:
+ """
+ sql = []
+ # We will fetch all the index constraints for the table
+ index_constraints = {
+ 'p': 'primary_key', 'u': 'unique_constraint'
+ }
+
+ for ctype in index_constraints.keys():
+ # Check if constraint is in data
+ # If yes then we need to check for add/change/delete
+ if index_constraints[ctype] in data:
+ constraint = data[index_constraints[ctype]]
+ # If constraint(s) is/are deleted
+ _get_sql_to_delete_constraints(data, constraint, sql,
+ template_path, conn)
+ # Get SQL for change constraints.
+ _get_sql_to_change_constraints(did, tid, ctype, data, constraint,
+ sql, conn)
+ # Get SQL for add constraints.
+ _get_sql_to_add_constraints(did, tid, ctype, data, constraint,
+ sql, conn)
+
+ if len(sql) > 0:
+ # Join all the sql(s) as single string
+ return '\n\n'.join(sql)
+ else:
+ return None
+
+
+def is_key_str(key, data):
+ return isinstance(data[key], str) and data[key] != ""
+
+
+def _check_required_args(data, name):
+ """
+ Check required arguments are present.
+ :param data: Data for check.
+ :param name: constraint name.
+ :return: If any error return error.
+ """
+ required_args = [
+ ['columns', 'index'] # Either of one should be there.
+ ]
+
+ def is_key_list(key, data):
+ return isinstance(data[key], list) and len(data[param]) > 0
+
+ for arg in required_args:
+ if isinstance(arg, list):
+ for param in arg:
+ if param in data and \
+ (is_key_str(param, data) or
+ is_key_list(param, data)):
+ break
+ else:
+ return True, '-- definition incomplete', name
+
+ elif arg not in data:
+ return True, '-- definition incomplete', name
+
+ return False, '', name
+
+
+@get_template_path
+def get_sql(conn, data, did, tid, ctype, cid=None, template_path=None):
+ """
+ This function will generate sql from model data.
+ :param conn: Connection Object
+ :param data: data
+ :param did: Database ID
+ :param tid: Table id
+ :param ctype: Constraint Type
+ :param cid: index Constraint ID
+ :param template_path: Template Path
+ :return:
+ """
+ name = data['name'] if 'name' in data else None
+ sql = None
+ if cid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, cid=cid,
+ constraint_type=ctype)
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+
+ elif len(res['rows']) == 0:
+ raise ObjectGone(
+ _('Could not find the constraint in the table.'))
+
+ old_data = res['rows'][0]
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ sql = render_template("/".join([template_path, 'update.sql']),
+ data=data,
+ o_data=old_data,
+ conn=conn)
+ else:
+ is_error, errmsg, name = _check_required_args(data, name)
+ if is_error:
+ return _(errmsg), name
+
+ sql = render_template("/".join([template_path, 'create.sql']),
+ data=data,
+ conn=conn,
+ constraint_name='PRIMARY KEY'
+ if ctype == 'p' else 'UNIQUE')
+ return sql, name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/img/coll-constraints.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/img/coll-constraints.svg
new file mode 100644
index 0000000000000000000000000000000000000000..2aea698e60bd3c14c91deefb982fbfcfbd611e89
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/img/coll-constraints.svg
@@ -0,0 +1 @@
+coll-constraints
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/js/constraints.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/js/constraints.js
new file mode 100644
index 0000000000000000000000000000000000000000..f91171240114d787510bd9955f43b2aa0e03b6cd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/static/js/constraints.js
@@ -0,0 +1,50 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+define('pgadmin.node.constraints', [
+ 'sources/gettext', 'sources/pgadmin',
+ 'pgadmin.browser', 'pgadmin.browser.collection',
+ 'pgadmin.node.unique_constraint', 'pgadmin.node.check_constraint',
+ 'pgadmin.node.foreign_key', 'pgadmin.node.exclusion_constraint',
+ 'pgadmin.node.primary_key',
+], function(gettext, pgAdmin, pgBrowser) {
+
+ if (!pgBrowser.Nodes['coll-constraints']) {
+ pgAdmin.Browser.Nodes['coll-constraints'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'constraints',
+ label: gettext('Constraints'),
+ type: 'coll-constraints',
+ columns: ['name', 'comment'],
+ canDrop: true,
+ canDropCascade: true,
+ });
+ }
+
+ if (!pgBrowser.Nodes['constraints']) {
+ pgAdmin.Browser.Nodes['constraints'] = pgBrowser.Node.extend({
+ type: 'constraints',
+ label: gettext('Constraints'),
+ collection_type: ['coll-constraints','coll-foreign_table'],
+ parent_type: ['table','foreign_table'],
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([]);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['constraints'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/type.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/type.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b655d35b753a0bd1f200b65c9517c860736734
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/type.py
@@ -0,0 +1,38 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+from flask import Blueprint
+from pgadmin.browser.collection import CollectionNodeModule
+
+
+class ConstraintRegistry():
+ """
+ ConstraintTypeRegistry
+
+ It is more of a registry for difference type of constraints for the tables.
+ Its job is to initialize to different type of constraint blueprint and
+ register it with its respective NodeView.
+ """
+ registry = dict()
+
+ def __init__(self, name, con_blueprint, con_nodeview):
+ if name not in ConstraintRegistry.registry:
+ blueprint = con_blueprint(name)
+
+ # TODO:: register the view with the blueprint
+ con_nodeview.register_node_view(blueprint)
+
+ ConstraintRegistry.registry[name] = {
+ 'blueprint': blueprint,
+ 'nodeview': con_nodeview
+ }
+
+
+class ConstraintTypeModule(CollectionNodeModule):
+ pass
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b650103091b68700284bcf343aa8e551cbfa183f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/__init__.py
@@ -0,0 +1,1180 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Index Node """
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ partitions import backend_supported
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.directory_compare import directory_diff
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.browser.server_groups.servers.databases.schemas. \
+ tables.indexes import utils as index_utils
+
+
+class IndexesModule(CollectionNodeModule):
+ """
+ class IndexesModule(CollectionNodeModule)
+
+ A module class for Index node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Index and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'index'
+ _COLLECTION_LABEL = gettext("Indexes")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the IndexModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def backend_supported(self, manager, **kwargs):
+ """
+ Load this module if vid is view, we will not load it under
+ material view
+ """
+ if super().backend_supported(manager, **kwargs):
+ conn = manager.connection(did=kwargs['did'])
+
+ # If PG version > 100000 and < 110000 then index is
+ # not supported for partitioned table.
+ if 'tid' in kwargs and 100000 <= manager.version < 110000:
+ return not backend_supported(self, manager, **kwargs)
+
+ if 'vid' not in kwargs:
+ return True
+
+ template_path = 'indexes/sql/#{0}#'.format(manager.version)
+ SQL = render_template(
+ "/".join([template_path, 'backend_support.sql']),
+ vid=kwargs['vid']
+ )
+ status, res = conn.execute_scalar(SQL)
+
+ # check if any errors
+ if not status:
+ return internal_server_error(errormsg=res)
+ # Check vid is view not material view
+ # then true, othewise false
+ return res
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs)
+ if self.has_nodes(sid, did, scid=scid,
+ tid=kwargs.get('tid', kwargs.get('vid', None)),
+ base_template_path=IndexesView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ kwargs['tid'] if 'tid' in kwargs else kwargs['vid']
+ )
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return False
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = IndexesModule(__name__)
+
+
+class IndexesView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Index node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the IndexView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Index nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Index node.
+
+ * node()
+ - This function will used to create the child node within that
+ collection, Here it will create specific the Index node.
+
+ * properties(gid, sid, did, scid, tid, idx)
+ - This function will show the properties of the selected Index node
+
+ * create(gid, sid, did, scid, tid)
+ - This function will create the new Index object
+
+ * update(gid, sid, did, scid, tid, idx)
+ - This function will update the data for the selected Index node
+
+ * delete(self, gid, sid, scid, tid, idx):
+ - This function will drop the Index object
+
+ * msql(gid, sid, did, scid, tid, idx)
+ - This function is used to return modified SQL for the selected
+ Index node
+
+ * get_sql(data, scid, tid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Index node.
+
+ * dependency(gid, sid, did, scid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Index node.
+
+ * dependent(gid, sid, did, scid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Index node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Index"
+ BASE_TEMPLATE_PATH = 'indexes/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'idx'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_collations': [{'get': 'get_collations'},
+ {'get': 'get_collations'}],
+ 'get_access_methods': [{'get': 'get_access_methods'},
+ {'get': 'get_access_methods'}],
+ 'get_op_class': [{'get': 'get_op_class'},
+ {'get': 'get_op_class'}]
+ })
+
+ # Schema Diff: Keys to ignore while comparing
+ keys_to_ignore = ['oid', 'relowner', 'schema', 'indclass',
+ 'indrelid', 'nspname', 'oid-2']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.table_template_path = compile_template_path(
+ 'tables/sql',
+ self.manager.version
+ )
+
+ # we will set template path for sql scripts
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version
+ )
+
+ # We need parent's name eg table name and schema name
+ # when we create new index in update we can fetch it using
+ # property sql
+ schema, table = index_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def get_collations(self, gid, sid, did, scid, tid, idx=None):
+ """
+ This function will return list of collation available
+ via AJAX response
+ """
+ res = []
+ try:
+ SQL = render_template(
+ "/".join([self.template_path, 'get_collations.sql'])
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['collation'],
+ 'value': row['collation']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_access_methods(self, gid, sid, did, scid, tid, idx=None):
+ """
+ This function will return list of access methods available
+ via AJAX response
+ """
+ res = []
+ try:
+ SQL = render_template("/".join([self.template_path, 'get_am.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['amname'],
+ 'value': row['amname']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_op_class(self, gid, sid, did, scid, tid, idx=None):
+ """
+ This function will return list of op_class method
+ for each access methods available via AJAX response
+ """
+ res = dict()
+ try:
+ # Fetching all the access methods
+ SQL = render_template("/".join([self.template_path, 'get_am.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ # Fetching all the op_classes for each access method
+ SQL = render_template(
+ "/".join([self.template_path, 'get_op_class.sql']),
+ oid=row['oid']
+ )
+ status, result = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ op_class_list = []
+
+ for r in result['rows']:
+ op_class_list.append({'label': r['opcname'],
+ 'value': r['opcname']})
+
+ # Append op_class list in main result as collection
+ res[row['amname']] = op_class_list
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the schema nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available schema nodes
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]), tid=tid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, idx):
+ """
+ This function will used to create all the child node within that
+ collection. Here it will create all the schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+
+ Returns:
+ JSON of available schema child nodes
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]),
+ tid=tid, idx=idx,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-index"
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function will used to create all the child node within that
+ collection. Here it will create all the schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available schema child nodes
+ """
+ res = []
+ SQL = render_template(
+ "/".join([self.template_path, self._NODES_SQL]), tid=tid,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-index",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, idx):
+ """
+ This function will show the properties of the selected schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+
+ Returns:
+ JSON of selected schema node
+ """
+ status, data = self._fetch_properties(did, tid, idx)
+ if not status:
+ return data
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ def _fetch_properties(self, did, tid, idx):
+ """
+ This function is used to fetch the properties of specified object.
+ :param did:
+ :param tid:
+ :param idx:
+ :return:
+ """
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+
+ # Add column details for current index
+ data = index_utils.get_column_details(self.conn, idx, data)
+
+ # Add Include details of the index
+ if self.manager.version >= 110000:
+ data = index_utils.get_include_details(self.conn, idx, data)
+
+ return True, data
+
+ @staticmethod
+ def _check_for_error(required_args, data):
+ """
+ This function is used to check for any error.
+ :param required_args:
+ :param data:
+ :return:
+ """
+ for arg in required_args:
+ err_msg = None
+ if arg == 'columns' and len(data['columns']) < 1:
+ err_msg = gettext("You must provide one or more column to "
+ "create index.")
+
+ if arg not in data:
+ err_msg = gettext("Could not find the required parameter ({})"
+ ".").format(required_args[arg])
+ # Check if we have at least one column
+ if err_msg is not None:
+ return True, err_msg
+ return False, ''
+
+ def end_transaction(self, data):
+ """
+ This function is used to end the transaction
+ """
+ if hasattr(data, "isconcurrent") and not data['isconcurrent']:
+ self.conn.execute_scalar("END;")
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will create the new index object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ required_args = {
+ 'columns': 'Columns'
+ }
+
+ is_error, err_msg = IndexesView._check_for_error(required_args, data)
+ if is_error:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(err_msg)
+ )
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+ data["storage_parameters"] = {}
+
+ storage_params = index_utils.get_storage_params(data['amname'])
+
+ for param in storage_params:
+ if param in data and data[param] != '':
+ data["storage_parameters"].update({param: data[param]})
+
+ if len(data['table']) == 0:
+ return gone(gettext(self.not_found_error_msg('Table')))
+
+ try:
+ # If user chooses concurrent index then we cannot run it inside
+ # a transaction block.
+ # Don't start transaction if isconcurrent is True
+ if hasattr(data, "isconcurrent") and not data['isconcurrent']:
+ # Start transaction.
+ self.conn.execute_scalar("BEGIN;")
+ SQL = render_template(
+ "/".join([self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn, mode='create'
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ # End transaction.
+ self.end_transaction(data)
+ return internal_server_error(errormsg=res)
+
+ # If user chooses concurrent index then we cannot run it along
+ # with other alter statements so we will separate alter index part
+ SQL = render_template(
+ "/".join([self.template_path, self._ALTER_SQL]),
+ data=data, conn=self.conn
+ )
+ SQL = SQL.strip('\n').strip(' ')
+ if SQL != '':
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ self.end_transaction(data)
+ return internal_server_error(errormsg=res)
+
+ # we need oid to add object in tree at browser
+ idx = 0
+ if data.get('name', '') == "":
+ SQL = render_template(
+ "/".join([self.template_path, 'get_oid_name.sql']),
+ tid=tid, conn=self.conn
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ self.end_transaction(data)
+ return internal_server_error(errormsg=tid)
+
+ if 'rows' in res and len(res['rows']) > 0:
+ data['name'] = res['rows'][0]['relname']
+ idx = res['rows'][0]['oid']
+ else:
+ SQL = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid, data=data, conn=self.conn
+ )
+ status, idx = self.conn.execute_scalar(SQL)
+ if not status:
+ self.end_transaction(data)
+ return internal_server_error(errormsg=tid)
+
+ self.end_transaction(data)
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ idx,
+ tid,
+ data['name'],
+ icon="icon-index"
+ )
+ )
+ except Exception as e:
+ self.end_transaction(data)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will updates the existing schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+ """
+ idx = kwargs.get('idx', None)
+ only_sql = kwargs.get('only_sql', False)
+
+ if idx is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [idx]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for idx in data['ids']:
+ # We will first fetch the index name for current request
+ # so that we create template for dropping index
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ data = dict(res['rows'][0])
+
+ SQL = render_template(
+ "/".join([self.template_path, self._DELETE_SQL]),
+ data=data, conn=self.conn, cascade=cascade
+ )
+
+ if only_sql:
+ return SQL
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Index is dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, idx):
+ """
+ This function will updates the existing schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ data['schema'] = self.schema
+ data['table'] = self.table
+ try:
+ SQL, name = index_utils.get_sql(
+ self.conn, data=data, did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_sys_objects=self.blueprint.show_system_objects)
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ idx,
+ tid,
+ name,
+ icon="icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, idx=None):
+ """
+ This function will generates modified sql for schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID (When working with existing index)
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ if data.get('amname', None):
+ data["storage_parameters"] = {}
+
+ storage_params = index_utils.get_storage_params(data['amname'])
+
+ for param in storage_params:
+ if param in data and data[param] != '':
+ data["storage_parameters"].update({param: data[param]})
+
+ try:
+ sql, _ = index_utils.get_sql(
+ self.conn, data=data, did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID, mode='create',
+ show_sys_objects=self.blueprint.show_system_objects)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, idx):
+ """
+ This function will generates reverse engineered sql for schema object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+ """
+
+ SQL = index_utils.get_reverse_engineered_sql(
+ self.conn, schema=self.schema, table=self.table, did=did,
+ tid=tid, idx=idx, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ add_not_exists_clause=True,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def get_sql_from_index_diff(self, **kwargs):
+ """
+ This function get the sql from index diff.
+ :param kwargs:
+ :return:
+ """
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ idx = kwargs.get('idx')
+ data = kwargs.get('data', None)
+ target_schema = kwargs.get('target_schema', None)
+ drop_req = kwargs.get('drop_req', False)
+
+ sql = ''
+
+ if data:
+ data['schema'] = self.schema
+ data['nspname'] = self.schema
+ data['table'] = self.table
+
+ sql, _ = index_utils.get_sql(
+ self.conn, data=data, did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID, mode='create',
+ show_sys_objects=self.blueprint.show_system_objects)
+
+ sql = sql.strip('\n').strip(' ')
+
+ elif target_schema:
+ sql = index_utils.get_reverse_engineered_sql(
+ self.conn, schema=target_schema,
+ table=self.table, did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ template_path=None, with_header=False,
+ add_not_exists_clause=True,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ drop_sql = ''
+ if drop_req:
+ drop_sql = '\n' + self.delete(gid=1, sid=sid, did=did,
+ scid=scid, tid=tid,
+ idx=idx, only_sql=True)
+
+ if drop_sql != '':
+ sql = drop_sql + '\n\n' + sql
+ return sql
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, idx):
+ """
+ This function get the dependents and return ajax response
+ for the schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, idx
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, idx):
+ """
+ This function get the dependencies and return ajax response
+ for the schema node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ idx: Index ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, idx
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, tid, idx=None):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ tid: Table Id
+ idx: Index Id
+
+ Returns the statistics for a particular object if idx is specified
+ else return all indexes
+ """
+
+ if idx is not None:
+ # Individual index
+
+ # Check if pgstattuple extension is already created?
+ # if created then only add extended stats
+ status, is_pgstattuple = self.conn.execute_scalar("""
+ SELECT (pg_catalog.count(extname) > 0) AS is_pgstattuple
+ FROM pg_catalog.pg_extension
+ WHERE extname='pgstattuple'
+ """)
+ if not status:
+ return internal_server_error(errormsg=is_pgstattuple)
+
+ if is_pgstattuple:
+ # Fetch index details only if extended stats available
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ did=did, tid=tid, idx=idx,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = dict(res['rows'][0])
+ index = data['name']
+ else:
+ index = None
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'stats.sql']),
+ conn=self.conn, schema=self.schema,
+ index=index, idx=idx, is_pgstattuple=is_pgstattuple
+ )
+ )
+
+ else:
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'coll_stats.sql']),
+ conn=self.conn, schema=self.schema,
+ table=self.table
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, oid=None):
+ """
+ This function will fetch the list of all the indexes for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param oid: Index Id
+ :return:
+ """
+
+ res = dict()
+
+ if not oid:
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid,
+ schema_diff=True)
+ status, indexes = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(indexes)
+ return False
+
+ for row in indexes['rows']:
+ status, data = self._fetch_properties(did, tid,
+ row['oid'])
+ if status:
+ res[row['name']] = data
+ else:
+ status, data = self._fetch_properties(did, tid,
+ oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+ res = data
+
+ return res
+
+ @staticmethod
+ def _check_for_create_req(required_create_keys, diff_dict):
+ """
+ This function is used to check whether create required or not.
+ :param required_create_keys:
+ :param diff_dict:
+ :return:
+ """
+ create_req = False
+ for key in required_create_keys:
+ if key in diff_dict and \
+ ((key == 'columns' and
+ (('added' in diff_dict[key] and
+ len(diff_dict[key]['added']) > 0) or
+ ('changed' in diff_dict[key] and
+ len(diff_dict[key]['changed']) > 0) or
+ ('deleted' in diff_dict[key] and
+ len(diff_dict[key]['deleted']) > 0))) or
+ key != 'columns'):
+ create_req = True
+ return create_req
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ src_params = kwargs.get('source_params')
+ tgt_params = kwargs.get('target_params')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ comp_status = kwargs.get('comp_status')
+ tgt_schema = kwargs.get('target_schema', None)
+
+ diff = ''
+ if comp_status == 'source_only':
+ diff = self.get_sql_from_index_diff(sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ idx=source['oid'],
+ target_schema=tgt_schema)
+ elif comp_status == 'target_only':
+ diff = self.delete(gid=1, sid=tgt_params['sid'],
+ did=tgt_params['did'], scid=tgt_params['scid'],
+ tid=tgt_params['tid'], idx=target['oid'],
+ only_sql=True)
+
+ elif comp_status == 'different':
+ diff_dict = directory_diff(
+ source, target, ignore_keys=self.keys_to_ignore,
+ difference={}
+ )
+
+ required_create_keys = ['columns']
+
+ create_req = IndexesView._check_for_create_req(
+ required_create_keys,
+ diff_dict
+ )
+
+ if create_req:
+ diff = self.get_sql_from_index_diff(sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ idx=source['oid'],
+ target_schema=tgt_schema,
+ drop_req=True)
+ else:
+ diff = self.get_sql_from_index_diff(sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ idx=target['oid'],
+ data=diff_dict)
+
+ return diff
+
+
+SchemaDiffRegistry(blueprint.node_type, IndexesView, 'table')
+IndexesView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/coll-index.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/coll-index.svg
new file mode 100644
index 0000000000000000000000000000000000000000..177866243a86dc99057f8b2e51bfff02c0d2a877
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/coll-index.svg
@@ -0,0 +1 @@
+coll-index
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/index.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/index.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3cc6d8fdf9b7113ce90542562f03bce8d14b8f5e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/img/index.svg
@@ -0,0 +1 @@
+index
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..9abcc95b5189388cc8464f204a928f6f2f811b6c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.js
@@ -0,0 +1,149 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import IndexSchema from './index.ui';
+import { getNodeAjaxOptions, getNodeListByName } from 'pgbrowser/node_ajax';
+import _ from 'lodash';
+
+define('pgadmin.node.index', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-index']) {
+ pgAdmin.Browser.Nodes['coll-index'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'index',
+ label: gettext('Indexes'),
+ type: 'coll-index',
+ columns: ['name', 'description'],
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Size'), gettext('Index size')],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['index']) {
+ pgAdmin.Browser.Nodes['index'] = pgBrowser.Node.extend({
+ parent_type: ['table', 'view', 'mview', 'partition'],
+ collection_type: ['coll-table', 'coll-view'],
+ sqlAlterHelp: 'sql-alterindex.html',
+ sqlCreateHelp: 'sql-createindex.html',
+ dialogHelp: url_for('help.static', {'filename': 'index_dialog.html'}),
+ type: 'index',
+ label: gettext('Index'),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ width: pgBrowser.stdW.lg + 'px',
+ statsPrettifyFields: [gettext('Size'), gettext('Index size')],
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_index_on_coll', node: 'coll-index', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Index...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_index', node: 'index', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Index...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_index_onTable', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Index...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_index_onPartition', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Index...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_index_onMatView', node: 'mview', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Index...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ ]);
+ },
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ // Below function will enable right click menu for creating column
+ canCreate: function(itemData, item, data) {
+ // If check is false then , we will allow create menu
+ if (data && !data.check)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData, parents = [],
+ immediate_parent_table_found = false,
+ is_immediate_parent_table_partitioned = false,
+ s_version = t.getTreeNodeHierarchy(i).server.version;
+ // To iterate over tree to check parent node
+ while (i) {
+ // Do not allow creating index on partitioned tables.
+ if (!immediate_parent_table_found &&
+ _.indexOf(['table', 'partition'], d._type) > -1) {
+ immediate_parent_table_found = true;
+ if ('is_partitioned' in d && d.is_partitioned && s_version < 110000) {
+ is_immediate_parent_table_partitioned = true;
+ }
+ }
+
+ // If it is schema then allow user to create index
+ if (_.indexOf(['schema'], d._type) > -1)
+ return !is_immediate_parent_table_partitioned;
+ parents.push(d._type);
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+ // If node is under catalog then do not allow 'create' menu
+ if (_.indexOf(parents, 'catalog') > -1) {
+ return false;
+ } else {
+ return !is_immediate_parent_table_partitioned;
+ }
+ },
+ getSchema: (treeNodeInfo, itemNodeData) => {
+ let nodeObj = pgAdmin.Browser.Nodes['index'];
+ return new IndexSchema(
+ {
+ tablespaceList: ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ }),
+ amnameList : ()=>getNodeAjaxOptions('get_access_methods', nodeObj, treeNodeInfo, itemNodeData, {jumpAfterNode: 'schema'}),
+ columnList: ()=>getNodeListByName('column', treeNodeInfo, itemNodeData, {}),
+ collationList: ()=>getNodeAjaxOptions('get_collations', nodeObj, treeNodeInfo, itemNodeData, {jumpAfterNode: 'schema'}),
+ opClassList: ()=>getNodeAjaxOptions('get_op_class', nodeObj, treeNodeInfo, itemNodeData, {jumpAfterNode: 'schema'})
+ },
+ {
+ node_info: treeNodeInfo
+ },
+ {
+ amname: 'btree',
+ deduplicate_items: treeNodeInfo.server.version >= 130000 ? true : undefined,
+ }
+ );
+ }
+ });
+ }
+
+ return pgBrowser.Nodes['index'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..f7c3edeebf51364a21673453f161677935a31e04
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/static/js/index.ui.js
@@ -0,0 +1,643 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import DataGridViewWithHeaderForm from '../../../../../../../../../static/js/helpers/DataGridViewWithHeaderForm';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import pgAdmin from 'sources/pgadmin';
+
+
+function inSchema(node_info) {
+ return node_info && 'catalog' in node_info;
+}
+
+class IndexColHeaderSchema extends BaseUISchema {
+ constructor(columns) {
+ super({
+ is_exp: true,
+ colname: undefined,
+ expression: undefined,
+ });
+
+ this.columns = columns;
+ }
+
+ changeColumnOptions(columns) {
+ this.columns = columns;
+ }
+
+ addDisabled(state) {
+ return !(state.is_exp ? state.expression : state.colname);
+ }
+
+ /* Data to IndexColumnSchema will be added using the header form */
+ getNewData(data) {
+ return this.indexColumnSchema.getNewData({
+ is_exp: data.is_exp,
+ colname: data.is_exp ? data.expression : data.colname,
+ });
+ }
+
+ get baseFields() {
+ return [{
+ id: 'is_exp', label: gettext('Is expression'), type:'switch', editable: false,
+ },{
+ id: 'colname', label: gettext('Column'), type: 'select', editable: false,
+ options: this.columns, deps: ['is_exp'],
+ optionsReloadBasis: this.columns?.map ? _.join(this.columns.map((c)=>c.label), ',') : null,
+ optionsLoaded: (res)=>this.columnOptions=res,
+ disabled: (state)=>state.is_exp, node: 'column',
+ },{
+ id: 'expression', label: gettext('Expression'), editable: false, deps: ['is_exp'],
+ type: 'sql', disabled: (state)=>!state.is_exp,
+ }];
+ }
+}
+
+class IndexColumnSchema extends BaseUISchema {
+ constructor(nodeData = {}) {
+ super({
+ colname: undefined,
+ is_exp: false,
+ op_class: undefined,
+ sort_order: false,
+ nulls: false,
+ is_sort_nulls_applicable: false,
+ collspcname:undefined
+ });
+ this.node_info = {
+ ...nodeData
+ };
+ this.operClassOptions = [];
+ this.collationOptions = [];
+ this.op_class_types = [];
+ }
+
+ setOpClassTypes(options) {
+ if(!options || (_.isArray(options) && options.length == 0))
+ return this.op_class_types;
+
+ if(this.op_class_types.length == 0)
+ this.op_class_types = options;
+ }
+
+ isEditable(state) {
+ let topObj = this._top;
+ if(this.inSchemaWithModelCheck(state)) {
+ return false;
+ } else if (topObj._sessData && topObj._sessData.amname === 'btree') {
+ state.is_sort_nulls_applicable = true;
+ return true;
+ } else {
+ state.is_sort_nulls_applicable = false;
+ }
+ return false;
+ }
+
+ setOperClassOptions(options) {
+ this.operClassOptions = options;
+ }
+
+ setCollationOptions(options) {
+ this.collationOptions = options;
+ }
+
+ getNewData(data) {
+ return {
+ ...super.getNewData(data),
+ };
+ }
+
+ // We will check if we are under schema node & in 'create' mode
+ inSchemaWithModelCheck(state) {
+ if(this.node_info && 'schema' in this.node_info) {
+ // We will disable control if it's in 'edit' mode
+ return !this.isNew(state);
+ }
+ return true;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'is_exp', label: '', type:'', cell: '', editable: false, width: 20,
+ disableResizing: true,
+ controlProps: {
+ formatter: {
+ fromRaw: function (rawValue) {
+ return rawValue ? 'E' : 'C';
+ },
+ }
+ }, visible: false,
+ },{
+ id: 'colname', label: gettext('Col/Exp'), type:'', editable: false,
+ cell:'', width: 100,
+ },{
+ id: 'op_class', label: gettext('Operator class'), tags: true, type: 'select',
+ cell: () => {
+ return {
+ cell: 'select',
+ options: obj.operClassOptions,
+ optionsLoaded: (options)=>{obj.setOpClassTypes(options);},
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ /* We need to extract data from collection according
+ * to access method selected by user if not selected
+ * send btree related op_class options
+ */
+ let amname = obj._top?._sessData ? obj._top?._sessData.amname : obj._top?._origData.amname;
+
+ if(_.isUndefined(amname))
+ return options;
+
+ _.each(obj.op_class_types, function(v, k) {
+ if(amname === k) {
+ options = v;
+ }
+ });
+ return options;
+ }
+ }
+ };
+ },
+ editable: function (state) {
+ return !obj.inSchemaWithModelCheck(state);
+ },
+ node: 'index',
+ url_jump_after_node: 'schema',
+ deps: ['amname'],
+ },{
+ id: 'sort_order', label: gettext('Sort order'), type: 'select', cell: 'select',
+ options: [
+ {label: 'ASC', value: false},
+ {label: 'DESC', value: true},
+ ],
+ width: 110, disableResizing: true,
+ controlProps: {
+ allowClear: false,
+ },
+ depChange: (state, source, topState, actionObj) => {
+ //Access method is empty or btree then do not disable field
+ if(isEmptyString(topState.amname) || topState.amname === 'btree') {
+ // We need to set nulls to true if sort_order is set to desc
+ // nulls first is default for desc
+ if(state.sort_order && !actionObj.oldState.sort_order) {
+ setTimeout(function() {
+ state.nulls = true;
+ }, 10);
+ }
+ }
+ else {
+ state.is_sort_nulls_applicable = false;
+ }
+ },
+ editable: function(state) {
+ return obj.isEditable(state);
+ },
+ deps: ['amname'],
+ },{
+ id: 'nulls', label: gettext('NULLs'), type:'select', cell: 'select',
+ options: [
+ {label: 'FIRST', value: true},
+ {label: 'LAST', value: false},
+ ], controlProps: {allowClear: false},
+ width: 110, disableResizing: true,
+ editable: function(state) {
+ return obj.isEditable(state);
+ },
+ deps: ['amname', 'sort_order'],
+ },{
+ id: 'collspcname', label: gettext('Collation'),
+ type: 'select',
+ cell: 'select',
+ disabled: () => inSchema(obj.node_info),
+ editable: function (state) {
+ return !obj.inSchemaWithModelCheck(state);
+ },
+ options: obj.collationOptions,
+ node: 'index',
+ url_jump_after_node: 'schema',
+ },{
+ id: 'statistics', label: gettext('Statistics'),
+ type: 'int', cell: 'int', disabled: (state)=> {
+ return (!state.is_exp || obj.node_info.server.version < 110000);
+ },
+ min: -1, max: 10000, mode: ['edit','properties'],
+ }
+ ];
+ }
+}
+
+export class WithSchema extends BaseUISchema {
+ constructor(node_info) {
+ super({});
+ this.node_info = node_info;
+ }
+
+ get baseFields() {
+ let withSchemaObj = this;
+ return [
+ {
+ id: 'fillfactor', label: gettext('Fill factor'), deps: ['amname'], cell: 'string',
+ type: 'int', disabled: (state) => {
+ return !_.includes(['btree', 'hash', 'gist', 'spgist'], state.amname) || inSchema(withSchemaObj.node_info);
+ },
+ mode: ['create', 'edit', 'properties'],
+ min: 10, max:100, group: gettext('Definition'),
+ depChange: state => {
+ if (!_.includes(['btree', 'hash', 'gist', 'spgist'], state.amname)) {
+ return {fillfactor: ''};
+ }
+ }
+ },{
+ id: 'gin_pending_list_limit', label: gettext('Gin pending list limit'), cell: 'string',
+ type: 'int', deps: ['amname'], disabled: state => state.amname !== 'gin' || inSchema(withSchemaObj.node_info),
+ mode: ['create', 'edit', 'properties'],
+ group: gettext('Definition'), min: 64, max: 2147483647,
+ depChange: state => {
+ if (state.amname !== 'gin') {
+ return {gin_pending_list_limit: ''};
+ }
+ }, helpMessage: gettext('This value is specified in kilobytes.')
+ },{
+ id: 'pages_per_range', label: gettext('Pages per range'), cell: 'string',
+ type: 'int', deps: ['amname'], disabled: state => state.amname !== 'brin' || inSchema(withSchemaObj.node_info),
+ mode: ['create', 'edit', 'properties'],
+ group: gettext('Definition'), depChange: state => {
+ if (state.amname !== 'brin') {
+ return {pages_per_range: ''};
+ }
+ }, helpMessage: gettext('Number of table blocks that make up one block range for each entry of a BRIN index.')
+ },{
+ id: 'buffering', label: gettext('Buffering'), cell: 'string', group: gettext('Definition'),
+ type: 'select', deps: ['amname'], mode: ['create', 'edit', 'properties'], options: [
+ {
+ label: gettext('Auto'),
+ value: 'auto',
+ },
+ {
+ label: gettext('On'),
+ value: 'on',
+ },
+ {
+ label: gettext('Off'),
+ value: 'off',
+ }], disabled: state => state.amname !== 'gist' || inSchema(withSchemaObj.node_info),
+ depChange: (state, source) => {
+ if (state.amname !== 'gist') {
+ return {buffering: ''};
+ } else if (state.amname === 'gist' && source[0] !== 'buffering') {
+ return {buffering: 'auto'};
+ }
+ }
+ },{
+ id: 'deduplicate_items', label: gettext('Deduplicate items?'), cell: 'string',
+ type: 'switch', deps:['amname'], mode: ['create', 'edit', 'properties'], disabled: (state) => {
+ return state.amname !== 'btree' || inSchema(withSchemaObj.node_info);
+ },
+ depChange: (state, source) => {
+ if (state.amname !== 'btree') {
+ return {deduplicate_items:undefined};
+ } else if (state.amname === 'btree' && source[0] !== 'deduplicate_items' &&
+ withSchemaObj.node_info.server.version >= 130000) {
+ return {deduplicate_items: true};
+ }
+ }, min_version: 130000,
+ group: gettext('Definition'),
+ },{
+ id: 'fastupdate', label: gettext('Fast update?'), cell: 'string',
+ type: 'switch', deps:['amname'], mode: ['create', 'edit', 'properties'], disabled: (state) => {
+ return state.amname !== 'gin' || inSchema(withSchemaObj.node_info);
+ },
+ depChange: (state, source) => {
+ if (state.amname !== 'gin') {
+ return {fastupdate:undefined};
+ } else if (state.amname === 'gin' && source[0] !== 'fastupdate') {
+ return {fastupdate: true};
+ }
+ },
+ group: gettext('Definition'),
+ },{
+ id: 'autosummarize', label: gettext('Autosummarize?'), cell: 'string',
+ type: 'switch', deps:['amname'], mode: ['create', 'edit', 'properties'], disabled: state => {
+ return state.amname !== 'brin' || inSchema(withSchemaObj.node_info);
+ }, group: gettext('Definition'),
+ depChange: (state) => {
+ if (state.amname !== 'brin') {
+ return {autosummarize:undefined};
+ }
+ }
+ }
+ ];
+ }
+}
+
+export default class IndexSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, nodeData = {}, initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ description: '',
+ is_sys_obj: false,
+ nspname: undefined,
+ tabname: undefined,
+ spcname: undefined,
+ amname: undefined,
+ fastupdate: false,
+ autosummarize: false,
+ columns: [],
+ ...initValues
+ });
+ this.fieldOptions = {
+ tablespaceList: [],
+ amnameList: [],
+ columnList: [],
+ opClassList: [],
+ collationList: [],
+ ...fieldOptions
+ };
+ this.node_info = {
+ ...nodeData.node_info
+ };
+ this.indexHeaderSchema = new IndexColHeaderSchema(this.fieldOptions.columnList);
+ this.indexColumnSchema = new IndexColumnSchema(this.node_info);
+ this.indexHeaderSchema.indexColumnSchema = this.indexColumnSchema;
+ this.withSchema = new WithSchema(this.node_info);
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ initialise() {
+ this.indexColumnSchema.setOperClassOptions(this.fieldOptions.opClassList);
+ this.indexColumnSchema.setCollationOptions(this.fieldOptions.collationList);
+ }
+
+ changeColumnOptions(columns) {
+ this.indexHeaderSchema.changeColumnOptions(columns);
+ this.fieldOptions.columns = columns;
+ }
+
+ getColumns() {
+ return {
+ type: 'select',
+ options: this.fieldOptions.columnList,
+ optionsLoaded: (options) => { this.fieldOptions.columnList = options; },
+ controlProps: {
+ allowClear: false,
+ multiple: true,
+ placeholder: gettext('Select the column(s)'),
+ width: 'style',
+ filter: (options) => {
+ let res = [];
+ if (options && _.isArray(options)) {
+ _.each(options, function(d) {
+ if(d.label != '')
+ res.push({label: d.label, value: d.value, image:'icon-column'});
+ });
+ }
+ return res;
+ }
+ }
+ };
+ }
+
+ isVisible() {
+ return (!_.isUndefined(this.node_info) && !_.isUndefined(this.node_info.server)
+ && !_.isUndefined(this.node_info.server.version) &&
+ this.node_info.server.version >= 110000);
+ }
+
+ get baseFields() {
+ let indexSchemaObj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text',
+ disabled: () => inSchema(indexSchemaObj.node_info),
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'int', readonly: true, mode: ['properties'],
+ },{
+ id: 'spcname', label: gettext('Tablespace'), cell: 'string',
+ node: 'tablespace',
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => inSchema(indexSchemaObj.node_info),
+ type: 'select',
+ options: indexSchemaObj.fieldOptions.tablespaceList,
+ controlProps: { allowClear: true },
+ },{
+ id: 'amname', label: gettext('Access Method'), cell: 'string',
+ mode: ['properties', 'create', 'edit'], noEmpty: true,
+ disabled: () => inSchema(indexSchemaObj.node_info),
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ group: gettext('Definition'),
+ type: () => {
+ return {
+ type: 'select',
+ options: indexSchemaObj.fieldOptions.amnameList,
+ optionsLoaded: (options) => { indexSchemaObj.fieldOptions.amnameList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ let res = [];
+ if (options && _.isArray(options)) {
+ _.each(options, function(d) {
+ if(d.label != '')
+ res.push({label: d.label, value: d.value, data:d});
+ });
+ }
+ return res;
+ }
+ }
+ };
+ },
+ deferredDepChange: (state, source, topState, actionObj) => {
+ const setColumns = (resolve)=>{
+ resolve(()=>{
+ state.columns.splice(0, state.columns?.length);
+ return {
+ columns: state.columns,
+ };
+ });
+ };
+ if((state.amname != actionObj?.oldState.amname) && state.columns?.length > 0) {
+ return new Promise((resolve)=>{
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Warning'),
+ gettext('Changing access method will clear columns collection. Do you want to continue?'),
+ function () {
+ setColumns(resolve);
+ },
+ function() {
+ resolve(()=>{
+ state.amname = actionObj?.oldState.amname;
+ return {
+ amname: state.amname,
+ };
+ });
+ }
+ );
+ });
+ } else {
+ return Promise.resolve(()=>{/*This is intentional (SonarQube)*/});
+ }
+ },
+ },{
+ type: 'nested-fieldset', label: gettext('With'), group: gettext('Definition'),
+ schema: this.withSchema,
+ },{
+ id: 'indisunique', label: gettext('Unique?'), cell: 'string',
+ type: 'switch', deps:['amname'], disabled: (state) => {
+ return state.amname !== 'btree' || inSchema(indexSchemaObj.node_info);
+ },
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ depChange: (state) => {
+ if (state.amname !== 'btree') {
+ return {indisunique:false};
+ }
+ },
+ group: gettext('Definition'),
+ },{
+ id: 'indnullsnotdistinct', label: gettext('NULLs not distinct?'), cell: 'string',
+ type: 'switch', deps:['indisunique', 'amname'], disabled: (state) => {
+ return !state.indisunique || inSchema(indexSchemaObj.node_info);
+ },
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ depChange: (state) => {
+ if (!state.indisunique) {
+ return {indnullsnotdistinct:false};
+ }
+ },
+ min_version: 150000,
+ group: gettext('Definition'),
+ },{
+ id: 'indisclustered', label: gettext('Clustered?'), cell: 'string',
+ type: 'switch', group: gettext('Definition'), deps: ['name'],
+ disabled: function (state) {
+ return isEmptyString(state.name) || inSchema(indexSchemaObj.node_info);
+ },
+ depChange: (state)=>{
+ if(isEmptyString(state.name)) {
+ return {indisclustered: false};
+ }
+ }
+ },{
+ id: 'indisvalid', label: gettext('Valid?'), cell: 'string',
+ type: 'switch', mode: ['properties'],
+ group: gettext('Definition'),
+ },{
+ id: 'indisprimary', label: gettext('Primary?'), cell: 'string',
+ type: 'switch', mode: ['properties'],
+ group: gettext('Definition'),
+ },{
+ id: 'is_sys_idx', label: gettext('System index?'), cell: 'string',
+ type: 'switch', mode: ['properties'],
+ },{
+ id: 'isconcurrent', label: gettext('Concurrent build?'), cell: 'string',
+ type: 'switch', disabled: () => inSchema(indexSchemaObj.node_info),
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ mode: ['create'], group: gettext('Definition'),
+ },{
+ id: 'indconstraint', label: gettext('Constraint'), cell: 'string',
+ type: 'sql', controlProps: {className:['custom_height_css_class']},
+ disabled: () => inSchema(indexSchemaObj.node_info),
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ mode: ['create', 'edit'],
+ control: 'sql-field', visible: true, group: gettext('Definition'),
+ },{
+ id: 'columns', label: gettext('Columns/Expressions'),
+ group: gettext('Columns'), type: 'collection',
+ mode: ['create', 'edit', 'properties'],
+ editable: false, schema: this.indexColumnSchema,
+ headerSchema: this.indexHeaderSchema, headerVisible: (state)=>indexSchemaObj.isNew(state),
+ CustomControl: DataGridViewWithHeaderForm,
+ uniqueCol: ['colname'],
+ canAdd: false, canDelete: function(state) {
+ // We can't update columns of existing
+ return indexSchemaObj.isNew(state);
+ }, cell: ()=>({
+ cell: '',
+ controlProps: {
+ formatter: {
+ fromRaw: (rawValue)=>{
+ return _.map(rawValue || [], 'colname').join(', ');
+ },
+ }
+ },
+ width: 245,
+ })
+ },{
+ id: 'include', label: gettext('Include columns'),
+ type: () => {
+ return indexSchemaObj.getColumns();
+ },
+ group: gettext('Columns'),
+ editable: false,
+ canDelete: true, canAdd: true, mode: ['edit', 'create', 'properties'],
+ disabled: () => inSchema(indexSchemaObj.node_info),
+ readonly: function (state) {
+ return !indexSchemaObj.isNew(state);
+ },
+ visible: function() {
+ return indexSchemaObj.isVisible();
+ },
+ node:'column',
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ deps: ['name'],
+ disabled: function (state) {
+ return isEmptyString(state.name) || inSchema(indexSchemaObj.node_info);
+ },
+ depChange: (state)=>{
+ if(isEmptyString(state.name)) {
+ return {comment: ''};
+ }
+ }
+ },
+ ];
+ }
+
+ validate(state, setError) {
+ let msg;
+
+ if (!this.isNew(state) && isEmptyString(state.name)) {
+ msg = gettext('Name cannot be empty in edit mode.');
+ setError('name', msg);
+ return true;
+ } else {
+ setError('name', null);
+ }
+
+ // Checks if columns is empty
+ let cols = state.columns;
+ if(_.isArray(cols) && cols.length == 0){
+ msg = gettext('You must specify at least one column/expression.');
+ setError('columns', msg);
+ return true;
+ }
+ return null;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..94bd178f6f3e9a649b350fc3a97d07249031aa8c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/indexes/utils.py
@@ -0,0 +1,404 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Indexes. """
+
+from flask import render_template
+from flask_babel import gettext
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+AUTO_CREATE_INDEX_MSG = "-- This constraint index is automatically " \
+ "generated from a constraint with an identical name.\n-- " \
+ "For more details, refer to the Constraints node. Note that this type " \
+ "of index is only visible \n-- when the 'Show system objects?' is set " \
+ "to True in the Preferences.\n\n"
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs or kwargs['template_path'] is None:
+ kwargs['template_path'] = \
+ 'indexes/sql/#{0}#'.format(conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+def _get_column_property_display_data(row, col_str, data):
+ """
+ This function is used to get the columns data.
+ :param row:
+ :param col_str:
+ :param data:
+ :return:
+ """
+ if row['collnspname']:
+ col_str += ' COLLATE ' + row['collnspname']
+ if row['opcname']:
+ col_str += ' ' + row['opcname']
+
+ # ASC/DESC and NULLS works only with btree indexes
+ if 'amname' in data and data['amname'] == 'btree':
+ # Append sort order
+ col_str += ' ' + row['options'][0]
+ # Append nulls value
+ col_str += ' ' + row['options'][1]
+
+ return col_str
+
+
+@get_template_path
+def get_column_details(conn, idx, data, mode='properties', template_path=None):
+ """
+ This functional will fetch list of column for index.
+
+ :param conn: Connection Object
+ :param idx: Index ID
+ :param data: Data
+ :param mode: 'create' or 'properties'
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template(
+ "/".join([template_path, 'column_details.sql']), idx=idx
+ )
+ status, rset = conn.execute_2darray(SQL)
+ # Remove column if duplicate column is present in list.
+ rset['rows'] = [i for n, i in enumerate(rset['rows']) if
+ i not in rset['rows'][n + 1:]]
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # 'attdef' comes with quotes from query so we need to strip them
+ # 'options' we need true/false to render switch ASC(false)/DESC(true)
+ columns = []
+ cols = []
+ for row in rset['rows']:
+ # We need all data as collection for ColumnsModel
+ # we will not strip down colname when using in SQL to display
+ cols_data = {
+ 'colname': row['attdef'] if mode == 'create' else
+ row['attdef'].strip('"'),
+ 'collspcname': row['collnspname'],
+ 'op_class': row['opcname'],
+ 'col_num': row['attnum'],
+ 'is_exp': row['is_exp'],
+ 'statistics': row['statistics']
+ }
+
+ # ASC/DESC and NULLS works only with btree indexes
+ if 'amname' in data and data['amname'] == 'btree':
+ cols_data['sort_order'] = False
+ if row['options'][0] == 'DESC':
+ cols_data['sort_order'] = True
+
+ cols_data['nulls'] = False
+ if row['options'][1].split(" ")[1] == 'FIRST':
+ cols_data['nulls'] = True
+
+ columns.append(cols_data)
+
+ # We need same data as string to display in properties window
+ # If multiple column then separate it by colon
+ cols_str = ''
+ cols_str += _get_column_property_display_data(row, row['attdef'], data)
+
+ cols.append(cols_str)
+
+ # Push as collection
+ data['columns'] = columns
+ # Push as string
+ data['columns_csv'] = ', '.join(cols)
+
+ return data
+
+
+@get_template_path
+def get_include_details(conn, idx, data, template_path=None):
+ """
+ This functional will fetch list of include details for index
+ supported with Postgres 11+
+
+ :param conn: Connection object
+ :param idx: Index ID
+ :param data: data
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template(
+ "/".join([template_path, 'include_details.sql']), idx=idx
+ )
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Push as collection
+ data['include'] = [col['colname'] for col in rset['rows']]
+
+ return data
+
+
+def _get_create_sql(data, template_path, conn, mode, name,
+ if_exists_flag=False):
+ """
+ This function is used to get the sql where index is None
+ :param data:
+ :param template_path:
+ :param conn:
+ :param mode:
+ :param name:
+ :return:
+ """
+ required_args = {
+ 'columns': 'Columns'
+ }
+ for arg in required_args:
+ err = False
+ if arg == 'columns' and len(data['columns']) < 1:
+ err = True
+
+ if arg not in data:
+ err = True
+ # Check if we have at least one column
+ if err:
+ return gettext('-- definition incomplete'), name
+
+ # If the request for new object which do not have did
+ sql = render_template(
+ "/".join([template_path, 'create.sql']),
+ data=data, conn=conn, mode=mode,
+ add_not_exists_clause=if_exists_flag
+ )
+ sql += "\n"
+
+ sql += render_template(
+ "/".join([template_path, 'alter.sql']),
+ data=data, conn=conn
+ )
+ return sql
+
+
+@get_template_path
+def get_sql(conn, **kwargs):
+ """
+ This function will generate sql from model data.
+
+ :param conn: Connection Object
+ :param kwargs:
+ :return:
+ """
+
+ data = kwargs.get('data')
+ did = kwargs.get('did')
+ tid = kwargs.get('tid')
+ idx = kwargs.get('idx')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ mode = kwargs.get('mode', None)
+ template_path = kwargs.get('template_path', None)
+ if_exists_flag = kwargs.get('if_exists_flag', False)
+ show_sys_obj = kwargs.get('show_sys_objects', False)
+
+ name = data['name'] if 'name' in data else None
+ if idx is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, idx=idx,
+ datlastsysoid=datlastsysoid,
+ show_sys_objects=show_sys_obj)
+
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(gettext('Could not find the index in the table.'))
+
+ old_data = dict(res['rows'][0])
+
+ # Add column details for current index
+ old_data = get_column_details(conn, idx, old_data)
+
+ update_column_data, update_column = \
+ _get_column_details_to_update(old_data, data)
+ # Remove opening and closing bracket as we already have in jinja
+ # template.
+ if 'using' in old_data and old_data['using'] is not None and \
+ old_data['using'].startswith('(') and \
+ old_data['using'].endswith(')'):
+ old_data['using'] = old_data['using'][1:-1]
+ if 'withcheck' in old_data and old_data['withcheck'] is not None and \
+ old_data['withcheck'].startswith('(') and \
+ old_data['withcheck'].endswith(')'):
+ old_data['withcheck'] = old_data['withcheck'][1:-1]
+
+ # If name is not present in data then
+ # we will fetch it from old data, we also need schema & table name
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ sql = render_template(
+ "/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn,
+ update_column_data=update_column_data, update_column=update_column
+ )
+ else:
+ sql = _get_create_sql(data, template_path, conn, mode, name,
+ if_exists_flag=if_exists_flag)
+
+ return sql, name
+
+
+@get_template_path
+def get_reverse_engineered_sql(conn, **kwargs):
+ """
+ This function will return reverse engineered sql for specified trigger.
+
+ :param conn: Connection Object
+ :param kwargs:
+ :return:
+ """
+ schema = kwargs.get('schema')
+ table = kwargs.get('table')
+ did = kwargs.get('did')
+ tid = kwargs.get('tid')
+ idx = kwargs.get('idx')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ template_path = kwargs.get('template_path', None)
+ with_header = kwargs.get('with_header', True)
+ if_exists_flag = kwargs.get('add_not_exists_clause', False)
+ show_sys_obj = kwargs.get('show_sys_objects', False)
+
+ SQL = render_template("/".join([template_path, 'properties.sql']),
+ did=did, tid=tid, idx=idx,
+ datlastsysoid=datlastsysoid,
+ show_sys_objects=show_sys_obj)
+
+ status, res = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(gettext('Could not find the index in the table.'))
+
+ data = dict(res['rows'][0])
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = schema
+ data['table'] = table
+ data["storage_parameters"] = {}
+
+ storage_params = get_storage_params(data['amname'])
+
+ for param in storage_params:
+ if (param in data) and (data[param] is not None):
+ data["storage_parameters"].update({param: data[param]})
+
+ # Add column details for current index
+ data = get_column_details(conn, idx, data, 'create')
+
+ # Add Include details of the index
+ if conn.manager.version >= 110000:
+ data = get_include_details(conn, idx, data)
+
+ SQL, _ = get_sql(conn, data=data, did=did, tid=tid, idx=None,
+ datlastsysoid=datlastsysoid,
+ if_exists_flag=if_exists_flag)
+
+ if with_header:
+ sql_header = ''
+ # Add a Note if index is automatically created.
+ if 'conname' in data and data['conname'] is not None:
+ sql_header += AUTO_CREATE_INDEX_MSG
+
+ sql_header += "-- Index: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([template_path, 'delete.sql']),
+ data=data, conn=conn)
+
+ SQL = sql_header + '\n\n' + SQL
+
+ return SQL
+
+
+def get_storage_params(amname):
+ """
+ This function will return storage parameters according to index type.
+
+ :param amname: access method name
+ :return:
+ """
+ storage_parameters = {
+ "btree": ["fillfactor", "deduplicate_items"],
+ "hash": ["fillfactor"],
+ "gist": ["fillfactor", "buffering"],
+ "gin": ["fastupdate", "gin_pending_list_limit"],
+ "spgist": ["fillfactor"],
+ "brin": ["pages_per_range", "autosummarize"],
+ "heap": [],
+ "ivfflat": ['lists']
+ }
+ return [] if amname not in storage_parameters else \
+ storage_parameters[amname]
+
+
+def _get_column_details_to_update(old_data, data):
+ """
+ This function returns the columns/expressions which need to update
+ :param old_data:
+ :param data:
+ :return:
+ """
+ update_column_data = []
+ update_column = False
+
+ if 'columns' in data and 'changed' in data['columns']:
+ for index, col1 in enumerate(old_data['columns']):
+ for col2 in data['columns']['changed']:
+ if col1['col_num'] == col2['col_num'] and col1['statistics'] \
+ != col2['statistics']:
+ update_column_data.append(col2)
+ update_column = True
+ break
+
+ return update_column_data, update_column
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c6b27b90910bb7de55c5222a121527ddc32463e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/__init__.py
@@ -0,0 +1,894 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Partitions Node """
+
+import re
+import secrets
+import json
+import pgadmin.browser.server_groups.servers.databases.schemas as schema
+from flask import render_template, request, current_app
+from flask_babel import gettext
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import DataTypeReader
+from pgadmin.utils.ajax import internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.utils \
+ import BaseTableView
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.utils.ajax import make_json_response
+from pgadmin.browser.utils import PGChildModule
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+def backend_supported(module, manager, **kwargs):
+
+ if CollectionNodeModule.backend_supported(module, manager, **kwargs):
+ if 'tid' not in kwargs:
+ return True
+
+ conn = manager.connection(did=kwargs['did'])
+
+ template_path = 'partitions/sql/{0}/#{0}#{1}#'.format(
+ manager.server_type, manager.version
+ )
+ SQL = render_template("/".join(
+ [template_path, 'backend_support.sql']), tid=kwargs['tid'])
+ status, res = conn.execute_scalar(SQL)
+
+ # check if any errors
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return res
+
+
+class PartitionsModule(CollectionNodeModule):
+ """
+ class PartitionsModule(CollectionNodeModule)
+
+ A module class for Partition node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Partition and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for schema, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'partition'
+ _COLLECTION_LABEL = gettext("Partitions")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the PartitionsModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = 100000
+ self.max_ver = None
+ self.min_ppasver = 100000
+ self.max_ppasver = None
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ yield self.generate_browser_collection_node(kwargs['tid'])
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return schema.SchemaModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return True
+
+ def backend_supported(self, manager, **kwargs):
+ """
+ Load this module if it is a partition table
+ """
+ return backend_supported(self, manager, **kwargs)
+
+ def register(self, app, options):
+ """
+ Override the default register function to automatically register
+ sub-modules of table node under partition table node.
+ """
+
+ self.submodules = []
+ super().register(app, options)
+
+ # Now add sub modules of table node to partition table node.
+ # Exclude 'partition' module for now to avoid cyclic import issue.
+ modules_to_skip = ['partition', 'column']
+ for parent in self.parentmodules:
+ if parent.node_type == 'table':
+ self.submodules += [
+ submodule for submodule in parent.submodules
+ if submodule.node_type not in modules_to_skip
+ ]
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ "partitions/css/partition.css",
+ node_type=self.node_type,
+ _=gettext
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+
+blueprint = PartitionsModule(__name__)
+
+
+class PartitionsView(BaseTableView, DataTypeReader, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Partition node
+
+ Methods:
+ -------
+
+ * list()
+ - This function is used to list all the Partition nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Partition node.
+
+ * properties(gid, sid, did, scid, tid, ptid)
+ - This function will show the properties of the selected Partition node
+
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Partition"
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'ptid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'nodes'}, {'get': 'nodes'}],
+ 'children': [{'get': 'children'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {}],
+ 'detach': [{'put': 'detach'}],
+ 'truncate': [{'put': 'truncate'}],
+ 'set_trigger': [{'put': 'enable_disable_triggers'}],
+ 'get_table_access_methods': [{}, {'get': 'get_table_access_methods'}],
+ })
+
+ # Schema Diff: Keys to ignore while comparing
+ keys_to_ignore = ['oid', 'schema', 'vacuum_table',
+ 'vacuum_toast', 'edit_types', 'oid-2']
+
+ def get_children_nodes(self, manager, **kwargs):
+ nodes = []
+ # treat partition table as normal table.
+ # replace tid with ptid and pop ptid from kwargs
+ if 'ptid' in kwargs:
+ ptid = kwargs.pop('ptid')
+ kwargs['tid'] = ptid
+
+ for module in self.blueprint.submodules:
+ if isinstance(module, PGChildModule):
+ if manager is not None and \
+ module.backend_supported(manager, **kwargs):
+ nodes.extend(module.get_nodes(**kwargs))
+ else:
+ nodes.extend(module.get_nodes(**kwargs))
+
+ if manager is not None and \
+ self.blueprint.backend_supported(manager, **kwargs):
+ nodes.extend(self.blueprint.get_nodes(**kwargs))
+
+ return nodes
+
+ @BaseTableView.check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the table nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available table nodes
+ """
+ SQL = render_template("/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def nodes(self, gid, sid, did, scid, tid, ptid=None):
+ """
+ This function is used to list all the table nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Parent Table ID
+ ptid: Partition Table ID
+
+ Returns:
+ JSON of available table nodes
+ """
+ SQL = render_template(
+ "/".join([self.partition_template_path, self._NODES_SQL]),
+ scid=scid, tid=tid, ptid=ptid, did=did
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ def browser_node(row):
+ icon = self.get_partition_icon_css_class(row)
+ return self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon=icon,
+ tigger_count=row['triggercount'],
+ has_enable_triggers=row['has_enable_triggers'],
+ is_partitioned=row['is_partitioned'],
+ parent_schema_id=scid,
+ schema_id=row['schema_id'],
+ schema_name=row['schema_name'],
+ description=row['description'],
+ is_detach_pending=row['inhdetachpending'] if 'inhdetachpending'
+ in row else False
+ )
+
+ if ptid is not None:
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ return make_json_response(
+ data=browser_node(rset['rows'][0]), status=200
+ )
+
+ res = []
+ for row in rset['rows']:
+ res.append(browser_node(row))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def properties(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will show the properties of the selected table node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+
+ Returns:
+ JSON of selected table node
+ """
+
+ status, res = self._fetch_properties(did, scid, tid, ptid)
+
+ if not status:
+ return res
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ return super().properties(
+ gid, sid, did, scid, ptid, res=res)
+
+ def _fetch_properties(self, did, scid, tid, ptid=None):
+
+ """
+ This function is used to fetch the properties of the specified object
+ :param did:
+ :param scid:
+ :param tid:
+ :return:
+ """
+ try:
+ SQL = render_template("/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ ptid=ptid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(
+ gettext(self.not_found_error_msg()))
+
+ # Update autovacuum properties
+ self.update_autovacuum_properties(res['rows'][0])
+
+ except Exception as e:
+ return False, internal_server_error(errormsg=str(e))
+
+ return True, res
+
+ @BaseTableView.check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, ptid=None):
+ """
+ This function will fetch the list of all the tables for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :param ptif: Partition table Id
+ :return:
+ """
+ res = {}
+
+ if ptid:
+ SQL = render_template("/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ ptid=ptid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, result = self.conn.execute_dict(SQL)
+ if not status:
+ current_app.logger.error(result)
+ return False
+
+ res = super().properties(
+ 0, sid, did, scid, ptid, result)
+
+ else:
+ SQL = render_template(
+ "/".join([self.partition_template_path, self._NODES_SQL]),
+ scid=scid, tid=tid, schema_diff=True
+ )
+ status, partitions = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(partitions)
+ return False
+
+ for row in partitions['rows']:
+ SQL = render_template(
+ "/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid, ptid=row['oid'],
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, result = self.conn.execute_dict(SQL)
+
+ if not status:
+ current_app.logger.error(result)
+ return False
+
+ data = super().properties(
+ 0, sid, did, scid, row['oid'], result, False
+ )
+ res[row['name']] = data
+
+ return res
+
+ @BaseTableView.check_precondition
+ def sql(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will creates reverse engineered sql for
+ the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+ """
+ main_sql = []
+
+ status, res = self._fetch_properties(did, scid, tid, ptid)
+
+ if not status:
+ return res
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data = res['rows'][0]
+
+ return BaseTableView.get_reverse_engineered_sql(
+ self, did=did, scid=scid, tid=ptid, main_sql=main_sql, data=data)
+
+ @BaseTableView.check_precondition
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements for
+ partitions.
+
+ :param kwargs:
+ :return:
+ """
+
+ source_data = kwargs['source_data'] if 'source_data' in kwargs \
+ else None
+ target_data = kwargs['target_data'] if 'target_data' in kwargs \
+ else None
+
+ # Store the original name and create a temporary name for
+ # the partitioned(base) table.
+ target_data['orig_name'] = target_data['name']
+ target_data['name'] = 'temp_partitioned_{0}'.format(
+ secrets.choice(range(1, 9999999)))
+ # For PG/EPAS 11 and above when we copy the data from original
+ # table to temporary table for schema diff, we will have to create
+ # a default partition to prevent the data loss.
+ target_data['default_partition_name'] = \
+ target_data['orig_name'] + '_default'
+
+ # Copy the partition scheme from source to target.
+ if 'partition_scheme' in source_data:
+ target_data['partition_scheme'] = source_data['partition_scheme']
+
+ partition_data = dict()
+ partition_data['name'] = target_data['name']
+ partition_data['schema'] = target_data['schema']
+ partition_data['partition_type'] = source_data['partition_type']
+ partition_data['default_partition_header'] = \
+ '-- Create a default partition to prevent the data loss.\n' \
+ '-- It helps when none of the partitions of a relation\n' \
+ '-- matches the inserted data.'
+
+ # Create temporary name for partitions
+ for item in source_data['partitions']:
+ item['temp_partition_name'] = 'partition_{0}'.format(
+ secrets.choice(range(1, 9999999)))
+
+ partition_data['partitions'] = source_data['partitions']
+
+ partition_sql = self.get_partitions_sql(partition_data,
+ schema_diff=True)
+
+ return render_template(
+ "/".join([self.partition_template_path, 'partition_diff.sql']),
+ conn=self.conn, data=target_data, partition_sql=partition_sql,
+ partition_data=partition_data
+ )
+
+ @BaseTableView.check_precondition
+ def detach(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will reset statistics of table
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ mode = data.get('mode')
+
+ # Fetch schema name
+ status, parent_schema = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_schema.sql']),
+ conn=self.conn, scid=scid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=parent_schema)
+
+ # Fetch Parent Table name
+ status, partitioned_table_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_table.sql']),
+ conn=self.conn, scid=scid, tid=tid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=partitioned_table_name)
+
+ # Get schema oid of partition
+ status, pscid = self.conn.execute_scalar(
+ render_template("/".join([self.table_template_path,
+ self._GET_SCHEMA_OID_SQL]), tid=ptid,
+ conn=self.conn))
+ if not status:
+ return internal_server_error(errormsg=scid)
+
+ # Fetch schema name
+ status, partition_schema = self.conn.execute_scalar(
+ render_template("/".join([self.table_template_path,
+ 'get_schema.sql']), conn=self.conn,
+ scid=pscid)
+ )
+ if not status:
+ return internal_server_error(errormsg=partition_schema)
+
+ # Fetch Partition Table name
+ status, partition_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_table.sql']),
+ conn=self.conn, scid=pscid, tid=ptid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=partition_name)
+
+ try:
+ temp_data = dict()
+ temp_data['parent_schema'] = parent_schema
+ temp_data['partitioned_table_name'] = partitioned_table_name
+ temp_data['schema'] = partition_schema
+ temp_data['name'] = partition_name
+ temp_data['mode'] = mode
+
+ SQL = render_template(
+ "/".join([self.partition_template_path, 'detach.sql']),
+ data=temp_data, conn=self.conn
+ )
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Partition detached."),
+ data={
+ 'id': ptid,
+ 'scid': scid
+ }
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def msql(self, gid, sid, did, scid, tid, ptid=None):
+ """
+ This function will create modified sql for table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ if ptid is not None:
+ status, res = self._fetch_properties(did, scid, tid, ptid)
+
+ if not status:
+ return res
+
+ SQL, _ = self.get_sql(did, scid, ptid, data, res)
+ SQL = re.sub('\n{2,}', '\n\n', SQL)
+ SQL = SQL.strip('\n')
+ if SQL == '':
+ SQL = "--modified SQL"
+ return make_json_response(
+ data=SQL,
+ status=200
+ )
+
+ @BaseTableView.check_precondition
+ def update(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will update an existing table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ try:
+ status, res = self._fetch_properties(did, scid, tid, ptid)
+
+ if not status:
+ return res
+
+ return super().update(
+ gid, sid, did, scid, ptid, data=data, res=res, parent_id=tid)
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def truncate(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will truncate the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+
+ try:
+ SQL = render_template("/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ ptid=ptid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return super().truncate(
+ gid, sid, did, scid, ptid, res
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def delete(self, gid, sid, did, scid, tid, ptid=None):
+ """
+ This function will delete the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+ """
+ if ptid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [ptid]}
+
+ try:
+ for ptid in data['ids']:
+ SQL = render_template(
+ "/".join([self.partition_template_path,
+ self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid, ptid=ptid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified partition could not be found.\n'
+ )
+ )
+
+ status, res = super().delete(
+ gid, sid, did, scid, tid, res)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Partition dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @BaseTableView.check_precondition
+ def enable_disable_triggers(self, gid, sid, did, scid, tid, ptid):
+ """
+ This function will enable/disable trigger(s) on the partition object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ # Convert str 'true' to boolean type
+ is_enable_trigger = data['is_enable_trigger']
+
+ try:
+ SQL = render_template(
+ "/".join([self.partition_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid, ptid=ptid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ data = res['rows'][0]
+
+ SQL = render_template(
+ "/".join([
+ self.table_template_path, 'enable_disable_trigger.sql'
+ ]),
+ data=data, is_enable_trigger=is_enable_trigger
+ )
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Trigger(s) have been disabled")
+ if is_enable_trigger == 'D'
+ else gettext("Trigger(s) have been enabled"),
+ data={
+ 'id': ptid,
+ 'scid': scid
+ }
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ tgt_params = kwargs.get('target_params')
+ parent_source_data = kwargs.get('parent_source_data')
+ parent_target_data = kwargs.get('parent_target_data')
+
+ diff = self.get_sql_from_diff(sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ source_data=parent_source_data,
+ target_data=parent_target_data)
+
+ return diff + '\n'
+
+ @BaseTableView.check_precondition
+ def get_table_access_methods(self, gid, sid, did, scid, tid, ptid=None):
+ """
+ This function returns access methods for table.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ ptid: Partition Table ID
+
+ Returns:
+ Returns list of access methods for partition table
+ """
+ res = BaseTableView.get_access_methods(self)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+
+SchemaDiffRegistry(blueprint.node_type, PartitionsView, 'table')
+PartitionsView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/coll-partition.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/coll-partition.svg
new file mode 100644
index 0000000000000000000000000000000000000000..37ea5b09c38646c04b48a35371173c3ffee59f37
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/coll-partition.svg
@@ -0,0 +1,35 @@
+
+
+
+
+partition
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition.svg
new file mode 100644
index 0000000000000000000000000000000000000000..1381dc4c155366c08698102369f3cbbdae0243e9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition.svg
@@ -0,0 +1 @@
+partition
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition_table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition_table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..c36929c0e9171873699cabc4729d8afcb62b88e8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/partition_table.svg
@@ -0,0 +1,23 @@
+
+
+
+
+inherits
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/sub_partition_table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/sub_partition_table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..93e214d5c139fb3833208d0a57469b3ecab4ec79
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/img/sub_partition_table.svg
@@ -0,0 +1,29 @@
+
+
+
+
+partition
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
new file mode 100644
index 0000000000000000000000000000000000000000..90e7f1440da05e0a1e0cc92b3b88c09714ff5408
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.js
@@ -0,0 +1,341 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodePartitionTableSchema } from './partition.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../../static/js/api_instance';
+
+define([
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'sources/utils',
+ 'pgadmin.browser.collection',
+],
+function(
+ gettext, url_for, pgAdmin, pgBrowser,
+ SchemaChildTreeNode, pgadminUtils
+) {
+
+ if (!pgBrowser.Nodes['coll-partition']) {
+ pgAdmin.Browser.Nodes['coll-partition'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'partition',
+ label: gettext('Partitions'),
+ type: 'coll-partition',
+ columns: [
+ 'name', 'schema', 'partition_scheme', 'partition_value', 'is_partitioned', 'description',
+ ],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['partition']) {
+ pgAdmin.Browser.Nodes['partition'] = pgBrowser.Node.extend({
+ parent_type: 'table',
+ collection_type: 'coll-partition',
+ type: 'partition',
+ label: gettext('Partition'),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Total Size'), gettext('Indexes size'), gettext('Table size'),
+ gettext('TOAST table size'), gettext('Tuple length'),
+ gettext('Dead tuple length'), gettext('Free space')],
+ sqlAlterHelp: 'sql-altertable.html',
+ sqlCreateHelp: 'sql-createtable.html',
+ dialogHelp: url_for('help.static', {'filename': 'table_dialog.html'}),
+ hasScriptTypes: ['create'],
+ width: '650px',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'truncate_table', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'truncate_table',
+ category: gettext('Truncate'), priority: 3, label: gettext('Truncate'),
+ enable : 'canCreate',
+ },{
+ name: 'truncate_table_cascade', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'truncate_table_cascade',
+ category: gettext('Truncate'), priority: 3, label: gettext('Truncate Cascade'),
+ enable : 'canCreate',
+ },{
+ // To enable/disable all triggers for the table
+ name: 'enable_all_triggers', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'enable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Enable All'),
+ enable : 'canCreate_with_trigger_enable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ },
+ },{
+ name: 'disable_all_triggers', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'disable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Disable All'),
+ enable : 'canCreate_with_trigger_disable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ },
+ },{
+ name: 'reset_table_stats', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'reset_table_stats',
+ category: 'Reset', priority: 4, label: gettext('Reset Statistics'),
+ enable : 'canCreate',
+ },{
+ name: 'detach_partition', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'detach_partition',
+ category: gettext('Detach Partition'), priority: 2, label: gettext('Detach'),
+ },{
+ name: 'detach_partition_concurrently', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'detach_partition_concurrently',
+ category: gettext('Detach Partition'), priority: 2, label: gettext('Concurrently'),
+ enable: function(itemData, item) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'],
+ partition = treeData['partition'];
+
+ return (server && server.version >= 140000 && !partition.is_detach_pending);
+ }
+ },{
+ name: 'detach_partition_finalize', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'detach_partition_finalize',
+ category: gettext('Detach Partition'), priority: 2, label: gettext('Finalize'),
+ enable: function(itemData, item) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'],
+ partition = treeData['partition'];
+
+ return (server && server.version >= 140000 && partition.is_detach_pending);
+ }
+ },{
+ name: 'count_table_rows', node: 'partition', module: pgBrowser.Nodes['table'],
+ applies: ['object', 'context'], callback: 'count_table_rows',
+ category: 'Count', priority: 2, label: gettext('Count Rows'),
+ enable: true,
+ }]);
+ },
+ generate_url: function(item, type, d, with_id, info) {
+ if (_.indexOf([
+ 'stats', 'statistics', 'dependency', 'dependent', 'reset',
+ 'get_relations', 'get_oftype', 'get_attach_tables',
+ ], type) == -1) {
+ return pgBrowser.Node.generate_url.apply(this, arguments);
+ }
+
+ if (type == 'statistics') {
+ type = 'stats';
+ }
+
+ info = (_.isUndefined(item) || _.isNull(item)) ?
+ info || {} : pgBrowser.tree.getTreeNodeHierarchy(item);
+
+ return pgadminUtils.sprintf('table/%s/%s/%s/%s/%s/%s',
+ encodeURIComponent(type), encodeURIComponent(info['server_group']._id),
+ encodeURIComponent(info['server']._id),
+ encodeURIComponent(info['database']._id),
+ encodeURIComponent(info['partition'].schema_id),
+ encodeURIComponent(info['partition']._id)
+ );
+ },
+ on_done: function(res, data, t, i) {
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = 'icon-partition';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ },
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ callbacks: {
+ /* Enable trigger(s) on table */
+ enable_triggers_on_table: function(args) {
+ let params = {'is_enable_trigger': 'O'};
+ this.callbacks.set_triggers.apply(this, [args, params]);
+ },
+ /* Disable trigger(s) on table */
+ disable_triggers_on_table: function(args) {
+ let params = {'is_enable_trigger': 'D'};
+ this.callbacks.set_triggers.apply(this, [args, params]);
+ },
+ set_triggers: function(args, params) {
+ // This function will send request to enable or
+ // disable triggers on table level
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ getApiInstance().put(obj.generate_url(i, 'set_trigger' , d, true), params)
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.updateAndReselectNode(i, d);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ /* Truncate table */
+ truncate_table: function(args) {
+ let params = {'cascade': false };
+ this.callbacks.truncate.apply(this, [args, params]);
+ },
+ /* Truncate table with cascade */
+ truncate_table_cascade: function(args) {
+ let params = {'cascade': true };
+ this.callbacks.truncate.apply(this, [args, params]);
+ },
+ truncate: function(args, params) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Truncate Table'),
+ gettext('Are you sure you want to truncate table %s?', d.label),
+ function () {
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'truncate' , d, true), params)
+ .then(({data: res})=>{
+ obj.on_done(res, data, t, i);
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.unload(i);
+ });
+ },
+ );
+ },
+ reset_table_stats: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Reset statistics'),
+ gettext('Are you sure you want to reset the statistics for table "%s"?', d._label),
+ function () {
+ let data = d;
+ getApiInstance().delete(obj.generate_url(i, 'reset' , d, true))
+ .then(({data: res})=>{
+ obj.on_done(res, data, t, i);
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.unload(i);
+ });
+ },
+ function() {/*This is intentional (SonarQube)*/}
+ );
+ },
+ detach: function(args, params) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let title = gettext('Detach Partition');
+
+ if (params['mode'] === 'concurrently') {
+ title = gettext('Detach Partition Concurrently');
+ } else if (params['mode'] === 'finalize') {
+ title = gettext('Detach Partition Finalize');
+ }
+
+ pgAdmin.Browser.notifier.confirm(
+ title,
+ gettext('Are you sure you want to detach the partition %s?', d._label),
+ function () {
+ getApiInstance().put(obj.generate_url(i, 'detach' , d, true), params)
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ let n = t.next(i);
+ if (!n) {
+ n = t.prev(i);
+ if (!n) {
+ n = t.parent(i);
+ }
+ }
+ t.remove(i);
+ if (n) {
+ t.select(n);
+ }
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ });
+ },
+ function() {/*This is intentional (SonarQube)*/}
+ );
+ },
+ detach_partition: function(args) {
+ let params = {'mode': 'detach' };
+ this.callbacks.detach.apply(this, [args, params]);
+ },
+ detach_partition_concurrently: function(args) {
+ let params = {'mode': 'concurrently' };
+ this.callbacks.detach.apply(this, [args, params]);
+ },
+ detach_partition_finalize: function(args) {
+ let params = {'mode': 'finalize' };
+ this.callbacks.detach.apply(this, [args, params]);
+ },
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return getNodePartitionTableSchema(treeNodeInfo, itemNodeData, pgBrowser);
+ },
+ canCreate: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ // Check to whether table has disable trigger(s)
+ canCreate_with_trigger_enable: function(itemData, item, data) {
+ if(this.canCreate(itemData, item, data)) {
+ // We are here means we can create menu, now let's check condition
+ return (itemData.tigger_count > 0);
+ }
+ },
+ // Check to whether table has enable trigger(s)
+ canCreate_with_trigger_disable: function(itemData, item, data) {
+ if(this.canCreate(itemData, item, data)) {
+ // We are here means we can create menu, now let's check condition
+ return (itemData.tigger_count > 0 && itemData.has_enable_triggers > 0);
+ }
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['partition'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..25b1701cc58416b9435b8809638ebf6e718541bc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/static/js/partition.ui.js
@@ -0,0 +1,454 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from 'top/browser/server_groups/servers/static/js/sec_label.ui';
+import _ from 'lodash';
+import { ConstraintsSchema } from '../../../static/js/table.ui';
+import { PartitionKeysSchema, PartitionsSchema } from '../../../static/js/partition.utils.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../../static/js/privilege.ui';
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../../static/js/node_ajax';
+import { getNodeForeignKeySchema } from '../../../constraints/foreign_key/static/js/foreign_key.ui';
+import { getNodeExclusionConstraintSchema } from '../../../constraints/exclusion_constraint/static/js/exclusion_constraint.ui';
+import * as pgadminUtils from 'sources/utils';
+
+export function getNodePartitionTableSchema(treeNodeInfo, itemNodeData, pgBrowser) {
+ const spcname = ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ });
+
+ let partNode = pgBrowser.Nodes['partition'];
+
+ return new PartitionTableSchema(
+ {
+ relowner: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }, (d)=>{
+ // If schema name start with pg_* then we need to exclude them
+ return !(d?.label.match(/^pg_/));
+ }),
+ spcname: spcname,
+ coll_inherits: ()=>getNodeAjaxOptions('get_inherits', partNode, treeNodeInfo, itemNodeData),
+ typname: ()=>getNodeAjaxOptions('get_oftype', partNode, treeNodeInfo, itemNodeData),
+ like_relation: ()=>getNodeAjaxOptions('get_relations', partNode, treeNodeInfo, itemNodeData),
+ table_amname_list: ()=>getNodeAjaxOptions('get_table_access_methods', partNode, treeNodeInfo, itemNodeData),
+ },
+ treeNodeInfo,
+ {
+ constraints: ()=>new ConstraintsSchema(
+ treeNodeInfo,
+ ()=>getNodeForeignKeySchema(treeNodeInfo, itemNodeData, pgBrowser, true),
+ ()=>getNodeExclusionConstraintSchema(treeNodeInfo, itemNodeData, pgBrowser, true),
+ {spcname: spcname},
+ ),
+ },
+ (privileges)=>getNodePrivilegeRoleSchema(partNode, treeNodeInfo, itemNodeData, privileges),
+ (params)=>{
+ return getNodeAjaxOptions('get_columns', partNode, treeNodeInfo, itemNodeData, {urlParams: params, useCache:false});
+ },
+ ()=>getNodeAjaxOptions('get_collations', pgBrowser.Nodes['collation'], treeNodeInfo, itemNodeData),
+ ()=>getNodeAjaxOptions('get_op_class', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData),
+ ()=>{
+ return getNodeAjaxOptions('get_attach_tables', partNode, treeNodeInfo, itemNodeData, {
+ useCache:false,
+ customGenerateUrl: (trNodeInfo, actionType)=>{
+ return pgadminUtils.sprintf('table/%s/%s/%s/%s/%s/%s',
+ encodeURIComponent(actionType), encodeURIComponent(trNodeInfo['server_group']._id),
+ encodeURIComponent(trNodeInfo['server']._id),
+ encodeURIComponent(trNodeInfo['database']._id),
+ encodeURIComponent(trNodeInfo['partition'].schema_id),
+ encodeURIComponent(trNodeInfo['partition']._id)
+ );
+ }});
+ },
+ {
+ relowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: treeNodeInfo.schema._label,
+ }
+ );
+}
+
+export default class PartitionTableSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, schemas={}, getPrivilegeRoleSchema={}, getColumns=()=>[],
+ getCollations=()=>[], getOperatorClass=()=>[], getAttachTables=()=>[], initValues={}) {
+ super({
+ name: undefined,
+ oid: undefined,
+ spcoid: undefined,
+ spcname: undefined,
+ relowner: undefined,
+ relacl: undefined,
+ relhasoids: undefined,
+ relhassubclass: undefined,
+ reltuples: undefined,
+ description: undefined,
+ conname: undefined,
+ conkey: undefined,
+ isrepl: undefined,
+ triggercount: undefined,
+ relpersistence: undefined,
+ fillfactor: undefined,
+ reloftype: undefined,
+ typname: undefined,
+ labels: undefined,
+ providers: undefined,
+ is_sys_table: undefined,
+ coll_inherits: [],
+ hastoasttable: true,
+ toast_autovacuum_enabled: 'x',
+ autovacuum_enabled: 'x',
+ primary_key: [],
+ partitions: [],
+ partition_type: 'range',
+ is_partitioned: false,
+ partition_value: undefined,
+ amname: undefined,
+ ...initValues,
+ });
+
+ this.fieldOptions = fieldOptions;
+ this.schemas = schemas;
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.nodeInfo = nodeInfo;
+ this.getColumns = getColumns;
+ this.getAttachTables = getAttachTables;
+
+ this.partitionKeysObj = new PartitionKeysSchema([], getCollations, getOperatorClass);
+ this.partitionsObj = new PartitionsSchema(this.nodeInfo, getCollations, getOperatorClass, fieldOptions.table_amname_list, getAttachTables);
+ this.constraintsObj = this.schemas.constraints();
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ initialise(state) {
+ this.changeColumnOptions(state.columns);
+ }
+
+ inSchemaWithModelCheck(state) {
+ if(this.nodeInfo && 'schema' in this.nodeInfo) {
+ return !this.isNew(state);
+ }
+ return false;
+ }
+
+ isPartitioned(state) {
+ if(state.is_partitioned) {
+ return true;
+ }
+ return this.inCatalog();
+ }
+
+ changeColumnOptions(columns) {
+ let colOptions = (columns||[]).map((c)=>({label: c.name, value: c.name, image:'icon-column'}));
+ this.constraintsObj.changeColumnOptions(colOptions);
+ this.partitionKeysObj.changeColumnOptions(colOptions);
+ this.partitionsObj.changeColumnOptions(colOptions);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text', noEmpty: true,
+ mode: ['properties', 'create', 'edit'], readonly: this.inCatalog,
+ },{
+ id: 'oid', label: gettext('OID'), type: 'text', mode: ['properties'],
+ },{
+ id: 'relowner', label: gettext('Owner'), type: 'select',
+ options: this.fieldOptions.relowner, noEmpty: true,
+ mode: ['properties', 'create', 'edit'], controlProps: {allowClear: false},
+ readonly: this.inCatalog,
+ },{
+ id: 'schema', label: gettext('Schema'), type: 'select',
+ options: this.fieldOptions.schema, noEmpty: true,
+ mode: ['create', 'edit'],
+ readonly: this.inCatalog,
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ type: 'select', options: this.fieldOptions.spcname,
+ mode: ['properties', 'create', 'edit'], deps: ['is_partitioned'],
+ readonly: this.inCatalog,
+ },{
+ id: 'partition', type: 'group', label: gettext('Partitions'),
+ mode: ['edit', 'create'], min_version: 100000,
+ visible: function(state) {
+ // Always show in case of create mode
+ return obj.isNew(state) || state.is_partitioned;
+ },
+ },{
+ id: 'is_partitioned', label:gettext('Partitioned table?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ min_version: 100000,
+ readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'is_sys_table', label: gettext('System table?'), cell: 'switch',
+ type: 'switch', mode: ['properties'],
+ disabled: this.inCatalog,
+ },{
+ id: 'description', label: gettext('Comment'), type: 'multiline',
+ mode: ['properties', 'create', 'edit'], disabled: this.inCatalog,
+ },{
+ id: 'advanced', label: gettext('Advanced'), type: 'group',
+ visible: true,
+ },{
+ id: 'coll_inherits', label: gettext('Inherited from table(s)'),
+ type: 'text', group: gettext('Advanced'), mode: ['properties'],
+ },
+ {
+ id: 'inherited_tables_cnt', label: gettext('Inherited tables count'),
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ // Here we will create tab control for constraints
+ type: 'nested-tab', group: gettext('Constraints'),
+ mode: ['edit', 'create'],
+ schema: obj.constraintsObj,
+ },{
+ id: 'fillfactor', label: gettext('Fill factor'), type: 'int',
+ mode: ['create', 'edit'], min: 10, max: 100,
+ group: 'advanced',
+ disabled: obj.isPartitioned,
+ },{
+ id: 'toast_tuple_target', label: gettext('Toast tuple target'), type: 'int',
+ mode: ['create', 'edit'], min: 128, min_version: 110000,
+ group: 'advanced',
+ disabled: obj.isPartitioned,
+ },{
+ id: 'parallel_workers', label: gettext('Parallel workers'), type: 'int',
+ mode: ['create', 'edit'], group: 'advanced', min_version: 90600,
+ disabled: obj.isPartitioned,
+ },
+ {
+ id: 'amname', label: gettext('Access Method'), group: 'advanced',
+ type: (state)=>{
+ return {
+ type: 'select', options: this.fieldOptions.table_amname_list,
+ controlProps: {
+ allowClear: obj.isNew(state),
+ }
+ };
+ }, mode: ['create', 'properties', 'edit'], min_version: 120000,
+ disabled: (state) => {
+ if (obj.getServerVersion() < 150000 && !obj.isNew(state)) {
+ return true;
+ }
+ return obj.isPartitioned(state);
+ },
+ },
+ {
+ id: 'relhasoids', label: gettext('Has OIDs?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ group: 'advanced', readonly: true,
+ disabled: function() {
+ if(obj.getServerVersion() >= 120000) {
+ return true;
+ }
+ return obj.inCatalog();
+ },
+ },{
+ id: 'relpersistence', label: gettext('Unlogged?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ disabled: obj.inSchemaWithModelCheck,
+ group: 'advanced',
+ },{
+ id: 'conname', label: gettext('Primary key'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ id: 'reltuples', label: gettext('Rows (estimated)'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ id: 'rows_cnt', label: gettext('Rows (counted)'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ formatter: {
+ fromRaw: ()=>{
+ return 0;
+ },
+ toRaw: (backendVal)=>{
+ return backendVal;
+ },
+ },
+ },{
+ id: 'relhassubclass', label: gettext('Is inherited?'), cell: 'switch',
+ type: 'switch', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ id: 'partition_type', label:gettext('Partition Type'),
+ editable: false, type: 'select', controlProps: {allowClear: false},
+ group: 'partition', deps: ['is_partitioned'],
+ options: function() {
+ let options = [{
+ label: gettext('Range'), value: 'range',
+ },{
+ label: gettext('List'), value: 'list',
+ }];
+
+ if(obj.getServerVersion() >= 110000) {
+ options.push({
+ label: gettext('Hash'), value: 'hash',
+ });
+ }
+ return Promise.resolve(options);
+ },
+ mode:['create'],
+ min_version: 100000,
+ disabled: function(state) {
+ return !state.is_partitioned;
+ },
+ readonly: function(state) {return !obj.isNew(state);},
+ },
+ {
+ id: 'partition_keys', label:gettext('Partition Keys'),
+ schema: obj.partitionKeysObj,
+ editable: true, type: 'collection',
+ group: 'partition', mode: ['create'],
+ deps: ['is_partitioned', 'partition_type', 'typname'],
+ canEdit: false, canDelete: true,
+ canAdd: function(state) {
+ return obj.isNew(state) && state.is_partitioned;
+ },
+ canAddRow: function(state) {
+ let columnsExist = false;
+
+ let maxRowCount = 1000;
+ if (state.partition_type && state.partition_type == 'list')
+ maxRowCount = 1;
+
+ if (state.columns?.length > 0) {
+ columnsExist = _.some(_.map(state.columns, 'name'));
+ }
+
+ if(state.partition_keys) {
+ return state.partition_keys.length < maxRowCount && columnsExist;
+ }
+
+ return true;
+ }, min_version: 100000,
+ depChange: (state, source, topState, actionObj)=>{
+ if(state.typname != actionObj.oldState.typname) {
+ return {
+ partition_keys: [],
+ };
+ }
+ }
+ },
+ {
+ id: 'partition_scheme', label: gettext('Partition Scheme'),
+ group: 'partition', mode: ['edit'],
+ type: (state)=>({
+ type: 'note',
+ text: state.partition_scheme || '',
+ }),
+ min_version: 100000,
+ },
+ {
+ id: 'partition_key_note', label: gettext('Partition Keys'),
+ type: 'note', group: 'partition', mode: ['create'],
+ text: [
+ '',
+ gettext('Partition table supports two types of keys:'),
+ ' ',
+ '', gettext('Column: '), ' ',
+ gettext('User can select any column from the list of available columns.'),
+ ' ',
+ '', gettext('Expression: '), ' ',
+ gettext('User can specify expression to create partition key.'),
+ ' ',
+ '', gettext('Example: '), ' ',
+ gettext('Let\'s say, we want to create a partition table based per year for the column \'saledate\', having datatype \'date/timestamp\', then we need to specify the expression as \'extract(YEAR from saledate)\' as partition key.'),
+ ' ',
+ ].join(''),
+ min_version: 100000,
+ },
+ {
+ id: 'partitions', label: gettext('Partitions'),
+ schema: this.partitionsObj,
+ editable: true, type: 'collection',
+ group: 'partition', mode: ['edit', 'create'],
+ deps: ['is_partitioned', 'partition_type', 'typname'],
+ depChange: (state, source)=>{
+ if(['is_partitioned', 'partition_type', 'typname'].indexOf(source[0]) >= 0 && obj.isNew(state)){
+ return {'partitions': []};
+ }
+ },
+ canEdit: true, canDelete: true,
+ customDeleteTitle: gettext('Detach Partition'),
+ customDeleteMsg: gettext('Are you sure you wish to detach this partition?'),
+ columns:['is_attach', 'partition_name', 'is_default', 'values_from', 'values_to', 'values_in', 'values_modulus', 'values_remainder'],
+ canAdd: function(state) {
+ return state.is_partitioned;
+ },
+ min_version: 100000,
+ },
+ {
+ id: 'partition_note', label: gettext('Partitions'),
+ type: 'note', group: 'partition', mode: ['create'],
+ text: [
+ '',
+ '', gettext('Create a table: '), ' ',
+ gettext('User can create multiple partitions while creating new partitioned table. Operation switch is disabled in this scenario.'),
+ ' ',
+ '', gettext('Edit existing table: '), ' ',
+ gettext('User can create/attach/detach multiple partitions. In attach operation user can select table from the list of suitable tables to be attached.'),
+ ' ',
+ '', gettext('Default: '), ' ',
+ gettext('The default partition can store rows that do not fall into any existing partition’s range or list.'),
+ ' ',
+ '', gettext('From/To/In input: '), ' ',
+ gettext('From/To/In input: Values for these fields must be quoted with single quote. For more than one partition key values must be comma(,) separated.'),
+ ' ',
+ '', gettext('Example: From/To: '), ' ',
+ gettext('Enabled for range partition. Consider partitioned table with multiple keys of type Integer, then values should be specified like \'100\',\'200\'.'),
+ ' ',
+ '', gettext('In: '), ' ',
+ gettext('Enabled for list partition. Values must be comma(,) separated and quoted with single quote.'),
+ ' ',
+ '', gettext('Modulus/Remainder: '), ' ',
+ gettext('Enabled for hash partition.'),
+ ' ',
+ ].join(''),
+ min_version: 100000,
+ },
+ {
+ id: 'relacl_str', label: gettext('Privileges'), disabled: this.inCatalog,
+ type: 'text', mode: ['properties'], group: gettext('Security'),
+ },
+ {
+ id: 'relacl', label: gettext('Privileges'), type: 'collection',
+ group: gettext('Security'), schema: this.getPrivilegeRoleSchema(['a','r','w','d','D','x','t']),
+ mode: ['edit', 'create'], canAdd: true, canDelete: true,
+ uniqueCol : ['grantee'],
+ },{
+ id: 'seclabels', label: gettext('Security labels'), canEdit: false,
+ schema: new SecLabelSchema(), editable: false, canAdd: true,
+ type: 'collection', min_version: 90100, mode: ['edit', 'create'],
+ group: gettext('Security'), canDelete: true, control: 'unique-col-collection',
+ },{
+ id: 'vacuum_settings_str', label: gettext('Storage settings'),
+ type: 'multiline', group: 'advanced', mode: ['properties'],
+ }];
+ }
+
+ validate(state, setError) {
+ if (state.is_partitioned && this.isNew(state) &&
+ (!state.partition_keys || state.partition_keys && state.partition_keys.length <= 0)) {
+ setError('partition_keys', gettext('Please specify at least one key for partitioned table.'));
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/templates/partitions/css/partition.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/templates/partitions/css/partition.css
new file mode 100644
index 0000000000000000000000000000000000000000..889eca4b55fd67fee20374929cabe560364d5401
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/partitions/templates/partitions/css/partition.css
@@ -0,0 +1,36 @@
+.icon-coll-partition {
+ background-image: url('{{ url_for('NODE-partition.static', filename='img/coll-partition.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-partition {
+ background-image: url('{{ url_for('NODE-partition.static', filename='img/partition.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-partition_table {
+ background-image: url('{{ url_for('NODE-partition.static', filename='img/partition_table.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-sub_partition_table {
+ background-image: url('{{ url_for('NODE-partition.static', filename='img/sub_partition_table.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ border-radius: 10px;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa823095f3aed1e8ba506e22f29ec750e013ee24
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/__init__.py
@@ -0,0 +1,750 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements policy Node"""
+
+import json
+from functools import wraps
+
+from pgadmin.browser.server_groups.servers import databases
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.tables. \
+ row_security_policies import utils as row_security_policies_utils
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.directory_compare import directory_diff
+
+
+class RowSecurityModule(CollectionNodeModule):
+ """
+ class RowSecurityModule(CollectionNodeModule)
+
+ A module class for policy node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the RowSecurityModule
+ and it's base module.
+
+ * get_nodes(gid, sid, did)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overplidden from its base class to
+ make the node as leaf node.
+
+ * script_load()
+ - Load the module script for policy, when any of the database node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'row_security_policy'
+ _COLLECTION_LABEL = gettext('RLS Policies')
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90500
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs)
+ if self.has_nodes(
+ sid, did, scid=scid,
+ tid=kwargs.get('tid', kwargs.get('vid', None)),
+ base_template_path=RowSecurityView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ kwargs['tid'] if 'tid' in kwargs else kwargs['vid']
+ )
+
+ @property
+ def node_inode(self):
+ """
+ Overplide the property to make the node as leaf node
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for policy, when any of the database node is
+ initialized.
+ """
+ return databases.DatabaseModule.node_type
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+blueprint = RowSecurityModule(__name__)
+
+
+class RowSecurityView(PGChildNodeView):
+ """
+ class RowSecurityView(PGChildNodeView)
+
+ A view class for policy node derived from PGChildNodeView.
+ This class is
+ responsible for all the stuff related to view like
+ create/update/delete policy, showing properties of policy node,
+ showing sql in sql pane.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the RowSecurityView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the policy nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection. Here it will create all the policy nodes.
+
+ * properties(gid, sid, did, plid)
+ - This function will show the properties of the selected policy node
+
+ * create(gid, sid, did, plid)
+ - This function will create the new policy object
+
+ * update(gid, sid, did, plid)
+ - This function will update the data for the selected policy node
+
+ * delete(self, gid, sid, plid):
+ - This function will drop the policy object
+
+ * msql(gid, sid, did, plid)
+ - This function is used to return modified sql for the selected
+ policy node
+
+
+ * sql(gid, sid, did, plid):
+ - This function will generate sql to show in sql pane for the selected
+ policy node.
+ """
+
+ node_type = blueprint.node_type
+ node_label = "RLS Policy"
+ BASE_TEMPLATE_PATH = 'row_security_policies/sql/#{0}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'plid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}]
+ })
+
+ def _init_(self, **kwargs):
+ self.conn = None
+ self.template_path = None
+ self.manager = None
+ super().__init__(**kwargs)
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will check the
+ database connection before running view. It will also attach
+ manager, conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(
+ PG_DEFAULT_DRIVER
+ ).connection_manager(kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ schema, table = row_security_policies_utils.get_parent(self.conn,
+ kwargs[
+ 'tid'])
+ self.schema = schema
+ self.table = table
+ # Set template path for the sql scripts
+ self.table_template_path = compile_template_path(
+ 'tables/sql',
+ self.manager.version
+ )
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ Fetch all policy properties and render into properties tab
+ """
+
+ # fetch schema name by schema id
+ sql = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]), schema=self.schema,
+ tid=tid)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, plid):
+ """
+ return single node
+ """
+ sql = render_template("/".join(
+ [self.template_path, self._NODES_SQL]), plid=plid)
+
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-row_security_policy"
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ List all the policies under the policies Collection node
+ """
+ res = []
+ sql = render_template("/".join(
+ [self.template_path, self._NODES_SQL]), tid=tid)
+
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-row_security_policy"
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, plid):
+ """
+ Fetch the properties of an individual policy and render in
+ properties tab
+
+ """
+ status, data = self._fetch_properties(did, scid, tid, plid)
+ if not status:
+ return data
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ def _fetch_properties(self, did, scid, tid, plid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param plid:
+ :return:
+ """
+ sql = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]
+ ), plid=plid, scid=scid, policy_table_id=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ data = dict(res['rows'][0])
+
+ # Remove opening and closing bracket as we already have in jinja
+ # template.
+ if 'using' in data and data['using'] is not None and \
+ data['using'].startswith('(') and data['using'].endswith(')'):
+ data['using'] = data['using'][1:-1]
+ if 'withcheck' in data and data['withcheck'] is not None and \
+ data['withcheck'].startswith('(') and \
+ data['withcheck'].endswith(')'):
+ data['withcheck'] = data['withcheck'][1:-1]
+
+ return True, data
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will creates new the policy object
+ :param did: database id
+ :param sid: server id
+ :param gid: group id
+ :param tid: table id
+ :param scid: Schema ID
+ :return:
+ """
+
+ required_args = [
+ 'name',
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ data['schema'] = self.schema
+ data['table'] = self.table
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ try:
+ sql = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need oid to add object in tree at browser
+ sql = render_template(
+ "/".join([self.template_path, 'get_position.sql']),
+ tid=tid, data=data, conn=self.conn
+ )
+ status, plid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=tid)
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ plid,
+ tid,
+ data['name'],
+ icon="icon-row_security_policy"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, scid, did, tid, plid=None):
+ """
+ This function will update policy object
+ :param plid: policy id
+ :param did: database id
+ :param sid: server id
+ :param gid: group id
+ :param tid: table id
+ :param scid: Schema ID
+ :return:
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ try:
+ sql, name = row_security_policies_utils.get_sql(
+ self.conn, data=data, scid=scid, plid=plid,
+ policy_table_id=tid,
+ schema=self.schema, table=self.table)
+
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ plid,
+ tid,
+ name,
+ icon="icon-row_security_policy"
+ )
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @staticmethod
+ def get_policy_data(plid):
+ """
+ return policy data
+ :param plid:
+ :return: policy id
+ """
+ if plid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [plid]}
+
+ return data
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will drop the policy object
+ :param plid: policy id
+ :param did: database id
+ :param sid: server id
+ :param gid: group id
+ :param tid: table id
+ :param scid: Schema ID
+ :param kwargs
+ :return:
+ """
+ plid = kwargs.get('plid', None)
+ only_sql = kwargs.get('only_sql', False)
+
+ # Below will deplide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ data = self.get_policy_data(plid)
+
+ for plid in data['ids']:
+ try:
+ # Get name of policy using plid
+ sql = render_template("/".join([self.template_path,
+ 'get_policy_name.sql']),
+ plid=plid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ # drop policy
+ result = res['rows'][0]
+ result['schema'] = self.schema
+ result['table'] = self.table
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ policy_name=result['name'],
+ cascade=cascade,
+ result=result
+ )
+ if only_sql:
+ return sql
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ return make_json_response(
+ success=1,
+ info=gettext("policy dropped")
+ )
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, plid=None):
+ """
+ This function returns modified sql
+ """
+ data = dict(request.args)
+
+ sql, _ = row_security_policies_utils.get_sql(
+ self.conn, data=data, scid=scid, plid=plid, policy_table_id=tid,
+ schema=self.schema, table=self.table)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified sql"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, plid):
+ """
+ This function will generate sql to render into the sql panel
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ plid: policy ID
+ """
+
+ SQL = row_security_policies_utils.get_reverse_engineered_sql(
+ self.conn, schema=self.schema, table=self.table, scid=scid,
+ plid=plid, policy_table_id=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, plid):
+ """
+ This function gets the dependents and returns an ajax response
+ for the policy node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ plid: policy ID
+ tid: table id
+ scid: Schema ID
+ """
+ dependents_result = self.get_dependents(self.conn, plid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, plid):
+ """
+ This function gets the dependencies and returns an ajax response
+ for the policy node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ plid: policy ID
+ tid: table id
+ scid: Schema ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, plid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ oid = kwargs.get('plid')
+ data = kwargs.get('data', None)
+ drop_req = kwargs.get('drop_req', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ data['schema'] = self.schema
+ data['table'] = self.table
+ sql, _ = row_security_policies_utils.get_sql(
+ self.conn, data=data, scid=scid, plid=oid, policy_table_id=tid,
+ schema=self.schema, table=self.table)
+
+ sql = sql.strip('\n').strip(' ')
+
+ else:
+ schema = self.schema
+ if target_schema:
+ schema = target_schema
+
+ sql = row_security_policies_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=self.table, scid=scid,
+ plid=oid, policy_table_id=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ with_header=False)
+
+ drop_sql = ''
+ if drop_req:
+ drop_sql = self.delete(gid=1, sid=sid, did=did,
+ scid=scid, tid=tid, plid=oid, only_sql=True)
+ if drop_sql != '':
+ sql = drop_sql + '\n\n'
+ return sql
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, oid=None):
+ """
+ This function will fetch the list of all the policies for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param oid: Policy Id
+ :return:
+ """
+
+ res = dict()
+
+ if not oid:
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid,
+ schema_diff=True)
+ status, policies = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(policies)
+ return False
+ for row in policies['rows']:
+ status, data = self._fetch_properties(did, scid, tid,
+ row['oid'])
+ if status:
+ res[row['name']] = data
+ else:
+ status, data = self._fetch_properties(did, scid, tid, oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+ res = data
+
+ return res
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ src_params = kwargs.get('source_params')
+ tgt_params = kwargs.get('target_params')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ target_schema = kwargs.get('target_schema')
+ comp_status = kwargs.get('comp_status')
+
+ diff = ''
+ if comp_status == 'source_only':
+ diff = self.get_sql_from_diff(gid=src_params['gid'],
+ sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ plid=source['oid'],
+ target_schema=target_schema)
+ elif comp_status == 'target_only':
+ diff = self.delete(gid=1,
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ plid=target['oid'],
+ only_sql=True)
+ elif comp_status == 'different':
+ diff_dict = directory_diff(
+ source, target, difference={}
+ )
+ if 'event' in diff_dict or 'type' in diff_dict:
+ delete_sql = self.get_sql_from_diff(gid=1,
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ plid=target['oid'],
+ drop_req=True)
+
+ diff = self.get_sql_from_diff(gid=src_params['gid'],
+ sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ plid=source['oid'],
+ target_schema=target_schema)
+ return delete_sql + diff
+
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ plid=target['oid'],
+ data=diff_dict)
+ return '\n' + diff
+
+
+SchemaDiffRegistry(blueprint.node_type, RowSecurityView, 'table')
+RowSecurityView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/coll-row_security_policy.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/coll-row_security_policy.svg
new file mode 100644
index 0000000000000000000000000000000000000000..9fbad75692b77273adc0c30a9e8bbff10924fc2d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/coll-row_security_policy.svg
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/row_security_policy.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/row_security_policy.svg
new file mode 100644
index 0000000000000000000000000000000000000000..e72c7845eaa860aa11529a494861075c56e5e535
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/img/row_security_policy.svg
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.js
new file mode 100644
index 0000000000000000000000000000000000000000..4e729d0b4b3977f00f234c17f1faa804bec5a25d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.js
@@ -0,0 +1,102 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import RowSecurityPolicySchema from './row_security_policy.ui';
+import { getNodeListByName } from '../../../../../../../../static/js/node_ajax';
+
+
+define('pgadmin.node.row_security_policy', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-row_security_policy']) {
+ pgAdmin.Browser.Nodes['coll-row_security_policy'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'row_security_policy',
+ label: gettext('RLS Policies'),
+ type: 'coll-row_security_policy',
+ columns: ['name', 'description'],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['row_security_policy']) {
+ pgAdmin.Browser.Nodes['row_security_policy'] = pgBrowser.Node.extend({
+ parent_type: ['table', 'view', 'partition'],
+ collection_type: ['coll-table', 'coll-view'],
+ type: 'row_security_policy',
+ label: gettext('RLS Policy'),
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.sm + 'px',
+ sqlAlterHelp: 'sql-alterpolicy.html',
+ sqlCreateHelp: 'sql-createpolicy.html',
+ dialogHelp: url_for('help.static', {'filename': 'rls_policy_dialog.html'}),
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_row_security_policy_on_coll', node: 'coll-row_security_policy', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('RLS Policy...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_row_security_policy', node: 'row_security_policy', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('RLS Policy...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ {
+ name: 'create_row_security_policy_on_coll', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 6, label: gettext('RLS Policy...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ ]);
+ },
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new RowSecurityPolicySchema(
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData, {}, ()=>true, (res)=>{
+ res.unshift({label: 'PUBLIC', value: 'public'});
+ return res;
+ }),
+ nodeInfo: treeNodeInfo
+ }
+ );
+ },
+ canCreate: function(itemData, item) {
+
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ // If node is under catalog then do not allow 'create' menu
+ if (treeData['catalog'] != undefined)
+ return false;
+
+ // If server is less than 9.5 then do not allow 'create' menu
+ return server && server.version >= 90500;
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['row_security_policy'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..e19fe489ad658ea221acdd66be09237d061a7bfb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/static/js/row_security_policy.ui.js
@@ -0,0 +1,128 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+
+export default class RowSecurityPolicySchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ policyowner: 'public',
+ event: 'ALL',
+ using: undefined,
+ using_orig: undefined,
+ withcheck: undefined,
+ withcheck_orig: undefined,
+ type:'PERMISSIVE',
+ ...initValues
+ });
+
+ this.fieldOptions = {
+ role: [],
+ function_names: [],
+ ...fieldOptions,
+ };
+
+ this.nodeInfo = this.fieldOptions.nodeInfo;
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ disableUsingField(state){
+ return state.event == 'INSERT';
+ }
+
+ disableWithCheckField(state){
+ let event = state.event;
+ if ((event == 'SELECT') || (event == 'DELETE')){
+ state.withcheck = '';
+ return true;
+ }
+ return false;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ editable: true, type: 'text', readonly: false,
+ noEmpty: true
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ editable: false, type: 'text', mode: ['properties'],
+ },
+ {
+ id: 'event', label: gettext('Event'), type: 'select',
+ group: gettext('Commands'),disabled: () => {
+ return !obj.isNew();
+ },
+ controlProps: { allowClear: false },
+ options:[
+ {label: 'ALL', value: 'ALL'},
+ {label: 'SELECT', value: 'SELECT'},
+ {label: 'INSERT', value: 'INSERT'},
+ {label: 'UPDATE', value: 'UPDATE'},
+ {label: 'DELETE', value: 'DELETE'},
+ ],
+ },
+ {
+ id: 'using', label: gettext('Using'), deps: ['using', 'event'],
+ type: 'sql', disabled: obj.disableUsingField,
+ mode: ['create', 'edit', 'properties'],
+ control: 'sql', visible: true, group: gettext('Commands'),
+ },
+ {
+ id: 'withcheck', label: gettext('With check'), deps: ['withcheck', 'event'],
+ type: 'sql', mode: ['create', 'edit', 'properties'],
+ control: 'sql', visible: true, group: gettext('Commands'),
+ disabled: obj.disableWithCheckField,
+ },
+ {
+ id: 'rls_expression_key_note', label: gettext('RLS policy expression'),
+ type: 'note', group: gettext('Commands'), mode: ['create', 'edit'],
+ text: [
+ '',
+ '', gettext('Using: '), ' ',
+ gettext('This expression will be added to queries that refer to the table if row level security is enabled. Rows for which the expression returns true will be visible. Any rows for which the expression returns false or null will not be visible to the user (in a SELECT), and will not be available for modification (in an UPDATE or DELETE). Such rows are silently suppressed; no error is reported.'),
+ ' ',
+ '', gettext('With check: '), ' ',
+ gettext('This expression will be used in INSERT and UPDATE queries against the table if row level security is enabled. Only rows for which the expression evaluates to true will be allowed. An error will be thrown if the expression evaluates to false or null for any of the records inserted or any of the records that result from the update.'),
+ ' ',
+ ].join(''),
+ },
+ {
+ id: 'policyowner', label: gettext('Role'), cell: 'text',
+ type: 'select',
+ options: obj.fieldOptions.role,
+ controlProps: { allowClear: false }
+ },
+ {
+ id: 'type', label: gettext('Type'), type: 'select', deps:['type'],
+ disabled: () => {return !obj.isNew();},
+ controlProps: {
+ width: '100%',
+ allowClear: false,
+ },
+ options:[
+ {label: 'PERMISSIVE', value: 'PERMISSIVE'},
+ {label: 'RESTRICTIVE', value: 'RESTRICTIVE'},
+ ],
+ visible: () => {
+ return obj.nodeInfo.server.version >= 100000;
+ },
+ },
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..82028b02feb7a4d82aec43fe2d93738584dc0829
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/row_security_policies/utils.py
@@ -0,0 +1,151 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for row level security. """
+
+from flask import render_template
+from flask_babel import gettext
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs or kwargs['template_path'] is None:
+ kwargs['template_path'] = 'row_security_policies/sql/#{0}#'.format(
+ conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_sql(conn, **kwargs):
+ """
+ This function will generate sql from model data
+ """
+ data = kwargs.get('data')
+ scid = kwargs.get('scid')
+ plid = kwargs.get('plid')
+ policy_table_id = kwargs.get('policy_table_id')
+ schema = kwargs.get('schema')
+ table = kwargs.get('table')
+ template_path = kwargs.get('template_path', None)
+
+ if plid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ schema=schema, plid=plid, scid=scid,
+ policy_table_id=policy_table_id)
+ status, res = conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(
+ gettext('Could not find the policy in the table.'))
+
+ old_data = dict(res['rows'][0])
+ old_data['schema'] = schema
+ old_data['table'] = table
+ sql = render_template(
+ "/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn
+ )
+ else:
+ data['schema'] = schema
+ data['table'] = table
+ sql = render_template("/".join(
+ [template_path, 'create.sql']), data=data, conn=conn)
+
+ return sql, data['name'] if 'name' in data else old_data['name']
+
+
+@get_template_path
+def get_reverse_engineered_sql(conn, **kwargs):
+ """
+ This function will return reverse engineered sql for specified trigger.
+ :param conn:
+ :param kwargs:
+ :return:
+ """
+ schema = kwargs.get('schema')
+ table = kwargs.get('table')
+ scid = kwargs.get('scid')
+ plid = kwargs.get('plid')
+ policy_table_id = kwargs.get('policy_table_id')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ template_path = kwargs.get('template_path', None)
+ with_header = kwargs.get('with_header', True)
+
+ SQL = render_template("/".join(
+ [template_path, 'properties.sql']), plid=plid, scid=scid,
+ policy_table_id=policy_table_id)
+
+ status, res = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(gettext('Could not find the policy in the table.'))
+
+ data = dict(res['rows'][0])
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = schema
+ data['table'] = table
+
+ SQL, _ = get_sql(conn, data=data, scid=scid, plid=None,
+ policy_table_id=policy_table_id,
+ datlastsysoid=datlastsysoid, schema=schema, table=table)
+ if with_header:
+ sql_header = "-- POLICY: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([template_path,
+ 'delete.sql']),
+ policy_name=data['name'],
+ result=data
+ )
+
+ SQL = sql_header + '\n\n' + SQL
+
+ return SQL
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..350dbadf6b1c8dee1b4d5000cf4a4b95421e7d1b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/__init__.py
@@ -0,0 +1,722 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements Rule Node"""
+
+import json
+from functools import wraps
+
+from pgadmin.browser.server_groups.servers.databases import schemas
+from flask import render_template, make_response, request, jsonify,\
+ current_app
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ parse_rule_definition
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.directory_compare import directory_diff,\
+ parse_acl
+
+
+class RuleModule(CollectionNodeModule):
+ """
+ class RuleModule(CollectionNodeModule):
+
+ A rule collection Node which inherits CollectionNodeModule
+ class and define methods:
+ get_nodes - To generate collection node.
+ script_load - tells when to load js file.
+ csssnppets - add css to page
+ """
+ _NODE_TYPE = 'rule'
+ _COLLECTION_LABEL = gettext("Rules")
+
+ def __init__(self, *args, **kwargs):
+ self.min_ver = None
+ self.max_ver = None
+
+ super().__init__(*args, **kwargs)
+
+ def backend_supported(self, manager, **kwargs):
+ """
+ Load this module if tid is view, we will not load it under
+ material view
+ """
+ if super().backend_supported(manager, **kwargs):
+ conn = manager.connection(did=kwargs['did'])
+
+ if 'vid' not in kwargs:
+ return True
+
+ self.template_path = 'rules/sql'
+ SQL = render_template("/".join(
+ [self.template_path, 'backend_support.sql']
+ ), vid=kwargs['vid'])
+
+ status, res = conn.execute_scalar(SQL)
+ # check if any errors
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Check tid is view not material view
+ # then true, othewise false
+ return res
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs)
+ if self.has_nodes(sid, did, scid=scid,
+ tid=kwargs.get('tid', kwargs.get('vid', None)),
+ base_template_path=RuleView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ kwargs['tid'] if 'tid' in kwargs else kwargs['vid']
+ )
+
+ @property
+ def node_inode(self):
+ """
+ If a node has children return True otherwise False
+ """
+ return False
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for rule, when any of the database nodes are
+ initialized.
+ """
+ return schemas.SchemaModule.node_type
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ self._COLLECTION_CSS,
+ node_type=self.node_type,
+ _=gettext
+ ),
+ render_template(
+ "rules/css/rule.css",
+ node_type=self.node_type,
+ _=gettext
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+
+# Create blueprint of RuleModule.
+blueprint = RuleModule(__name__)
+
+
+class RuleView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This is a class for rule node which inherits the
+ properties and methods from PGChildNodeView class and define
+ various methods to list, create, update and delete rule.
+
+ Variables:
+ ---------
+ * node_type - tells which type of node it is
+ * parent_ids - id with its type and name of parent nodes
+ * ids - id with type and name of extension module being used.
+ * operations - function routes mappings defined.
+ """
+ node_type = blueprint.node_type
+ node_label = "Rule"
+ BASE_TEMPLATE_PATH = 'rules/sql'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'rid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'configs': [{'get': 'configs'}]
+ })
+
+ # Schema Diff: Keys to ignore while comparing
+ keys_to_ignore = ['oid', 'schema', 'definition', 'oid-2']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will check the
+ database connection before running a view. It will also attach
+ manager, conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(
+ PG_DEFAULT_DRIVER).connection_manager(kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.template_path = self.BASE_TEMPLATE_PATH
+ self.table_template_path = compile_template_path(
+ 'tables/sql',
+ self.manager.version
+ )
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ Fetch all rule properties and render into properties tab
+ """
+
+ # fetch schema name by schema id
+ SQL = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]), tid=tid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, rid):
+ """
+ return single node
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._NODES_SQL]), rid=rid)
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-rule" if
+ rset['rows'][0]['is_enable_rule'] == 'D' else "icon-rule-bad"
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ List all the rules under the Rules Collection node
+ """
+ res = []
+ SQL = render_template("/".join(
+ [self.template_path, self._NODES_SQL]), tid=tid)
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-rule-bad"
+ if 'is_enable_rule' in row and
+ row['is_enable_rule'] == 'D' else "icon-rule",
+ description=row['comment']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, rid):
+ """
+ Fetch the properties of an individual rule and render in properties tab
+
+ """
+ status, data = self._fetch_properties(rid)
+ if not status:
+ return data
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ def _fetch_properties(self, rid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param rid:
+ :return:
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]
+ ), rid=rid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ return True, parse_rule_definition(res)
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will create a new rule object
+ """
+ required_args = [
+ 'name',
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ try:
+ SQL = render_template("/".join(
+ [self.template_path, self._CREATE_SQL]),
+ data=data,
+ conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Fetch the rule id against rule name to display node
+ # in tree browser
+ SQL = render_template("/".join(
+ [self.template_path, 'rule_id.sql']),
+ rule_name=data['name'], conn=self.conn)
+ status, rule_id = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=rule_id)
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ rule_id,
+ tid,
+ data['name'],
+ icon="icon-rule"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, rid):
+ """
+ This function will update a rule object
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ try:
+ SQL, name = self.getSQL(gid, sid, data, tid, rid)
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ rid,
+ tid,
+ name,
+ icon="icon-%s-bad" % self.node_type
+ if 'is_enable_rule' in data and
+ data['is_enable_rule'] == 'D'
+ else "icon-%s" % self.node_type,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will drop a rule object
+ """
+ rid = kwargs.get('rid', None)
+ only_sql = kwargs.get('only_sql', False)
+
+ if rid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [rid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for rid in data['ids']:
+ # Get name for rule from did
+ SQL = render_template("/".join(
+ [self.template_path, self._DELETE_SQL]), rid=rid)
+ status, res_data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res_data)
+
+ if not res_data['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ # drop rule
+ rset = res_data['rows'][0]
+ SQL = render_template("/".join(
+ [self.template_path, self._DELETE_SQL]),
+ rulename=rset['rulename'],
+ relname=rset['relname'],
+ nspname=rset['nspname'],
+ cascade=cascade
+ )
+ if only_sql:
+ return SQL
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Rule dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, rid=None):
+ """
+ This function returns modified SQL
+ """
+ data = request.args
+ sql, _ = self.getSQL(gid, sid, data, tid, rid)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, rid):
+ """
+ This function will generate sql to render into the sql panel
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]), rid=rid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res_data = parse_rule_definition(res)
+ SQL = render_template("/".join(
+ [self.template_path, self._CREATE_SQL]),
+ data=res_data, display_comments=True,
+ add_replace_clause=True,
+ conn=self.conn
+ )
+
+ return ajax_response(response=SQL)
+
+ def getSQL(self, gid, sid, data, tid, rid):
+ """
+ This function will generate sql from model data
+ """
+
+ if rid is not None:
+ SQL = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]), rid=rid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+ res_data = parse_rule_definition(res)
+
+ old_data = res_data
+ SQL = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ else:
+ SQL = render_template("/".join(
+ [self.template_path, self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ return SQL, data['name'] if 'name' in data else old_data['name']
+
+ @check_precondition
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, tid=tid,
+ rid=oid, only_sql=True)
+ else:
+ sql = render_template("/".join(
+ [self.template_path, self._PROPERTIES_SQL]), rid=oid)
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+ res_data = parse_rule_definition(res)
+
+ if data:
+ old_data = res_data
+ sql = render_template(
+ "/".join([self.template_path, self._UPDATE_SQL]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+ else:
+ RuleView._check_schema_diff(target_schema, res_data)
+ sql = render_template("/".join(
+ [self.template_path, self._CREATE_SQL]),
+ data=res_data,
+ display_comments=True,
+ conn=self.conn)
+
+ return sql
+
+ @ staticmethod
+ def _check_schema_diff(target_schema, res_data):
+ """
+ Check for schema diff, if yes then replace source schema with target
+ schema.
+ diff_schema: schema diff schema
+ res_data: response from properties sql.
+ """
+ if target_schema and 'statements' in res_data:
+ # Replace the source schema with the target schema
+ res_data['statements'] = \
+ res_data['statements'].replace(
+ res_data['schema'], target_schema)
+ res_data['schema'] = target_schema
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, rid):
+ """
+ This function gets the dependents and returns an ajax response
+ for the rule node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ tid: View ID
+ rid: Rule ID
+ """
+ dependents_result = self.get_dependents(self.conn, rid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, rid):
+ """
+ This function gets the dependencies and returns sn ajax response
+ for the rule node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ tid: View ID
+ rid: Rule ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, rid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, oid=None):
+ """
+ This function will fetch the list of all the rules for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :return:
+ """
+
+ res = {}
+ if oid:
+ status, data = self._fetch_properties(oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+
+ res = data
+ else:
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid, schema_diff=True)
+ status, rules = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(rules)
+ return False
+
+ for row in rules['rows']:
+ status, data = self._fetch_properties(row['oid'])
+ if status:
+ res[row['name']] = data
+ return res
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ src_params = kwargs.get('source_params')
+ tgt_params = kwargs.get('target_params')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ comp_status = kwargs.get('comp_status')
+
+ diff = ''
+ if comp_status == 'source_only':
+ diff = self.get_sql_from_diff(gid=src_params['gid'],
+ sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ oid=source['oid'])
+ elif comp_status == 'target_only':
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ drop_sql=True)
+ elif comp_status == 'different':
+ diff_dict = directory_diff(
+ source, target,
+ ignore_keys=self.keys_to_ignore, difference={}
+ )
+ parse_acl(source, target, diff_dict)
+
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ data=diff_dict)
+
+ return diff
+
+
+SchemaDiffRegistry(blueprint.node_type, RuleView, 'table')
+RuleView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/css/rule.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/css/rule.css
new file mode 100644
index 0000000000000000000000000000000000000000..b46b9bddbc79ad8a5e8f2e657ab86f30b038e83d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/css/rule.css
@@ -0,0 +1,7 @@
+.sql_field_height_140 {
+ height: 140px;
+}
+
+.sql_field_height_280 {
+ height: 280px;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/coll-rule.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/coll-rule.svg
new file mode 100644
index 0000000000000000000000000000000000000000..cfc6e09d36c72ac5709af064ed62c8f4e40960c1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/coll-rule.svg
@@ -0,0 +1 @@
+coll-rule
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule-bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule-bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..a1b4aef878c1a84b5318078574ecc4e3ae05081a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule-bad.svg
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule.svg
new file mode 100644
index 0000000000000000000000000000000000000000..59d89fb03e1daa8ff9e5859d3881c9bbd8256072
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/img/rule.svg
@@ -0,0 +1 @@
+rule
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.js
new file mode 100644
index 0000000000000000000000000000000000000000..3b84476c1622e15a78ab9751f515fc7ce30430bf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.js
@@ -0,0 +1,254 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import RuleSchema from './rule.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.rule', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+], function(gettext, url_for, pgAdmin, pgBrowser, SchemaChildTreeNode) {
+
+ /**
+ Create and add a rule collection into nodes
+ @param {variable} label - Label for Node
+ @param {variable} type - Type of Node
+ @param {variable} columns - List of columns to
+ display under under properties.
+ */
+ if (!pgBrowser.Nodes['coll-rule']) {
+ pgAdmin.Browser.Nodes['coll-rule'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'rule',
+ label: gettext('Rules'),
+ type: 'coll-rule',
+ columns: ['name', 'owner', 'comment'],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+
+ /**
+ Create and Add an Rule Node into nodes
+ @param {variable} parent_type - The list of nodes
+ under which this node to display
+ @param {variable} type - Type of Node
+ @param {variable} hasSQL - To show SQL tab
+ @param {variable} canDrop - Adds drop rule option
+ in the context menu
+ @param {variable} canDropCascade - Adds drop Cascade
+ rule option in the context menu
+ */
+ if (!pgBrowser.Nodes['rule']) {
+ pgAdmin.Browser.Nodes['rule'] = pgBrowser.Node.extend({
+ parent_type: ['table','view', 'partition'],
+ type: 'rule',
+ sqlAlterHelp: 'sql-alterrule.html',
+ sqlCreateHelp: 'sql-createrule.html',
+ dialogHelp: url_for('help.static', {'filename': 'rule_dialog.html'}),
+ label: gettext('rule'),
+ collection_type: 'coll-table',
+ hasSQL: true,
+ hasDepends: true,
+ canDrop: function(itemData, item){
+ SchemaChildTreeNode.isTreeItemOfChildOfSchema.apply(this, [itemData, item]);
+ return (!_.has(itemData, 'label') || itemData.label !== '_RETURN');
+ },
+ canDropCascade: function(itemData, item){
+ SchemaChildTreeNode.isTreeItemOfChildOfSchema.apply(this, [itemData, item]);
+ return (!_.has(itemData, 'label') || itemData.label !== '_RETURN');
+ },
+ url_jump_after_node: 'schema',
+ Init: function() {
+
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ /**
+ Add "create rule" menu option into context and object menu
+ for the following nodes:
+ coll-rule, rule and view and table.
+ @property {data} - Allow create rule option on schema node or
+ system rules node.
+ */
+ pgBrowser.add_menus([{
+ name: 'create_rule_on_coll', node: 'coll-rule', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Rule...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_rule_onView', node: 'view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 5, label: gettext('Rule...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_rule', node: 'rule', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Rule...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_rule', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Rule...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },{
+ name: 'create_rule', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Rule...'),
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ },
+ {
+ name: 'enable_rule', node: 'rule', module: this,
+ applies: ['object', 'context'], callback: 'enable_rule',
+ category: 'connect', priority: 3, label: gettext('Enable'),
+ enable: 'canCreate_with_rule_enable',
+ },{
+ name: 'disable_rule', node: 'rule', module: this,
+ applies: ['object', 'context'], callback: 'disable_rule',
+ category: 'drop', priority: 3, label: gettext('Disable'),
+ enable: 'canCreate_with_rule_disable'
+ }
+ ]);
+ },
+ callbacks: {
+ /* Enable rule */
+ enable_rule: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'obj' , d, true), {'is_enable_rule' : 'O'})
+ .then(()=>{
+ pgAdmin.Browser.notifier.success('Rule updated.');
+ t.removeIcon(i);
+ data.icon = 'icon-rule';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ /* Disable rule */
+ disable_rule: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'obj' , d, true), {'is_enable_rule' : 'D'})
+ .then(()=>{
+ pgAdmin.Browser.notifier.success('Rule updated');
+ t.removeIcon(i);
+ data.icon = 'icon-rule-bad';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new RuleSchema(
+ {
+ nodeInfo: treeNodeInfo,
+ nodeData: itemNodeData
+ }
+ );
+ },
+
+ // Show or hide create rule menu option on parent node
+ canCreate: function(itemData, item, data) {
+
+ // If check is false then , we will allow create menu
+ if (data && data.check === false)
+ return true;
+
+ let t = pgBrowser.tree, i = item, d = itemData;
+
+ // To iterate over tree to check parent node
+ while (i) {
+
+ // If it is schema then allow user to create rule
+ if (_.indexOf(['schema'], d._type) > -1)
+ return true;
+
+ if ('coll-rule' == d._type) {
+
+ //Check if we are not child of rule
+ let prev_i = t.hasParent(i) ? t.parent(i) : null,
+ prev_j = t.hasParent(prev_i) ? t.parent(prev_i) : null,
+ prev_k = t.hasParent(prev_j) ? t.parent(prev_j) : null,
+ prev_f = prev_k ? t.itemData(prev_k) : null;
+ return (_.isNull(prev_f) || prev_f._type != 'catalog');
+ }
+
+ /**
+ Check if it is view and its parent node is schema
+ then allow to create Rule
+ */
+ else if('view' == d._type || 'table' == d._type){
+ let prev_i = t.hasParent(i) ? t.parent(i) : null,
+ prev_j = t.hasParent(prev_i) ? t.parent(prev_i) : null,
+ prev_e = prev_j ? t.itemData(prev_j) : null;
+ return (!_.isNull(prev_e) && prev_e._type == 'schema');
+ }
+ i = t.hasParent(i) ? t.parent(i) : null;
+ d = i ? t.itemData(i) : null;
+ }
+
+ // By default we do not want to allow create menu
+ return true;
+
+ },
+
+ canCreate_with_rule_enable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-rule-bad' &&
+ this.canCreate(itemData, item, data);
+ },
+ // Check to whether rule is enable ?
+ canCreate_with_rule_disable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-rule' &&
+ this.canCreate.apply(itemData, item, data);
+ },
+
+ });
+ }
+
+ return pgBrowser.Nodes['coll-rule'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..dea0b1b1f8418f5f5508a32be92b730c007fc826
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/static/js/rule.ui.js
@@ -0,0 +1,114 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+
+
+export default class RuleSchema extends BaseUISchema {
+ constructor(fieldOptions={}) {
+ super({
+ oid: undefined,
+ name: undefined,
+ schema: undefined
+ });
+
+ this.fieldOptions = {
+ nodeInfo: undefined,
+ nodeData: undefined,
+ ...fieldOptions,
+ };
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'),
+ type: 'text', disabled: (state) => {
+ // disable name field it it is system rule
+ if (state.name == '_RETURN') {
+ return true;
+ }
+ return !(obj.isNew(state) || obj.fieldOptions.nodeInfo.server.version >= 90400);
+ }, noEmpty: true
+ },
+ {
+ id: 'oid', label: gettext('OID'),
+ type: 'text', mode: ['properties'],
+ },
+ {
+ id: 'schema', label:'',
+ type: 'text', visible: false, disabled: (state) => {
+ // It is used while generating sql
+ state.schema = ('schema' in obj.fieldOptions.nodeInfo) ? obj.fieldOptions.nodeInfo.schema.label : '';
+ },
+ },
+ {
+ id: 'view', label:'',
+ type: 'text', visible: false, disabled: (state) => {
+ // It is used while generating sql
+ state.view = obj.fieldOptions.nodeData.label;
+ },
+ },
+ {
+ id: 'is_enable_rule', label: gettext('Rule enabled?'),
+ mode: ['edit', 'properties'], group: gettext('Definition'),
+ type: 'select',
+ disabled: () => {
+ return 'catalog' in obj.fieldOptions.nodeInfo || 'view' in obj.fieldOptions.nodeInfo;
+ },
+ options: [
+ {label: gettext('Enable'), value: 'O'},
+ {label: gettext('Enable Replica'), value: 'R'},
+ {label: gettext('Enable Always'), value: 'A'},
+ {label: gettext('Disable'), value: 'D'},
+ ],
+ controlProps: { allowClear: false },
+ },
+ {
+ id: 'event', label: gettext('Event'), control: 'select2',
+ group: gettext('Definition'), type: 'select',
+ controlProps: { allowClear: false },
+ options:[
+ {label: 'SELECT', value: 'SELECT'},
+ {label: 'INSERT', value: 'INSERT'},
+ {label: 'UPDATE', value: 'UPDATE'},
+ {label: 'DELETE', value: 'DELETE'},
+ ],
+ },
+ {
+ id: 'do_instead', label: gettext('Do instead?'), group: gettext('Definition'),
+ type: 'switch',
+ },
+ {
+ id: 'condition', label: gettext('Condition'),
+ type: 'sql', isFullTab: true, group: gettext('Condition'),
+
+ },
+ {
+ id: 'statements', label: gettext('Commands'),
+ type: 'sql', isFullTab: true, group: gettext('Commands'),
+ },
+ {
+ id: 'system_rule', label: gettext('System rule?'),
+ type: 'switch', mode: ['properties'],
+ },
+ {
+ id: 'comment', label: gettext('Comment'), cell: 'text', type: 'multiline',
+ },
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/templates/rules/css/rule.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/templates/rules/css/rule.css
new file mode 100644
index 0000000000000000000000000000000000000000..f6de648bad133cf75f2c47d8ef8394a5d69dfb9b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/rules/templates/rules/css/rule.css
@@ -0,0 +1,18 @@
+.icon-rule{
+ background-image: url('{{ url_for('NODE-rule.static', filename='img/rule.svg') }}') !important;
+ background-size: 20px !important;
+ background-repeat: no-repeat;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+
+.icon-rule-bad{
+ background-image: url('{{ url_for('NODE-rule.static', filename='img/rule-bad.svg') }}') !important;
+ background-size: 20px !important;
+ background-repeat: no-repeat;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_table_utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_table_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1820c6c49400f045d14dc5a26610b40ecc76f313
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_table_utils.py
@@ -0,0 +1,434 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Table and Partitioned Table. """
+
+import copy
+
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.tools.schema_diff.directory_compare import compare_dictionaries,\
+ are_dictionaries_identical
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+
+
+class SchemaDiffTableCompare(SchemaDiffObjectCompare):
+ table_keys_to_ignore = ['oid', 'schema', 'edit_types', 'attnum',
+ 'col_type', 'references', 'reltuples', 'oid-2',
+ 'rows_cnt', 'hastoasttable', 'relhassubclass',
+ 'relacl_str', 'setting']
+
+ column_keys_to_ignore = ['atttypid', 'edit_types', 'elemoid', 'seqrelid',
+ 'indkey', 'seqtypid']
+
+ constraint_keys_to_ignore = ['relname', 'nspname', 'parent_tbl',
+ 'attrelid', 'adrelid', 'fknsp', 'confrelid',
+ 'references', 'refnsp', 'remote_schema',
+ 'conkey', 'indkey', 'references_table_name',
+ 'refnspoid']
+
+ trigger_keys_to_ignore = ['xmin', 'tgrelid', 'tgfoid', 'tfunction',
+ 'tgqual', 'tgconstraint']
+ index_keys_to_ignore = ['indrelid', 'indclass']
+
+ keys_to_ignore = table_keys_to_ignore + column_keys_to_ignore + \
+ constraint_keys_to_ignore + trigger_keys_to_ignore + \
+ index_keys_to_ignore
+
+ def compare(self, **kwargs):
+ """
+ This function is used to compare all the table objects
+ from two different schemas.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = {'sid': kwargs.get('source_sid'),
+ 'did': kwargs.get('source_did'),
+ 'scid': kwargs.get('source_scid')}
+ target_params = {'sid': kwargs.get('target_sid'),
+ 'did': kwargs.get('target_did'),
+ 'scid': kwargs.get('target_scid')}
+ ignore_owner = kwargs.get('ignore_owner')
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+ ignore_tablespace = kwargs.get('ignore_tablespace')
+ ignore_grants = kwargs.get('ignore_grants')
+
+ group_name = kwargs.get('group_name')
+ source_schema_name = kwargs.get('source_schema_name', None)
+ source_tables = {}
+ target_tables = {}
+
+ status, target_schema = self.get_schema(**target_params)
+ if not status:
+ return internal_server_error(errormsg=target_schema)
+
+ if 'scid' in source_params and source_params['scid'] is not None:
+ source_tables = self.fetch_tables(**source_params,
+ with_serial_cols=True)
+
+ if 'scid' in target_params and target_params['scid'] is not None:
+ target_tables = self.fetch_tables(**target_params,
+ with_serial_cols=True)
+
+ # If both the dict have no items then return None.
+ if not (source_tables or target_tables) or (
+ len(source_tables) <= 0 and len(target_tables) <= 0):
+ return None
+
+ return compare_dictionaries(view_object=self,
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source_dict=source_tables,
+ target_dict=target_tables,
+ node=self.node_type,
+ node_label=self.blueprint.collection_label,
+ group_name=group_name,
+ ignore_keys=self.keys_to_ignore,
+ source_schema_name=source_schema_name,
+ ignore_owner=ignore_owner,
+ ignore_whitespaces=ignore_whitespaces,
+ ignore_tablespace=ignore_tablespace,
+ ignore_grants=ignore_grants)
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function will compare properties of 2 tables and
+ return the source DDL, target DDL and Difference of them.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = {'sid': kwargs.get('source_sid'),
+ 'did': kwargs.get('source_did'),
+ 'scid': kwargs.get('source_scid'),
+ 'tid': kwargs.get('source_oid'),
+ 'json_resp': False
+ }
+
+ target_params = {'sid': kwargs.get('target_sid'),
+ 'did': kwargs.get('target_did'),
+ 'scid': kwargs.get('target_scid'),
+ 'tid': kwargs.get('target_oid'),
+ 'json_resp': False
+ }
+
+ source = self.get_sql_from_table_diff(**source_params)
+ target = self.get_sql_from_table_diff(**target_params)
+
+ return {'source_ddl': source,
+ 'target_ddl': target,
+ 'diff_ddl': ''
+ }
+
+ @staticmethod
+ def table_col_comp(source, target):
+ """
+ Table Column comparison
+ :param source: Source columns
+ :param target: Target columns
+ :return: Difference of the columns
+ """
+ source_cols = source['columns']
+ target_cols = copy.deepcopy(target['columns'])
+ added = []
+ updated = []
+ different = {'columns': {}}
+
+ for source in source_cols:
+ if 'name' in source:
+ if isinstance(target_cols, list) and target_cols:
+ SchemaDiffTableCompare.compare_target_cols(source,
+ target_cols,
+ added, updated)
+ else:
+ added.append(source)
+ different['columns']['added'] = added
+ different['columns']['changed'] = updated
+
+ if target_cols and len(target_cols) > 0:
+ different['columns']['deleted'] = target_cols
+
+ return different
+
+ @staticmethod
+ def compare_target_cols(source, target_cols, added, updated):
+ """
+ Compare target col with source.
+ :param source:
+ :param target_cols:
+ :param added:
+ :param updated:
+ :return:
+ """
+ tmp = None
+ for item in target_cols:
+ # ignore keys from the columns list
+ for ig_key in SchemaDiffTableCompare.column_keys_to_ignore:
+ if ig_key in source:
+ del source[ig_key]
+ if ig_key in item:
+ del item[ig_key]
+
+ if item['name'] == source['name']:
+ tmp = copy.deepcopy(item)
+ source['attnum'] = tmp['attnum']
+
+ if tmp and source != tmp:
+ # check column level grants
+ acl_dict = dict()
+ if 'attacl' in source and 'attacl' in tmp and \
+ source['attacl'] != tmp['attacl']:
+ if len(source['attacl']) > 0 and len(tmp['attacl']) < 1:
+ acl_dict['added'] = source['attacl'].copy()
+ source['attacl'] = acl_dict
+ elif len(source['attacl']) < 1 and len(tmp['attacl']) > 0:
+ acl_dict['deleted'] = tmp['attacl'].copy()
+ source['attacl'] = acl_dict
+ else:
+ acl_dict['changed'] = source['attacl'].copy()
+ source['attacl'] = acl_dict
+
+ updated.append(source)
+ target_cols.remove(tmp)
+ elif tmp and source == tmp:
+ target_cols.remove(tmp)
+ elif tmp is None:
+ added.append(source)
+
+ @staticmethod
+ def table_constraint_comp(source_table, target_table):
+ """
+ Table Constraint DDL comparison
+ :param source_table: Source Table
+ :param target_table: Target Table
+ :return: Difference of constraints
+ """
+ different = {}
+ non_editable_keys = {'primary_key': ['col_count',
+ 'condeferrable',
+ 'condeffered',
+ 'columns'],
+ 'unique_constraint': ['col_count',
+ 'condeferrable',
+ 'condeffered',
+ 'columns'],
+ 'check_constraint': ['consrc'],
+ 'exclude_constraint': ['amname',
+ 'indconstraint',
+ 'columns'],
+ 'foreign_key': ['condeferrable', 'condeferred',
+ 'confupdtype', 'confdeltype',
+ 'confmatchtype', 'convalidated',
+ 'conislocal']
+ }
+
+ for constraint in ['primary_key', 'unique_constraint',
+ 'check_constraint',
+ 'exclude_constraint', 'foreign_key']:
+ source_cols = source_table[constraint] if \
+ constraint in source_table else []
+ target_cols = copy.deepcopy(target_table[constraint]) if\
+ constraint in target_table else []
+ added = []
+ updated = []
+ deleted = []
+
+ different[constraint] = {}
+ for source in source_cols:
+ if 'name' in source:
+ if isinstance(target_cols, list) and target_cols:
+ tmp_src = copy.deepcopy(source)
+ if 'oid' in tmp_src:
+ tmp_src.pop('oid')
+ tmp_tar = None
+ tmp = None
+ for item in target_cols:
+ if item['name'] == source['name']:
+ tmp_tar = copy.deepcopy(item)
+ tmp = copy.deepcopy(item)
+ if 'oid' in tmp_tar:
+ tmp_tar.pop('oid')
+ if tmp_tar and tmp_src != tmp_tar:
+ tmp_updated = copy.deepcopy(source)
+ for key in non_editable_keys[constraint]:
+ if key in tmp_updated and \
+ tmp_updated[key] != tmp_tar[key]:
+ added.append(source)
+ deleted.append(tmp_updated)
+ tmp_updated = None
+ break
+ if tmp_updated:
+ if 'oid' in tmp:
+ tmp_updated['oid'] = tmp['oid']
+ updated.append(tmp_updated)
+ target_cols.remove(tmp)
+ elif tmp_tar and tmp_src == tmp_tar:
+ target_cols.remove(tmp)
+ elif tmp_tar is None:
+ added.append(source)
+ else:
+ added.append(source)
+ different[constraint]['added'] = added
+ different[constraint]['changed'] = updated
+ different[constraint]['deleted'] = deleted
+
+ if target_cols and len(target_cols) > 0:
+ different[constraint]['deleted'] = target_cols
+
+ return different
+
+ def get_sql_from_submodule_diff(self, **kwargs):
+ """
+ This function returns the DDL/DML statements of the
+ submodules of table based on the comparison status.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = kwargs.get('source_params')
+ target_params = kwargs.get('target_params')
+ target_schema = kwargs.get('target_schema')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ diff_dict = kwargs.get('diff_dict')
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+
+ # Get the difference result for source and target columns
+ col_diff = self.table_col_comp(source, target)
+ diff_dict.update(col_diff)
+
+ # Get the difference result for source and target constraints
+ pk_diff = self.table_constraint_comp(source, target)
+ diff_dict.update(pk_diff)
+
+ # Get the difference DDL/DML statements for table
+ target_params['diff_data'] = diff_dict
+ diff = self.get_sql_from_table_diff(**target_params)
+
+ ignore_sub_modules = ['column', 'constraints']
+ if self.manager.version < 100000:
+ ignore_sub_modules.append('partition')
+ if self.manager.server_type == 'pg' or self.manager.version < 120000:
+ ignore_sub_modules.append('compound_trigger')
+
+ # Iterate through all the sub modules of the table
+ for module in self.blueprint.submodules:
+ if module.node_type not in ignore_sub_modules:
+ module_view = \
+ SchemaDiffRegistry.get_node_view(module.node_type)
+
+ if module.node_type == 'partition' and \
+ ('is_partitioned' in source and source['is_partitioned'])\
+ and ('is_partitioned' in target and
+ target['is_partitioned']):
+ target_ddl = module_view.ddl_compare(
+ target_params=target_params,
+ parent_source_data=source,
+ parent_target_data=target
+ )
+
+ diff += '\n' + target_ddl
+ elif module.node_type != 'partition':
+ dict1 = copy.deepcopy(source[module.node_type])
+ dict2 = copy.deepcopy(target[module.node_type])
+
+ # Find the duplicate keys in both the dictionaries
+ dict1_keys = set(dict1.keys())
+ dict2_keys = set(dict2.keys())
+ intersect_keys = dict1_keys.intersection(dict2_keys)
+
+ # Keys that are available in source and missing in target.
+ added = dict1_keys - dict2_keys
+ diff = SchemaDiffTableCompare._compare_source_only(
+ added, module_view, source_params, target_params,
+ dict1, diff, target_schema)
+
+ # Keys that are available in target and missing in source.
+ removed = dict2_keys - dict1_keys
+ diff = SchemaDiffTableCompare._compare_target_only(
+ removed, module_view, source_params, target_params,
+ dict2, diff, target_schema)
+
+ # Keys that are available in both source and target.
+ other_param = {
+ "dict1": dict1,
+ "dict2": dict2,
+ "source": source,
+ "target": target,
+ "target_schema": target_schema,
+ "ignore_whitespaces": ignore_whitespaces
+ }
+ diff = self._compare_source_and_target(
+ intersect_keys, module_view, source_params,
+ target_params, diff, **other_param)
+
+ return diff
+
+ @staticmethod
+ def _compare_source_only(added, module_view, source_params, target_params,
+ dict1, diff, target_schema):
+ for item in added:
+ source_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=dict1[item],
+ target=None,
+ comp_status='source_only'
+ )
+
+ diff += '\n' + source_ddl
+ return diff
+
+ @staticmethod
+ def _compare_target_only(removed, module_view, source_params,
+ target_params, dict2, diff, target_schema):
+ for item in removed:
+ target_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=None,
+ target=dict2[item],
+ comp_status='target_only'
+ )
+
+ diff += '\n' + target_ddl
+ return diff
+
+ def _compare_source_and_target(self, intersect_keys, module_view,
+ source_params, target_params, diff,
+ **kwargs):
+ dict1 = kwargs['dict1']
+ dict2 = kwargs['dict2']
+ source = kwargs['source']
+ target = kwargs['target']
+ target_schema = kwargs['target_schema']
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+
+ for key in intersect_keys:
+ # Recursively Compare the two dictionary
+ if not are_dictionaries_identical(
+ dict1[key], dict2[key], self.keys_to_ignore,
+ ignore_whitespaces):
+ diff_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=dict1[key],
+ target=dict2[key],
+ comp_status='different',
+ parent_source_data=source,
+ parent_target_data=target
+ )
+
+ diff += '\n' + diff_ddl
+ return diff
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/coll-table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/coll-table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..90228c9635ca0fc7c21584eec1d456d811294544
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/coll-table.svg
@@ -0,0 +1 @@
+coll-table
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherited.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherited.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f0e0ff26fec301d3afe13b38f54b69c8413e15f8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherited.svg
@@ -0,0 +1 @@
+inherited
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherits.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherits.svg
new file mode 100644
index 0000000000000000000000000000000000000000..efa5cbd31e8fee690ba00335a3473b0faaaefa77
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-inherits.svg
@@ -0,0 +1 @@
+inherits
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-multi-inherit.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-multi-inherit.svg
new file mode 100644
index 0000000000000000000000000000000000000000..c87ddf22235570de70de2530a1101822ca662426
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-multi-inherit.svg
@@ -0,0 +1 @@
+multiple
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl-sm.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl-sm.svg
new file mode 100644
index 0000000000000000000000000000000000000000..0be67588b4c7e1455cc7fbb06fab15385dbce824
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl-sm.svg
@@ -0,0 +1 @@
+table-repl-sm
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d4e3fdfa09382cc473ec853c8630ee2f1523381f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table-repl.svg
@@ -0,0 +1 @@
+table-repl
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table.svg
new file mode 100644
index 0000000000000000000000000000000000000000..4f8b2d624baf033491bc8a4bc4a74f3532db2fa7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/img/table.svg
@@ -0,0 +1 @@
+table
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/enable_disable_triggers.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/enable_disable_triggers.js
new file mode 100644
index 0000000000000000000000000000000000000000..30b8df07c2b1df0cbf5eea51faf37e245b1d56f1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/enable_disable_triggers.js
@@ -0,0 +1,55 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import axios from 'axios';
+import pgAdmin from 'sources/pgadmin';
+
+export function disableTriggers(tree, generateUrl, args) {
+ return setTriggers(tree, generateUrl, args, {is_enable_trigger: 'D' });
+}
+export function enableTriggers(tree, generateUrl, args) {
+ return setTriggers(tree, generateUrl, args, {is_enable_trigger: 'O' });
+}
+
+function setTriggers(tree, generateUrl, args, params) {
+ const treeNode = retrieveTreeNode(args, tree);
+
+ if (!treeNode || treeNode.getData() === null || treeNode.getData() === undefined)
+ return false;
+
+ axios.put(
+ generateUrl(treeNode.getHtmlIdentifier(), 'set_trigger', treeNode.getData(), true),
+ params
+ )
+ .then((res) => {
+ if (res.data.success === 1) {
+ pgAdmin.Browser.notifier.success(res.data.info);
+ treeNode.data.has_enable_triggers = res.data.data.has_enable_triggers;
+ treeNode.reload(tree);
+
+ }
+ })
+ .catch((xhr) => {
+ try {
+ const err = xhr.response.data;
+ if (err.success === 0) {
+ pgAdmin.Browser.notifier.error(err.errormsg);
+ }
+ } catch (e) {
+ console.warn(e.stack || e);
+ }
+ treeNode.unload(tree);
+ });
+}
+
+function retrieveTreeNode(args, tree) {
+ const input = args || {};
+ const domElementIdentifier = input.item || tree.selected();
+ return tree.findNodeByDomElement(domElementIdentifier);
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/partition.utils.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/partition.utils.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..52c819ae217b95826a35957239c79f37c5c754eb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/partition.utils.ui.js
@@ -0,0 +1,410 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import _ from 'lodash';
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { emptyValidator, isEmptyString } from '../../../../../../../../static/js/validators';
+
+export class PartitionKeysSchema extends BaseUISchema {
+ constructor(columns=[], getCollations=[], getOperatorClass=[]) {
+ super({
+ key_type: 'column',
+ });
+ this.columns = columns;
+ this.columnsReloadBasis = false;
+ this.getCollations = getCollations;
+ this.getOperatorClass = getOperatorClass;
+ }
+
+ changeColumnOptions(columns) {
+ this.columns = columns;
+ }
+
+ isEditable(state) {
+ return state.key_type != 'expression';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'key_type', label: gettext('Key type'), type:'select', editable: true,
+ cell:'select', controlProps: {allowClear: false}, noEmpty: true,
+ options:[{
+ label: gettext('Column'), value: 'column',
+ },{
+ label: gettext('Expression'), value: 'expression',
+ }],
+ },{
+ id: 'pt_column', label: gettext('Column'), type:'select',
+ deps: ['key_type', ['columns']],
+ depChange: (state, source)=>{
+ if(state.key_type == 'expression' || source[0] == 'columns') {
+ return {
+ pt_column: undefined,
+ };
+ }
+ },
+ cell: ()=>({
+ cell: 'select',
+ optionsReloadBasis: _.join(obj.columns.map((c)=>c.label), ','),//obj.columnsReloadBasis,
+ options: obj.columns,
+ controlProps: {
+ allowClear: false,
+ }
+ }),
+ editable: function(state) {
+ return obj.isEditable(state);
+ },
+ },{
+ id: 'expression', label: gettext('Expression'), type:'text',
+ cell: 'text', deps: ['key_type'],
+ depChange: (state)=>{
+ if(state.key_type == 'column') {
+ return {
+ expression: undefined,
+ };
+ }
+ },
+ editable: function(state) {
+ return state.key_type == 'expression';
+ },
+ },{
+ id: 'collationame', label: gettext('Collation'), cell: 'select',
+ type: 'select', group: gettext('partition'), deps:['key_type'],
+ options: obj.getCollations, mode: ['create', 'properties', 'edit'],
+ editable: function(state) {
+ return obj.isEditable(state);
+ },
+ disabled: ()=>{return !(obj.isNew()); },
+ },
+ {
+ id: 'op_class', label: gettext('Operator class'), cell: 'select',
+ type: 'select', group: gettext('partition'), deps:['key_type'],
+ editable: function(state) {
+ return obj.isEditable(state);
+ },
+ disabled: ()=>{return !(obj.isNew()); },
+ options: obj.getOperatorClass, mode: ['create', 'properties', 'edit'],
+ }];
+ }
+
+ validate(state, setError) {
+ let errmsg;
+ if(state.key_type == 'column') {
+ errmsg = emptyValidator('Partition key column', state.pt_column);
+ if(errmsg) {
+ setError('pt_column', errmsg);
+ return true;
+ }
+ } else {
+ errmsg = emptyValidator('Partition key expression', state.expression);
+ if(errmsg) {
+ setError('expression', errmsg);
+ return true;
+ }
+ }
+ return false;
+ }
+}
+export class PartitionsSchema extends BaseUISchema {
+ constructor(nodeInfo, getCollations, getOperatorClass, table_amname_list, getAttachTables=()=>[]) {
+ super({
+ oid: undefined,
+ is_attach: false,
+ partition_name: undefined,
+ is_default: undefined,
+ values_from: undefined,
+ values_to: undefined,
+ values_in: undefined,
+ values_modulus: undefined,
+ values_remainder: undefined,
+ is_sub_partitioned: false,
+ sub_partition_type: 'range',
+ amname: undefined,
+ });
+
+ this.subPartitionsObj = new PartitionKeysSchema([], getCollations, getOperatorClass);
+ this.getAttachTables = getAttachTables;
+ this.nodeInfo = nodeInfo;
+ this.table_amname_list = table_amname_list;
+ }
+
+ changeColumnOptions(columns) {
+ this.subPartitionsObj.changeColumnOptions(columns);
+ }
+
+ isEditable(state, type) {
+ return (this.top && this.top.sessData.partition_type == type && this.isNew(state)
+ && state.is_default !== true);
+ }
+
+ isDisable(state, type) {
+ return !(this.top && this.top.sessData.partition_type == type && this.isNew(state)
+ && state.is_default !== true);
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'oid', label: gettext('OID'), type: 'text',
+ mode: ['properties'],
+ },{
+ id: 'is_attach', label:gettext('Operation'), cell: 'select', type: 'select',
+ width: 120, disableResizing: true, options: [
+ {label: gettext('Attach'), value: true},
+ {label: gettext('Create'), value: false},
+ ], controlProps: {allowClear: false},
+ editable: function(state) {
+ return obj.isNew(state) && !obj.top.isNew();
+ },
+ readonly: function(state) {
+ return !(obj.isNew(state) && !obj.top.isNew());
+ },
+ },{
+ id: 'partition_name', label: gettext('Name'), deps: ['is_attach'],
+ type: (state)=>{
+ if(state.is_attach) {
+ return {
+ type: 'select',
+ options: this.getAttachTables,
+ controlProps: {allowClear: false},
+ };
+ } else {
+ return {
+ type: 'text',
+ };
+ }
+ },
+ cell: (state)=>{
+ if(state.is_attach) {
+ return {
+ cell: 'select',
+ options: this.getAttachTables,
+ controlProps: {allowClear: false},
+ };
+ } else {
+ return {
+ cell: 'text',
+ };
+ }
+ },
+ editable: function(state) {
+ return obj.isNew(state);
+ },
+ readonly: function(state) {
+ return !obj.isNew(state);
+ }, noEmpty: true,
+ },{
+ id: 'amname', label: gettext('Access Method'), deps: ['is_sub_partitioned'], cell: 'select',
+ type: (state)=>{
+ return {
+ type: 'select', options: this.table_amname_list,
+ controlProps: {
+ allowClear: obj.isNew(state),
+ }
+ };
+ }, min_version: 120000, disabled: state => {
+ if (obj.getServerVersion() < 150000 && !obj.isNew(state)) {
+ return true;
+ }
+ return state.is_sub_partitioned;
+ }, depChange: state => {
+ if (state.is_sub_partitioned) {
+ return {
+ amname: undefined
+ };
+ }
+ }, readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'is_default', label: gettext('Default'), type: 'switch', cell:'switch',
+ width: 55, disableResizing: true, min_version: 110000,
+ editable: function(state) {
+ return (obj.top && (obj.top.sessData.partition_type == 'range' ||
+ obj.top.sessData.partition_type == 'list') && obj.isNew(state)
+ && obj.getServerVersion() >= 110000);
+ },
+ readonly: function(state) {
+ return !(obj.top && (obj.top.sessData.partition_type == 'range' ||
+ obj.top.sessData.partition_type == 'list') && obj.isNew(state)
+ && obj.getServerVersion() >= 110000);
+ },
+ },{
+ id: 'values_from', label: gettext('From'), type:'text', cell: 'text',
+ deps: ['is_default'],
+ editable: function(state) {
+ return obj.isEditable(state, 'range');
+ },
+ disabled: function(state) {
+ return obj.isDisable(state, 'range');
+ }
+ },
+ {
+ id: 'values_to', label: gettext('To'), type:'text', cell: 'text',
+ deps: ['is_default'],
+ editable: function(state) {
+ return obj.isEditable(state, 'range');
+ },
+ disabled: function(state) {
+ return obj.isDisable(state, 'range');
+ },
+ },{
+ id: 'values_in', label: gettext('In'), type:'text', cell: 'text',
+ deps: ['is_default'],
+ editable: function(state) {
+ return obj.isEditable(state, 'list');
+ },
+ readonly: function(state) {
+ return obj.isDisable(state, 'list');
+ },
+ },{
+ id: 'values_modulus', label: gettext('Modulus'), type:'int', cell: 'int',
+ editable: function(state) {
+ return obj.isEditable(state, 'hash');
+ },
+ disabled: function(state) {
+ return obj.isDisable(state, 'hash');
+ },
+ },{
+ id: 'values_remainder', label: gettext('Remainder'), type:'int', cell: 'int',
+ editable: function(state) {
+ return obj.top && obj.top.sessData.partition_type == 'hash' && obj.isNew(state);
+ },
+ disabled: function(state) {
+ return !(obj.top && obj.top.sessData.partition_type == 'hash' && obj.isNew(state)
+ && state.is_default !== true);
+ },
+ },{
+ id: 'is_sub_partitioned', label:gettext('Partitioned table?'), cell: 'switch',
+ group: 'Partition', type: 'switch', mode: ['properties', 'create', 'edit'],
+ deps: ['is_attach'], readonly: (state)=>{
+ if(!obj.isNew(state)) {
+ return true;
+ }
+ return state.is_attach;
+ },
+ depChange: (state)=>{
+ if(state.is_attach) {
+ return {is_sub_partitioned: false};
+ }
+ },
+ },{
+ id: 'sub_partition_type', label:gettext('Partition Type'),
+ editable: false, type: 'select', controlProps: {allowClear: false},
+ group: 'Partition', deps: ['is_sub_partitioned'],
+ options: function() {
+ let options = [{
+ label: gettext('Range'), value: 'range',
+ },{
+ label: gettext('List'), value: 'list',
+ }];
+
+ if(obj.getServerVersion() >= 110000) {
+ options.push({
+ label: gettext('Hash'), value: 'hash',
+ });
+ }
+ return Promise.resolve(options);
+ },
+ visible: (state)=>obj.isNew(state),
+ readonly: (state)=>!obj.isNew(state),
+ disabled: (state)=>!state.is_sub_partitioned,
+ },{
+ id: 'sub_partition_keys', label:gettext('Partition Keys'),
+ schema: this.subPartitionsObj,
+ editable: true, type: 'collection',
+ group: 'Partition', mode: ['properties', 'create', 'edit'],
+ deps: ['is_sub_partitioned', 'sub_partition_type', ['typname']],
+ canEdit: false, canDelete: true,
+ canAdd: function(state) {
+ return obj.isNew(state) && state.is_sub_partitioned;
+ },
+ canAddRow: function(state) {
+ let columnsExist = false;
+ let columns = obj.top.sessData.columns;
+
+ let maxRowCount = 1000;
+ if (state.sub_partition_type && state.sub_partition_type == 'list')
+ maxRowCount = 1;
+
+ if (columns?.length > 0) {
+ columnsExist = _.some(_.map(columns, 'name'));
+ }
+
+ if(state.sub_partition_keys) {
+ return state.sub_partition_keys.length < maxRowCount && columnsExist;
+ }
+
+ return true;
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ if(topState.typname != actionObj.oldState.typname) {
+ return {
+ sub_partition_keys: [],
+ };
+ }
+ },
+ visible: (state)=>obj.isNew(state),
+ },{
+ id: 'sub_partition_scheme', label: gettext('Partition Scheme'),
+ group: 'Partition', mode: ['edit'],
+ type: (state)=>({
+ type: 'note',
+ text: state.sub_partition_scheme,
+ }),
+ visible: function(state) {
+ return obj.isNew(state) && !isEmptyString(state.sub_partition_scheme);
+ },
+ }];
+ }
+
+ validate(state, setError) {
+ let msg;
+ if (state.is_sub_partitioned && this.isNew(state) &&
+ (!state.sub_partition_keys || state.sub_partition_keys && state.sub_partition_keys.length <= 0)) {
+ msg = gettext('Please specify at least one key for partitioned table.');
+ setError('sub_partition_keys', msg);
+ return true;
+ }
+
+ let partitionType = this.top.sessData.partition_type;
+ if (partitionType === 'range') {
+ if (!state.is_default && isEmptyString(state.values_from)) {
+ msg = gettext('For range partition From field cannot be empty.');
+ setError('values_from', msg);
+ return true;
+ } else if (!state.is_default && isEmptyString(state.values_to)) {
+ msg = gettext('For range partition To field cannot be empty.');
+ setError('values_to', msg);
+ return true;
+ }
+ } else if (partitionType === 'list') {
+ if (!state.is_default && isEmptyString(state.values_in)) {
+ msg = gettext('For list partition In field cannot be empty.');
+ setError('values_in', msg);
+ return true;
+ }
+ } else if (partitionType === 'hash') {
+ if(isEmptyString(state.values_modulus)) {
+ msg = gettext('For hash partition Modulus field cannot be empty.');
+ setError('values_modulus', msg);
+ return true;
+ }
+
+ if(isEmptyString(state.values_remainder)) {
+ msg = gettext('For hash partition Remainder field cannot be empty.');
+ setError('values_remainder', msg);
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
new file mode 100644
index 0000000000000000000000000000000000000000..b276614f0255b8677d6a0e3f2a92983b5e0382f2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.js
@@ -0,0 +1,408 @@
+/////////////////////////////////////////////////////////////
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeTableSchema } from './table.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.table', [
+ 'pgadmin.tables.js/enable_disable_triggers',
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child','pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection', 'pgadmin.node.column',
+ 'pgadmin.node.constraints',
+], function(
+ tableFunctions,
+ gettext, url_for, pgAdmin, pgBrowser, SchemaChild, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-table']) {
+ pgBrowser.Nodes['coll-table'] =
+ pgBrowser.Collection.extend({
+ node: 'table',
+ label: gettext('Tables'),
+ type: 'coll-table',
+ columns: ['name', 'relowner', 'is_partitioned', 'description'],
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Total Size'), gettext('Indexes size'), gettext('Table size'),
+ gettext('TOAST table size'), gettext('Tuple length'),
+ gettext('Dead tuple length'), gettext('Free space')],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['table']) {
+ pgBrowser.Nodes['table'] = SchemaChild.SchemaChildNode.extend({
+ type: 'table',
+ label: gettext('Table'),
+ collection_type: 'coll-table',
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Total Size'), gettext('Indexes size'), gettext('Table size'),
+ gettext('TOAST table size'), gettext('Tuple length'),
+ gettext('Dead tuple length'), gettext('Free space')],
+ sqlAlterHelp: 'sql-altertable.html',
+ sqlCreateHelp: 'sql-createtable.html',
+ dialogHelp: url_for('help.static', {'filename': 'table_dialog.html'}),
+ hasScriptTypes: ['create', 'select', 'insert', 'update', 'delete'],
+ width: pgBrowser.stdW.lg + 'px',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_table_on_coll', node: 'coll-table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Table...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_table', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('Table...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_table__on_schema', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Table...'),
+ data: {action: 'create', check: false},
+ enable: 'canCreate',
+ },{
+ name: 'truncate_table', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'truncate_table',
+ category: gettext('Truncate'), priority: 3, label: gettext('Truncate'),
+ enable : 'canCreate',
+ },{
+ name: 'truncate_table_cascade', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'truncate_table_cascade',
+ category: gettext('Truncate'), priority: 3, label: gettext('Truncate Cascade'),
+ enable : 'canCreate',
+ },{
+ name: 'truncate_table_identity', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'truncate_table_identity',
+ category: gettext('Truncate'), priority: 3, label: gettext('Truncate Restart Identity'),
+ enable : 'canCreate',
+ },{
+ // To enable/disable all triggers for the table
+ name: 'enable_all_triggers', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'enable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Enable All'),
+ enable : 'canCreate_with_trigger_enable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ },
+ },{
+ name: 'disable_all_triggers', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'disable_triggers_on_table',
+ category: gettext('Trigger(s)'), priority: 4, label: gettext('Disable All'),
+ enable : 'canCreate_with_trigger_disable',
+ data: {
+ data_disabled: gettext('The selected tree node does not support this option.'),
+ },
+ },{
+ name: 'reset_table_stats', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'reset_table_stats',
+ category: 'Reset', priority: 4, label: gettext('Reset Statistics'),
+ enable : 'canCreate',
+ },{
+ name: 'count_table_rows', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'count_table_rows',
+ category: 'Count', priority: 2, label: gettext('Count Rows'),
+ enable: true,
+ },{
+ name: 'generate_erd', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'generate_erd',
+ category: 'erd', priority: 5, label: gettext('ERD For Table'),
+ }
+ ]);
+ pgBrowser.Events.on(
+ 'pgadmin:browser:node:table:updated', this.onTableUpdated.bind(this)
+ );
+ pgBrowser.Events.on(
+ 'pgadmin:browser:node:type:cache_cleared',
+ this.handle_cache.bind(this)
+ );
+ pgBrowser.Events.on(
+ 'pgadmin:browser:node:domain:cache_cleared',
+ this.handle_cache.bind(this)
+ );
+ },
+ callbacks: {
+ /* Enable trigger(s) on table */
+ enable_triggers_on_table: function(args) {
+ tableFunctions.enableTriggers(
+ pgBrowser.tree,
+ this.generate_url.bind(this),
+ args
+ );
+ },
+ /* Disable trigger(s) on table */
+ disable_triggers_on_table: function(args) {
+ tableFunctions.disableTriggers(
+ pgBrowser.tree,
+ this.generate_url.bind(this),
+ args
+ );
+ },
+ /* Truncate table */
+ truncate_table: function(args) {
+ let params = {'cascade': false };
+ this.callbacks.truncate.apply(this, [args, params]);
+ },
+ /* Truncate table with cascade */
+ truncate_table_cascade: function(args) {
+ let params = {'cascade': true };
+ this.callbacks.truncate.apply(this, [args, params]);
+ },
+ truncate_table_identity: function(args) {
+ let params = {'identity': true };
+ this.callbacks.truncate.apply(this, [args, params]);
+ },
+ truncate: function(args, params) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Truncate Table'),
+ gettext('Are you sure you want to truncate table %s?', d.label),
+ function () {
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'truncate' , d, true), params)
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = data.is_partitioned ? 'icon-partition': 'icon-table';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ if (res.success == 2) {
+ pgAdmin.Browser.notifier.error(res.info);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ }, function() {/*This is intentional (SonarQube)*/}
+ );
+ },
+ reset_table_stats: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Reset statistics'),
+ gettext('Are you sure you want to reset the statistics for table "%s"?', d._label),
+ function () {
+ let data = d;
+ getApiInstance().delete(obj.generate_url(i, 'reset' , d, true))
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = data.is_partitioned ? 'icon-partition': 'icon-table';
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, d);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ function() {/*This is intentional (SonarQube)*/}
+ );
+ },
+ count_table_rows: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+ if (!d)
+ return false;
+
+ /* Set the type to table so that partition module can call this func */
+ let newD = {
+ ...d, _type: this.type,
+ };
+ // Fetch the total rows of a table
+ getApiInstance().get(obj.generate_url(i, 'count_rows' , newD, true))
+ .then(({data: res})=>{
+ pgAdmin.Browser.notifier.success(res.info, null);
+ d.rows_cnt = res.data.total_rows;
+ t.updateAndReselectNode(i, d);
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ /* Generate the ERD */
+ generate_erd: function(args) {
+ let input = args || {},
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+ pgAdmin.Tools.ERD.showErdTool(d, i, true);
+ },
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return getNodeTableSchema(treeNodeInfo, itemNodeData, pgBrowser);
+ },
+ // Check to whether table has disable trigger(s)
+ canCreate_with_trigger_enable: function(itemData) {
+ return itemData.tigger_count > 0 && (itemData.has_enable_triggers == 0 || itemData.has_enable_triggers < itemData.tigger_count);
+ },
+ // Check to whether table has enable trigger(s)
+ canCreate_with_trigger_disable: function(itemData) {
+ return itemData.tigger_count > 0 && itemData.has_enable_triggers > 0;
+ },
+ onTableUpdated: function(_node, _oldNodeData, _newNodeData) {
+ let key, childIDs;
+ if (
+
+ _newNodeData.is_partitioned &&
+ 'affected_partitions' in _newNodeData
+ ) {
+ let partitions = _newNodeData.affected_partitions,
+ newPartitionsIDs = [],
+ insertChildTreeNodes = [],
+ insertChildrenNodes = function() {
+ if (!insertChildTreeNodes.length)
+ return;
+ let option = insertChildTreeNodes.pop();
+ pgBrowser.addChildTreeNodes(
+ option.treeHierarchy, option.parent, option.type,
+ option.childrenIDs, insertChildrenNodes
+ );
+ }, schemaNode ;
+
+ if ('detached' in partitions && partitions.detached.length > 0) {
+ // Remove it from the partition collections node first
+ pgBrowser.removeChildTreeNodesById(
+ _node, 'coll-partition', _.map(
+ partitions.detached, function(_d) { return parseInt(_d.oid); }
+ )
+ );
+
+ schemaNode = pgBrowser.findParentTreeNodeByType(
+ _node, 'schema'
+ );
+ let detachedBySchema = _.groupBy(
+ partitions.detached,
+ function(_d) { return parseInt(_d.schema_id); }
+ );
+
+ for (key in detachedBySchema) {
+ schemaNode = pgBrowser.findSiblingTreeNode(schemaNode, key);
+
+ if (schemaNode) {
+ childIDs = _.map(
+ detachedBySchema[key],
+ function(_d) { return parseInt(_d.oid); }
+ );
+
+ let tablesCollNode = pgBrowser.findChildCollectionTreeNode(
+ schemaNode, 'coll-table'
+ );
+
+ if (tablesCollNode) {
+ insertChildTreeNodes.push({
+ 'parent': tablesCollNode,
+ 'type': 'table',
+ 'treeHierarchy':
+ pgAdmin.Browser.tree.getTreeNodeHierarchy(
+ schemaNode
+ ),
+ 'childrenIDs': _.clone(childIDs),
+ });
+ }
+ }
+ }
+ }
+
+ if ('attached' in partitions && partitions.attached.length > 0) {
+ schemaNode = pgBrowser.findParentTreeNodeByType(
+ _node, 'schema'
+ );
+ let attachedBySchema = _.groupBy(
+ partitions.attached,
+ function(_d) { return parseInt(_d.schema_id); }
+ );
+
+ for (key in attachedBySchema) {
+ schemaNode = pgBrowser.findSiblingTreeNode(schemaNode, key);
+
+ if (schemaNode) {
+ childIDs = _.map(
+ attachedBySchema[key],
+ function(_d) { return parseInt(_d.oid); }
+ );
+ // Remove it from the table collections node first
+ pgBrowser.removeChildTreeNodesById(
+ schemaNode, 'coll-table', childIDs
+ );
+ }
+ newPartitionsIDs = newPartitionsIDs.concat(childIDs);
+ }
+ }
+
+ if ('created' in partitions && partitions.created.length > 0) {
+ _.each(partitions.created, function(_data) {
+ newPartitionsIDs.push(_data.oid);
+ });
+ }
+
+ if (newPartitionsIDs.length) {
+ let partitionsCollNode = pgBrowser.findChildCollectionTreeNode(
+ _node, 'coll-partition'
+ );
+
+ if (partitionsCollNode) {
+ insertChildTreeNodes.push({
+ 'parent': partitionsCollNode,
+ 'type': 'partition',
+ 'treeHierarchy': pgAdmin.Browser.tree.getTreeNodeHierarchy(_node),
+ 'childrenIDs': newPartitionsIDs,
+ });
+ }
+ }
+ insertChildrenNodes();
+ }
+ },
+ handle_cache: function() {
+ // Clear Table's cache as column's type is dependent on two node
+ // 1) Type node 2) Domain node
+ this.clear_cache.apply(this, null);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['table'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..d79d2e8a7a167e8d37f0659dbc8970503367a7f9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/static/js/table.ui.js
@@ -0,0 +1,1038 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from 'top/browser/server_groups/servers/static/js/sec_label.ui';
+import _ from 'lodash';
+import { isEmptyString } from 'sources/validators';
+import PrimaryKeySchema from '../../constraints/index_constraint/static/js/primary_key.ui';
+import { SCHEMA_STATE_ACTIONS } from '../../../../../../../../static/js/SchemaView';
+import { PartitionKeysSchema, PartitionsSchema } from './partition.utils.ui';
+import CheckConstraintSchema from '../../constraints/check_constraint/static/js/check_constraint.ui';
+import UniqueConstraintSchema from '../../constraints/index_constraint/static/js/unique_constraint.ui';
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import { getNodeColumnSchema } from '../../columns/static/js/column.ui';
+import { getNodeVacuumSettingsSchema } from '../../../../../static/js/vacuum.ui';
+import { getNodeForeignKeySchema } from '../../constraints/foreign_key/static/js/foreign_key.ui';
+import { getNodeExclusionConstraintSchema } from '../../constraints/exclusion_constraint/static/js/exclusion_constraint.ui';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import pgAdmin from 'sources/pgadmin';
+
+export function getNodeTableSchema(treeNodeInfo, itemNodeData, pgBrowser) {
+ const spcname = ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ });
+
+ let tableNode = pgBrowser.Nodes['table'];
+
+ return new TableSchema(
+ {
+ relowner: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }, (d)=>{
+ // If schema name start with pg_* then we need to exclude them
+ return !(d?.label.match(/^pg_/));
+ }),
+ spcname: spcname,
+ coll_inherits: ()=>getNodeAjaxOptions('get_inherits', tableNode, treeNodeInfo, itemNodeData),
+ typname: ()=>getNodeAjaxOptions('get_oftype', tableNode, treeNodeInfo, itemNodeData),
+ like_relation: ()=>getNodeAjaxOptions('get_relations', tableNode, treeNodeInfo, itemNodeData),
+ table_amname_list: ()=>getNodeAjaxOptions('get_table_access_methods', tableNode, treeNodeInfo, itemNodeData),
+ },
+ treeNodeInfo,
+ {
+ columns: ()=>getNodeColumnSchema(treeNodeInfo, itemNodeData, pgBrowser),
+ vacuum_settings: ()=>getNodeVacuumSettingsSchema(tableNode, treeNodeInfo, itemNodeData),
+ constraints: ()=>new ConstraintsSchema(
+ treeNodeInfo,
+ ()=>getNodeForeignKeySchema(treeNodeInfo, itemNodeData, pgBrowser, true, {autoindex: false}),
+ ()=>getNodeExclusionConstraintSchema(treeNodeInfo, itemNodeData, pgBrowser, true),
+ {spcname: spcname},
+ ),
+ },
+ (privileges)=>getNodePrivilegeRoleSchema(tableNode, treeNodeInfo, itemNodeData, privileges),
+ (params)=>{
+ return getNodeAjaxOptions('get_columns', tableNode, treeNodeInfo, itemNodeData, {urlParams: params, useCache:false});
+ },
+ ()=>getNodeAjaxOptions('get_collations', pgBrowser.Nodes['collation'], treeNodeInfo, itemNodeData),
+ ()=>getNodeAjaxOptions('get_op_class', pgBrowser.Nodes['table'], treeNodeInfo, itemNodeData),
+ ()=>{
+ return getNodeAjaxOptions('get_attach_tables', tableNode, treeNodeInfo, itemNodeData, {useCache:false, urlWithId: true});
+ },
+ {
+ relowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: treeNodeInfo.schema?._label,
+ }
+ );
+}
+
+export class ConstraintsSchema extends BaseUISchema {
+ constructor(nodeInfo, getFkObj, getExConsObj, otherOptions, inErd=false) {
+ super();
+ this.nodeInfo = nodeInfo;
+ this.primaryKeyObj = new PrimaryKeySchema({
+ spcname: otherOptions.spcname,
+ }, nodeInfo);
+ this.fkObj = getFkObj();
+ this.uniqueConsObj = new UniqueConstraintSchema({
+ spcname: otherOptions.spcname,
+ }, nodeInfo);
+ this.exConsObj = getExConsObj();
+ this.inErd = inErd;
+ }
+
+ changeColumnOptions(colOptions) {
+ this.primaryKeyObj.changeColumnOptions(colOptions);
+ this.fkObj.changeColumnOptions(colOptions);
+ this.uniqueConsObj.changeColumnOptions(colOptions);
+ if(!this.inErd) {
+ this.exConsObj.changeColumnOptions(colOptions);
+ }
+ }
+
+ anyColumnAdded(state) {
+ return _.some(_.map(state.columns, 'name'));
+ }
+
+ canAdd(state) {
+ return !(state.is_partitioned && this.top.getServerVersion() < 110000);
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'primary_key', label: '',
+ schema: this.primaryKeyObj,
+ editable: false, type: 'collection',
+ group: gettext('Primary Key'), mode: ['edit', 'create'],
+ canEdit: true, canDelete: true, deps:['is_partitioned', 'typname', 'columns'],
+ columns : ['name', 'columns'],
+ disabled: this.inCatalog,
+ canAdd: function(state) {
+ return obj.canAdd(state);
+ },
+ canAddRow: function(state) {
+ return ((state.primary_key||[]).length < 1 && obj.anyColumnAdded(state));
+ },
+ expandEditOnAdd: true,
+ depChange: (state, source, topState, actionObj)=>{
+ if (state.is_partitioned && obj.top.getServerVersion() < 110000 || state.columns?.length <= 0) {
+ return {primary_key: []};
+ }
+ /* If columns changed */
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE && actionObj.path[actionObj.path.length-1] == 'columns') {
+ /* Sync up the pk flag */
+ let columns = state.primary_key[0].columns.map((c)=>c.column);
+ state.columns = state.columns.map((c)=>({
+ ...c, is_primary_key: columns.indexOf(c.name) > -1,
+ }));
+ return {columns: state.columns};
+ }
+ /* If column or primary key is deleted */
+ if(actionObj.type === SCHEMA_STATE_ACTIONS.DELETE_ROW) {
+ let deletedColumn = _.differenceBy(actionObj.oldState.columns,state.columns,'cid');
+ if(deletedColumn.length && deletedColumn[0].is_primary_key && !obj.top.isNew(state)) {
+ state.columns = state.columns.map(c=>({
+ ...c, is_primary_key: false
+ }));
+ return {primary_key: []};
+ } else if(source[0] === 'primary_key') {
+ state.columns = state.columns.map(c=>({
+ ...c, is_primary_key: false
+ }));
+ }
+ }
+ }
+ },{
+ id: 'foreign_key', label: '',
+ schema: this.fkObj,
+ editable: false, type: 'collection',
+ group: gettext('Foreign Key'), mode: ['edit', 'create'],
+ canEdit: true, canDelete: true, deps:['is_partitioned', 'columns'],
+ canAdd: function(state) {
+ return obj.canAdd(state);
+ },
+ columns : ['name', 'columns','references_table_name'],
+ disabled: this.inCatalog,
+ canAddRow: obj.anyColumnAdded,
+ expandEditOnAdd: true,
+ depChange: (state)=>{
+ if (state.is_partitioned && obj.top.getServerVersion() < 110000 || state.columns?.length <= 0) {
+ return {foreign_key: []};
+ }
+ }
+ },{
+ id: 'check_group', type: 'group', label: gettext('Check'), visible: !this.inErd,
+ },{
+ id: 'check_constraint', label: '',
+ schema: new CheckConstraintSchema(),
+ editable: false, type: 'collection',
+ group: 'check_group', mode: ['edit', 'create'],
+ canEdit: true, canDelete: true, deps:['is_partitioned'],
+ canAdd: true,
+ columns : ['name', 'consrc'],
+ disabled: this.inCatalog,
+ },{
+ id: 'unique_group', type: 'group', label: gettext('Unique'),
+ },{
+ id: 'unique_constraint', label: '',
+ schema: this.uniqueConsObj,
+ editable: false, type: 'collection',
+ group: 'unique_group', mode: ['edit', 'create'],
+ canEdit: true, canDelete: true, deps:['is_partitioned', 'typname'],
+ columns : ['name', 'columns'],
+ disabled: this.inCatalog,
+ canAdd: function(state) {
+ return obj.canAdd(state);
+ },
+ canAddRow: obj.anyColumnAdded,
+ expandEditOnAdd: true,
+ depChange: (state)=>{
+ if (state.is_partitioned && obj.top.getServerVersion() < 110000 || state.columns?.length <= 0) {
+ return {unique_constraint: []};
+ }
+ }
+ },{
+ id: 'exclude_group', type: 'group', label: gettext('Exclude'), visible: !this.inErd,
+ },{
+ id: 'exclude_constraint', label: '',
+ schema: this.exConsObj,
+ editable: false, type: 'collection',
+ group: 'exclude_group', mode: ['edit', 'create'],
+ canEdit: true, canDelete: true, deps:['is_partitioned'],
+ columns : ['name', 'columns', 'constraint'],
+ disabled: this.inCatalog,
+ canAdd: function(state) {
+ return obj.canAdd(state);
+ },
+ canAddRow: obj.anyColumnAdded,
+ expandEditOnAdd: true,
+ depChange: (state)=>{
+ if (state.is_partitioned && obj.top.getServerVersion() < 110000 || state.columns?.length <= 0) {
+ return {exclude_constraint: []};
+ }
+ },
+ }];
+ }
+}
+
+export class LikeSchema extends BaseUISchema {
+ constructor(likeRelationOpts) {
+ super();
+ this.likeRelationOpts = likeRelationOpts;
+ }
+
+ isLikeDisable(state) {
+ return !(!this.top.inSchemaWithModelCheck(state) && isEmptyString(state.typname));
+ }
+
+ isRelationDisable(state) {
+ return isEmptyString(state.like_relation);
+ }
+
+ resetVals(state) {
+ if(this.isRelationDisable(state) && this.top.isNew()) {
+ return {
+ like_default_value: false,
+ like_constraints: false,
+ like_indexes: false,
+ like_storage: false,
+ like_comments: false,
+ like_compression: false,
+ like_generated: false,
+ like_identity: false,
+ like_statistics: false
+ };
+ }
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'like_relation', label: gettext('Relation'),
+ type: 'select', mode: ['create'], deps: ['typname', 'like_relation'],
+ options: obj.likeRelationOpts,
+ disabled: obj.isLikeDisable,
+ depChange: (state, source)=>{
+ if(source == 'typname' && !isEmptyString(state.typname)) {
+ state.like_relation = null;
+ return {
+ like_relation: null,
+ ...obj.resetVals(state),
+ };
+ }
+ }
+ },{
+ id: 'like_default_value', label: gettext('With default values?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_constraints', label: gettext('With constraints?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_indexes', label: gettext('With indexes?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_storage', label: gettext('With storage?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_comments', label: gettext('With comments?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_compression', label: gettext('With compression?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ min_version: 140000, inlineNext: true,
+ },{
+ id: 'like_generated', label: gettext('With generated?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ min_version: 120000, inlineNext: true,
+ },{
+ id: 'like_identity', label: gettext('With identity?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ inlineNext: true,
+ },{
+ id: 'like_statistics', label: gettext('With statistics?'),
+ type: 'switch', mode: ['create'], deps: ['like_relation'],
+ disabled: this.isRelationDisable, depChange: (...args)=>obj.resetVals(...args),
+ }
+ ];
+ }
+}
+
+export default class TableSchema extends BaseUISchema {
+ constructor(fieldOptions={}, nodeInfo={}, schemas={}, getPrivilegeRoleSchema=()=>{/*This is intentional (SonarQube)*/}, getColumns=()=>[],
+ getCollations=()=>[], getOperatorClass=()=>[], getAttachTables=()=>[], initValues={}, inErd=false) {
+ super({
+ name: undefined,
+ oid: undefined,
+ spcoid: undefined,
+ spcname: undefined,
+ relowner: undefined,
+ relacl: undefined,
+ relhasoids: undefined,
+ relhassubclass: undefined,
+ reltuples: undefined,
+ description: undefined,
+ conname: undefined,
+ conkey: undefined,
+ isrepl: undefined,
+ triggercount: undefined,
+ relpersistence: undefined,
+ fillfactor: undefined,
+ toast_tuple_target: undefined,
+ parallel_workers: undefined,
+ reloftype: undefined,
+ typname: undefined,
+ labels: undefined,
+ providers: undefined,
+ is_sys_table: undefined,
+ coll_inherits: [],
+ hastoasttable: true,
+ toast_autovacuum_enabled: 'x',
+ autovacuum_enabled: 'x',
+ primary_key: [],
+ foreign_key: [],
+ partition_keys: [],
+ partitions: [],
+ partition_type: 'range',
+ is_partitioned: false,
+ columns: [],
+ amname: undefined,
+ ...initValues,
+ });
+
+ this.fieldOptions = fieldOptions;
+ this.schemas = schemas;
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.nodeInfo = nodeInfo;
+ this.getColumns = getColumns;
+
+ this.partitionsObj = new PartitionsSchema(this.nodeInfo, getCollations, getOperatorClass, fieldOptions.table_amname_list, getAttachTables);
+ this.constraintsObj = this.schemas.constraints?.() || {};
+ this.columnsSchema = this.schemas.columns?.() || {};
+ this.vacuumSettingsSchema = this.schemas.vacuum_settings?.() || {};
+ this.partitionKeysObj = new PartitionKeysSchema([], getCollations, getOperatorClass);
+ this.inErd = inErd;
+ }
+
+ static getErdSupportedData(data) {
+ let newData = {...data};
+ const SUPPORTED_KEYS = [
+ 'name', 'schema', 'description', 'rlspolicy', 'forcerlspolicy', 'fillfactor',
+ 'toast_tuple_target', 'parallel_workers', 'relhasoids', 'relpersistence',
+ 'columns', 'primary_key', 'foreign_key', 'unique_constraint',
+ ];
+ newData = _.pick(newData, SUPPORTED_KEYS);
+
+ /* Remove inherited references */
+ newData.columns = newData.columns.map((c)=>{
+ delete c.inheritedfromtable;
+ return c;
+ });
+
+ /* Make autoindex as true if there is coveringindex since ERD works in create mode */
+ newData.foreign_key = (newData.foreign_key||[]).map((fk)=>{
+ fk.autoindex = false;
+ if(fk.coveringindex) {
+ fk.autoindex = true;
+ }
+ return fk;
+ });
+ return newData;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ initialise(state) {
+ this.changeColumnOptions(state.columns);
+ }
+
+ inSchemaWithModelCheck(state) {
+ if(this.nodeInfo && 'schema' in this.nodeInfo) {
+ return !this.isNew(state);
+ }
+ return false;
+ }
+
+ getTableOid(tabName) {
+ // Here we will fetch the table oid from table name
+ // iterate over list to find table oid
+ for(const t of this.inheritedTableList) {
+ if(t.label === tabName) {
+ return t.tid;
+ }
+ }
+ }
+
+ // Check for column grid when to Add
+ canAddRowColumns(state) {
+ if(!this.inCatalog()) {
+ // if of_type then disable add in grid
+ return isEmptyString(state.typname);
+ }
+ return false;
+ }
+
+ // Check for column grid when to edit/delete (for each row)
+ canEditDeleteRowColumns(colstate) {
+ return isEmptyString(colstate.inheritedfrom);
+ }
+
+ isPartitioned(state) {
+ if(state.is_partitioned) {
+ return true;
+ }
+ return this.inCatalog();
+ }
+
+ changeColumnOptions(columns) {
+ let colOptions = (columns||[]).map((c)=>({label: c.name, value: c.name, image:'icon-column', cid:c.cid}));
+ this.constraintsObj.changeColumnOptions(colOptions);
+ this.partitionKeysObj.changeColumnOptions(colOptions);
+ this.partitionsObj.changeColumnOptions(colOptions);
+ }
+
+ get baseFields() {
+ let obj = this;
+
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text', noEmpty: true,
+ mode: ['properties', 'create', 'edit'], readonly: this.inCatalog,
+ },{
+ id: 'oid', label: gettext('OID'), type: 'text', mode: ['properties'],
+ },{
+ id: 'relowner', label: gettext('Owner'), type: 'select',
+ options: this.fieldOptions.relowner, noEmpty: !this.inErd,
+ mode: ['properties', 'create', 'edit'], controlProps: {allowClear: false},
+ readonly: this.inCatalog, visible: !this.inErd,
+ },{
+ id: 'schema', label: gettext('Schema'), type: 'select',
+ options: this.fieldOptions.schema, noEmpty: true,
+ mode: ['create', 'edit'],
+ readonly: this.inCatalog,
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ visible: !this.inErd,
+ mode: ['properties', 'create', 'edit'], deps: ['is_partitioned'],
+ readonly: this.inCatalog, type: (state)=>{
+ return {
+ type: 'select', options: this.fieldOptions.spcname,
+ controlProps: {
+ allowClear: obj.isNew(state),
+ }
+ };
+ }
+ },{
+ id: 'partition', type: 'group', label: gettext('Partitions'),
+ mode: ['edit', 'create'], min_version: 100000,
+ visible: function(state) {
+ if(this.inErd) {
+ return false;
+ }
+ // Always show in case of create mode
+ return (obj.isNew(state) || state.is_partitioned);
+ },
+ },{
+ id: 'is_partitioned', label:gettext('Partitioned table?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ min_version: 100000, visible: !this.inErd,
+ readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'is_sys_table', label: gettext('System table?'), cell: 'switch',
+ type: 'switch', mode: ['properties'],
+ disabled: this.inCatalog,
+ },{
+ id: 'description', label: gettext('Comment'), type: 'multiline',
+ mode: ['properties', 'create', 'edit'], disabled: this.inCatalog,
+ },{
+ id: 'coll_inherits', label: gettext('Inherited from table(s)'),
+ type: 'select', group: gettext('Columns'),
+ deps: ['typname', 'is_partitioned'], mode: ['create', 'edit'],
+ controlProps: { multiple: true, allowClear: false, placeholder: gettext('Select to inherit from...')},
+ options: this.fieldOptions.coll_inherits, visible: !this.inErd,
+ optionsLoaded: (res)=>obj.inheritedTableList=res,
+ disabled: (state)=>{
+ if(state.adding_inherit_cols || state.is_partitioned){
+ return true;
+ }
+ return !(!obj.inCatalog() && isEmptyString(state.typname));
+ },
+ depChange: (state, source, topState, actionObj)=>{
+ if(actionObj.type == SCHEMA_STATE_ACTIONS.SET_VALUE && actionObj.path[0] == 'coll_inherits') {
+ return {adding_inherit_cols: true};
+ }
+ if(source[0] === 'is_partitioned' && state.is_partitioned) {
+ for(const collTable of state.coll_inherits || []) {
+ let removeOid = this.getTableOid(collTable);
+ _.remove(state.columns, (col)=>col.inheritedid==removeOid);
+ }
+
+ return {
+ coll_inherits: [],
+ };
+ }
+ },
+ deferredDepChange: (state, source, topState, actionObj)=>{
+ return new Promise((resolve)=>{
+ // current table list and previous table list
+ let newColInherits = state.coll_inherits || [];
+ let oldColInherits = actionObj.oldState.coll_inherits || [];
+
+ let tabName;
+ let tabColsResponse;
+
+ // Add columns logic
+ // If new table is added in list
+ if(newColInherits.length > 1 && newColInherits.length > oldColInherits.length) {
+ // Find newly added table from current list
+ tabName = _.difference(newColInherits, oldColInherits);
+ tabColsResponse = obj.getColumns({tid: this.getTableOid(tabName[0])});
+ } else if (newColInherits.length == 1) {
+ // First table added
+ tabColsResponse = obj.getColumns({tid: this.getTableOid(newColInherits[0])});
+ }
+
+ if(tabColsResponse) {
+ tabColsResponse.then((res)=>{
+ resolve((tmpstate)=>{
+ let finalCols = res.map((col)=>obj.columnsSchema.getNewData(col));
+ let currentSelectedCols = [];
+ if (!_.isEmpty(tmpstate.columns)){
+ currentSelectedCols = tmpstate.columns;
+ }
+ let colNameList = [];
+ tmpstate.columns.forEach((col=>{
+ colNameList.push(col.name);
+ }));
+ for (let col of Object.values(finalCols)) {
+ if(!colNameList.includes(col.name)){
+ currentSelectedCols.push(col);
+ }
+ }
+
+ if (!_.isEmpty(currentSelectedCols)){
+ finalCols = currentSelectedCols;
+ }
+
+ obj.changeColumnOptions(finalCols);
+ return {
+ adding_inherit_cols: false,
+ columns: finalCols,
+ };
+ });
+ });
+ }
+
+ // Remove columns logic
+ let removeOid;
+ if(newColInherits.length > 0 && newColInherits.length < oldColInherits.length) {
+ // Find deleted table from previous list
+ tabName = _.difference(oldColInherits, newColInherits);
+ removeOid = this.getTableOid(tabName[0]);
+ } else if (oldColInherits.length === 1 && newColInherits.length < 1) {
+ // We got last table from list
+ tabName = oldColInherits[0];
+ removeOid = this.getTableOid(tabName);
+ }
+ if(removeOid) {
+ resolve((tmpstate)=>{
+ let finalCols = tmpstate.columns;
+ _.remove(tmpstate.columns, (col)=>col.inheritedid==removeOid);
+ obj.changeColumnOptions(finalCols);
+ return {
+ adding_inherit_cols: false,
+ columns: finalCols
+ };
+ });
+ }
+ });
+ },
+ },{
+ id: 'advanced', label: gettext('Advanced'), type: 'group',
+ visible: true,
+ },
+ {
+ id: 'rlspolicy', label: gettext('RLS Policy?'), cell: 'switch',
+ type: 'switch', mode: ['properties','edit', 'create'],
+ group: 'advanced', min_version: 90600,
+ depChange: (state)=>{
+ if (state.rlspolicy && this.origData.rlspolicy != state.rlspolicy) {
+ pgAdmin.Browser.notifier.alert(
+ gettext('Check Policy?'),
+ gettext('Please check if any policy exists. If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified by other users')
+ );
+ }
+ }
+ },
+ {
+ id: 'forcerlspolicy', label: gettext('Force RLS Policy?'), cell: 'switch',
+ type: 'switch', mode: ['properties','edit', 'create'], deps: ['rlspolicy'],
+ group: 'advanced', min_version: 90600,
+ disabled: function(state) {
+ return !state.rlspolicy;
+ },
+ depChange: (state)=>{
+ if(!state.rlspolicy) {
+ return {forcerlspolicy: false};
+ }
+ }
+ },
+ {
+ id: 'replica_identity', label: gettext('Replica Identity'),
+ group: 'advanced', type: 'text',mode: ['edit', 'properties'],
+ }, {
+ id: 'coll_inherits', label: gettext('Inherited from table(s)'),
+ type: 'text', group: 'advanced', mode: ['properties'],
+ },{
+ id: 'inherited_tables_cnt', label: gettext('Inherited tables count'),
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ // Tab control for columns
+ id: 'columns', label: gettext('Columns'), type: 'collection',
+ group: gettext('Columns'),
+ schema: this.columnsSchema,
+ mode: ['create', 'edit'],
+ disabled: this.inCatalog,
+ deps: ['typname', 'is_partitioned'],
+ depChange: (state, source, topState, actionObj)=>{
+ if(source[0] === 'columns') {
+ /* In ERD, attnum is an imp let for setting the links
+ Here, attnum is set to max avail value.
+ */
+ let columns = state.columns;
+ if(actionObj.type === SCHEMA_STATE_ACTIONS.ADD_ROW && this.inErd) {
+ let lastAttnum = _.maxBy(columns, (c)=>c.attnum)?.attnum;
+ if(_.isUndefined(lastAttnum) || _.isNull(lastAttnum)) {
+ lastAttnum = -1;
+ }
+ columns[columns.length-1].attnum = lastAttnum + 1;
+ }
+ obj.changeColumnOptions(columns);
+ /* If primary key switch changes, primary key collection need to change */
+ if(actionObj.path.indexOf('is_primary_key') > -1) {
+ let tabColPath = _.slice(actionObj.path, 0, -1);
+ let columnData = _.get(state, tabColPath);
+ if(state.primary_key?.length > 0) {
+ /* Add/Remove columns if PK exists */
+ let currPk = state.primary_key[0];
+ /* If col is not PK, remove it */
+ if(!columnData.is_primary_key) {
+ currPk.columns = _.filter(currPk.columns, (c)=>c.cid !== columnData.cid);
+ } else {
+ currPk.columns = _.filter(currPk.columns, (c)=>c.cid !== columnData.cid);
+ currPk.columns.push({
+ column: columnData.name,
+ cid: columnData.cid,
+ });
+ }
+ /* Remove the PK if all columns not PK */
+ if(currPk.columns.length <= 0) {
+ return {primary_key: []};
+ } else {
+ return {primary_key: [currPk]};
+ }
+ } else {
+ /* Create PK if none */
+ return {primary_key: [
+ obj.constraintsObj.primaryKeyObj.getNewData({
+ columns: [{column: columnData.name, cid: columnData.cid}],
+ })
+ ]};
+ }
+ }
+ }
+ },
+ canAdd: this.canAddRowColumns,
+ canEdit: true, canDelete: true,
+ canReorder: (state)=>(this.inErd || this.isNew(state)),
+ // For each row edit/delete button enable/disable
+ canEditRow: this.canEditDeleteRowColumns,
+ canDeleteRow: this.canEditDeleteRowColumns,
+ uniqueCol : ['name'],
+ columns : ['name' , 'cltype', 'attlen', 'attprecision', 'attnotnull', 'is_primary_key', 'defval'],
+ allowMultipleEmptyRow: false,
+ },{
+ // Here we will create tab control for constraints
+ type: 'nested-tab', group: gettext('Constraints'),
+ mode: ['edit', 'create'],
+ schema: obj.constraintsObj,
+ },{
+ id: 'typname', label: gettext('Of type'), type: 'select',
+ mode: ['properties', 'create', 'edit'], group: 'advanced', deps: ['coll_inherits'],
+ visible: !this.inErd,
+ disabled: (state)=>{
+ return !(!obj.inSchemaWithModelCheck(state) && isEmptyString(state.coll_inherits));
+ }, options: this.fieldOptions.typname, optionsLoaded: (res)=>{
+ obj.ofTypeTables = res;
+ },
+ deferredDepChange: (state, source, topState, actionObj)=>{
+ const setColumns = (resolve)=>{
+ let finalCols = [];
+ if(!isEmptyString(state.typname)) {
+ let typeTable = _.find(obj.ofTypeTables||[], (t)=>t.label==state.typname);
+ finalCols = typeTable.oftype_columns;
+ }
+ resolve(()=>{
+ obj.changeColumnOptions(finalCols);
+ return {
+ columns: finalCols,
+ primary_key: [],
+ foreign_key: [],
+ exclude_constraint: [],
+ unique_constraint: [],
+ partition_keys: [],
+ partitions: [],
+ };
+ });
+ };
+ if(!isEmptyString(state.typname) && isEmptyString(actionObj.oldState.typname)) {
+ return new Promise((resolve)=>{
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Remove column definitions?'),
+ gettext('Changing \'Of type\' will remove column definitions.'),
+ function () {
+ setColumns(resolve);
+ },
+ function() {
+ resolve(()=>{
+ return {
+ typname: null,
+ };
+ });
+ }
+ );
+ });
+ } else if(state.typname != actionObj.oldState.typname) {
+ return new Promise((resolve)=>{
+ setColumns(resolve);
+ });
+ } else {
+ return Promise.resolve(()=>{/*This is intentional (SonarQube)*/});
+ }
+ },
+ },
+ {
+ id: 'amname', label: gettext('Access Method'), group: 'advanced',
+ deps:['is_partitioned'], type: (state)=>{
+ return {
+ type: 'select', options: this.fieldOptions.table_amname_list,
+ controlProps: {
+ allowClear: obj.isNew(state),
+ }
+ };
+ }, mode: ['create', 'properties', 'edit'], min_version: 120000,
+ disabled: (state) => {
+ if (obj.getServerVersion() < 150000 && !obj.isNew(state)) {
+ return true;
+ }
+ return obj.isPartitioned(state);
+ }, depChange: state => {
+ if (state.is_partitioned) {
+ return {
+ amname: undefined
+ };
+ }
+ },
+ },
+ {
+ id: 'fillfactor', label: gettext('Fill factor'), type: 'int',
+ mode: ['create', 'edit'], min: 10, max: 100,
+ group: 'advanced',
+ disabled: obj.isPartitioned,
+ },{
+ id: 'toast_tuple_target', label: gettext('Toast tuple target'), type: 'int',
+ mode: ['create', 'edit'], min: 128, min_version: 110000,
+ group: 'advanced',
+ disabled: obj.isPartitioned,
+ },{
+ id: 'parallel_workers', label: gettext('Parallel workers'), type: 'int',
+ mode: ['create', 'edit'], group: 'advanced', min_version: 90600,
+ disabled: obj.isPartitioned,
+ },
+ {
+ id: 'relhasoids', label: gettext('Has OIDs?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ group: 'advanced',
+ disabled: function() {
+ if(obj.getServerVersion() >= 120000) {
+ return true;
+ }
+ return obj.inCatalog();
+ },
+ },{
+ id: 'relpersistence', label: gettext('Unlogged?'), cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ readonly: obj.inSchemaWithModelCheck,
+ group: 'advanced',
+ },{
+ id: 'conname', label: gettext('Primary key'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ id: 'reltuples', label: gettext('Rows (estimated)'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ id: 'rows_cnt', label: gettext('Rows (counted)'), cell: 'text',
+ type: 'text', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ formatter: {
+ fromRaw: ()=>{
+ return 0;
+ },
+ toRaw: (backendVal)=>{
+ return backendVal;
+ },
+ },
+ },{
+ id: 'relhassubclass', label: gettext('Is inherited?'), cell: 'switch',
+ type: 'switch', mode: ['properties'], group: 'advanced',
+ disabled: this.inCatalog,
+ },{
+ type: 'nested-fieldset', label: gettext('Like'),
+ group: 'advanced', mode: ['create'],
+ schema: new LikeSchema(this.fieldOptions.like_relation),
+ visible: !this.inErd,
+ },{
+ id: 'partition_type', label:gettext('Partition Type'),
+ editable: false, type: 'select', controlProps: {allowClear: false},
+ group: 'partition', deps: ['is_partitioned'],
+ options: function() {
+ let options = [{
+ label: gettext('Range'), value: 'range',
+ },{
+ label: gettext('List'), value: 'list',
+ }];
+
+ if(obj.getServerVersion() >= 110000) {
+ options.push({
+ label: gettext('Hash'), value: 'hash',
+ });
+ }
+ return Promise.resolve(options);
+ },
+ mode:['create'],
+ min_version: 100000,
+ disabled: function(state) {
+ return !state.is_partitioned;
+ },
+ readonly: function(state) {return !obj.isNew(state);},
+ },
+ {
+ id: 'partition_keys', label:gettext('Partition Keys'),
+ schema: obj.partitionKeysObj,
+ editable: true, type: 'collection',
+ columns: ['key_type', 'pt_column', 'expression'].concat(!this.inErd ? ['collationame', 'op_class'] : []),
+ group: 'partition', mode: ['create'],
+ deps: ['is_partitioned', 'partition_type', 'typname'],
+ canEdit: false, canDelete: true,
+ canAdd: function(state) {
+ return obj.isNew(state) && state.is_partitioned;
+ },
+ canAddRow: function(state) {
+ let columnsExist = false;
+
+ let maxRowCount = 1000;
+ if (state.partition_type && state.partition_type == 'list')
+ maxRowCount = 1;
+
+ if (state.columns?.length > 0) {
+ columnsExist = _.some(_.map(state.columns, 'name'));
+ }
+
+ if(state.partition_keys) {
+ return state.partition_keys.length < maxRowCount && columnsExist;
+ }
+
+ return true;
+ }, min_version: 100000,
+ depChange: (state, source, topState, actionObj)=>{
+ if(state.typname != actionObj.oldState.typname) {
+ return {
+ partition_keys: [],
+ };
+ }
+ }
+ },
+ {
+ id: 'partition_scheme', label: gettext('Partition Scheme'),
+ group: 'partition', mode: ['edit'],
+ type: (state)=>({
+ type: 'note',
+ text: state.partition_scheme || '',
+ }),
+ min_version: 100000,
+ },
+ {
+ id: 'partition_key_note', label: gettext('Partition Keys'),
+ type: 'note', group: 'partition', mode: ['create'],
+ text: [
+ '',
+ gettext('Partition table supports two types of keys:'),
+ ' ',
+ '', gettext('Column: '), ' ',
+ gettext('User can select any column from the list of available columns.'),
+ ' ',
+ '', gettext('Expression: '), ' ',
+ gettext('User can specify expression to create partition key.'),
+ ' ',
+ '', gettext('Example: '), ' ',
+ gettext('Let\'s say, we want to create a partition table based per year for the column \'saledate\', having datatype \'date/timestamp\', then we need to specify the expression as \'extract(YEAR from saledate)\' as partition key.'),
+ ' ',
+ ].join(''),
+ min_version: 100000,
+ },
+ {
+ id: 'partitions', label: gettext('Partitions'),
+ schema: this.partitionsObj,
+ editable: true, type: 'collection',
+ group: 'partition', mode: ['edit', 'create'],
+ deps: ['is_partitioned', 'partition_type', 'typname'],
+ depChange: (state, source)=>{
+ if(['is_partitioned', 'partition_type', 'typname'].indexOf(source[0]) >= 0 && obj.isNew(state)){
+ return {'partitions': []};
+ }
+ },
+ canEdit: true, canDelete: true,
+ customDeleteTitle: gettext('Detach Partition'),
+ customDeleteMsg: gettext('Are you sure you wish to detach this partition?'),
+ columns:['is_attach', 'partition_name', 'is_default', 'values_from', 'values_to', 'values_in', 'values_modulus', 'values_remainder'],
+ canAdd: function(state) {
+ return state.is_partitioned;
+ },
+ min_version: 100000,
+ },
+ {
+ id: 'partition_note', label: gettext('Partitions'),
+ type: 'note', group: 'partition', mode: ['create'],
+ text: [
+ '',
+ '', gettext('Create a table: '), ' ',
+ gettext('User can create multiple partitions while creating new partitioned table. Operation switch is disabled in this scenario.'),
+ ' ',
+ '', gettext('Edit existing table: '), ' ',
+ gettext('User can create/attach/detach multiple partitions. In attach operation user can select table from the list of suitable tables to be attached.'),
+ ' ',
+ '', gettext('Default: '), ' ',
+ gettext('The default partition can store rows that do not fall into any existing partition’s range or list.'),
+ ' ',
+ '', gettext('From/To/In input: '), ' ',
+ gettext('From/To/In input: Values for these fields must be quoted with single quote. For more than one partition key values must be comma(,) separated.'),
+ ' ',
+ '', gettext('Example: From/To: '), ' ',
+ gettext('Enabled for range partition. Consider partitioned table with multiple keys of type Integer, then values should be specified like \'100\',\'200\'.'),
+ ' ',
+ '', gettext('In: '), ' ',
+ gettext('Enabled for list partition. Values must be comma(,) separated and quoted with single quote.'),
+ ' ',
+ '', gettext('Modulus/Remainder: '), ' ',
+ gettext('Enabled for hash partition.'),
+ ' ',
+ ].join(''),
+ min_version: 100000,
+ },{
+ type: 'group', id: 'parameters', label: gettext('Parameters'),
+ visible: !this.inErd,
+ },{
+ // Here - we will create tab control for storage parameters
+ // (auto vacuum).
+ type: 'nested-tab', group: 'parameters',
+ mode: ['edit', 'create'], deps: ['is_partitioned'],
+ schema: this.vacuumSettingsSchema, visible: !this.inErd,
+ },{
+ id: 'security_group', type: 'group', label: gettext('Security'), visible: !this.inErd,
+ },
+ {
+ id: 'relacl_str', label: gettext('Privileges'), disabled: this.inCatalog,
+ type: 'text', mode: ['properties'], group: 'security_group',
+ },
+ {
+ id: 'relacl', label: gettext('Privileges'), type: 'collection',
+ group: 'security_group', schema: this.getPrivilegeRoleSchema(['a','r','w','d','D','x','t']),
+ mode: ['edit', 'create'], canAdd: true, canDelete: true,
+ uniqueCol : ['grantee'],
+ },{
+ id: 'seclabels', label: gettext('Security labels'), canEdit: false,
+ schema: new SecLabelSchema(), editable: false, canAdd: true,
+ type: 'collection', min_version: 90100, mode: ['edit', 'create'],
+ group: 'security_group', canDelete: true,
+ },{
+ id: 'vacuum_settings_str', label: gettext('Storage settings'),
+ type: 'multiline', group: 'advanced', mode: ['properties'],
+ }];
+ }
+
+ validate(state, setError) {
+ if (state.is_partitioned && this.isNew(state) &&
+ (!state.partition_keys || state.partition_keys && state.partition_keys.length <= 0)) {
+ setError('partition_keys', gettext('Please specify at least one key for partitioned table.'));
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..644998a1d5ed25c0eb599481a24c17873a08aab2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/create.sql
@@ -0,0 +1,11 @@
+{% if data %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} CHECK ({{ data.consrc }}){% if data.convalidated %}
+
+ NOT VALID{% endif %}{% if data.connoinherit %} NO INHERIT{% endif %};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..74511b5c2a26915af10995c95e48cf401198a02a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/delete.sql
@@ -0,0 +1,3 @@
+{% if data %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.nspname, data.relname) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2bd1c2ebec6819fcc6b87d4dc9058027cb311e47
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_name.sql
@@ -0,0 +1,5 @@
+SELECT conname as name,
+ NOT convalidated as convalidated
+FROM pg_catalog.pg_constraint ct
+WHERE contype = 'c'
+AND ct.oid = {{cid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b858844bad8c5c8efc787f05239b724d67843428
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid.sql
@@ -0,0 +1,8 @@
+SELECT
+ oid, conname as name,
+ NOT convalidated as convalidated
+FROM
+ pg_catalog.pg_constraint
+WHERE
+ conrelid = {{tid}}::oid
+ AND conname={{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid_with_transaction.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid_with_transaction.sql
new file mode 100644
index 0000000000000000000000000000000000000000..da17d82fe158077c816c900e14fac523ac6f8be2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_oid_with_transaction.sql
@@ -0,0 +1,7 @@
+SELECT ct.oid,
+ ct.conname as name,
+ NOT convalidated as convalidated
+FROM pg_catalog.pg_constraint ct
+WHERE contype='c' AND
+ conrelid = {{tid}}::oid
+ORDER BY ct.oid DESC LIMIT 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e8e5a1eb6c62a19bfb646655c6e0e874c447531
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/get_parent.sql
@@ -0,0 +1,7 @@
+SELECT nsp.nspname AS schema,
+ rel.relname AS table
+FROM
+ pg_catalog.pg_class rel
+JOIN pg_catalog.pg_namespace nsp
+ON rel.relnamespace = nsp.oid::oid
+WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..57e4b144ac3c1b7fe4243f2dc2bcf19756e15334
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/nodes.sql
@@ -0,0 +1,11 @@
+SELECT c.oid, conname as name,
+ NOT convalidated as convalidated, conislocal, description as comment
+ FROM pg_catalog.pg_constraint c
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND
+ des.classoid='pg_constraint'::regclass)
+WHERE contype = 'c'
+ AND conrelid = {{ tid }}::oid
+{% if cid %}
+ AND c.oid = {{ cid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5673b1312f27153f11f3264efe18990b0eebd89e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/properties.sql
@@ -0,0 +1,14 @@
+SELECT c.oid, conname as name, relname, nspname, description as comment,
+ pg_catalog.pg_get_expr(conbin, conrelid, true) as consrc,
+ connoinherit, NOT convalidated as convalidated, conislocal
+ FROM pg_catalog.pg_constraint c
+ JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
+ JOIN pg_catalog.pg_namespace nl ON nl.oid=relnamespace
+LEFT OUTER JOIN
+ pg_catalog.pg_description des ON (des.objoid=c.oid AND
+ des.classoid='pg_constraint'::regclass)
+WHERE contype = 'c'
+ AND conrelid = {{ tid }}::oid
+{% if cid %}
+ AND c.oid = {{ cid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ddcb0a41a5bd6c4b4904bc2822af6715d1c63ea1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/update.sql
@@ -0,0 +1,13 @@
+{% if data %}
+{% if data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(o_data.nspname, data.table) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};{% endif -%}
+{% if 'convalidated' in data and o_data.convalidated != data.convalidated and not data.convalidated %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(o_data.nspname, data.table) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(data.name) }};{% endif -%}
+{% if data.comment is defined and data.comment != o_data.comment %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};{% endif %}
+{% endif -%}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/validate.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/validate.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d447cf9af9a4a4bf63d482e7230e5f5074c79221
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/check_constraint/sql/default/validate.sql
@@ -0,0 +1,2 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/privilege.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/privilege.macros
new file mode 100644
index 0000000000000000000000000000000000000000..7fe81e54be5b9fac71164dca1258e0f00b00d057
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/privilege.macros
@@ -0,0 +1,13 @@
+{% macro APPLY(conn, schema_name, table_object, column_object, role, privs, with_grant_privs) -%}
+{% if privs %}
+GRANT {% for p in privs %}{% if loop.index != 1 %}, {% endif %}{{p}}({{conn|qtIdent(column_object)}}){% endfor %}
+ ON {{ conn|qtIdent(schema_name, table_object) }} TO {{ role }};
+{% endif %}
+{% if with_grant_privs %}
+GRANT {% for p in with_grant_privs %}{% if loop.index != 1 %}, {% endif %}{{p}}({{conn|qtIdent(column_object)}}){% endfor %}
+ ON {{ conn|qtIdent(schema_name, table_object) }} TO {{ role }} WITH GRANT OPTION;
+{% endif %}
+{%- endmacro %}
+{% macro RESETALL(conn, schema_name, table_object, column_object, role) -%}
+REVOKE ALL({{ conn|qtIdent(column_object) }}) ON {{ conn|qtIdent(schema_name, table_object) }} FROM {{ role }};
+{%- endmacro %}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/security.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/security.macros
new file mode 100644
index 0000000000000000000000000000000000000000..2e99342c7f9541aec4405c6ca3df8e699906870f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/macros/security.macros
@@ -0,0 +1,6 @@
+{% macro APPLY(conn, type, schema_name, parent_object, child_object, provider, label) -%}
+SECURITY LABEL{% if provider and provider != '' %} FOR {{ conn|qtIdent(provider) }}{% endif %} ON {{ type }} {{ conn|qtIdent(schema_name, parent_object, child_object) }} IS {{ label|qtLiteral(conn) }};
+{%- endmacro %}
+{% macro DROP(conn, type, schema_name, parent_object, child_object, provider) -%}
+SECURITY LABEL{% if provider and provider != '' %} FOR {{ conn|qtIdent(provider) }}{% endif %} ON {{ type }} {{ conn|qtIdent(schema_name, parent_object, child_object) }} IS NULL;
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..46df0aeea565877d68836e65320fe8ef2e2ba36a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/create.sql
@@ -0,0 +1,60 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Add column ###}
+{% if data.name and data.cltype %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ADD COLUMN {{conn|qtIdent(data.name)}} {% if is_sql %}{{data.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.attlen, data.attprecision, data.hasSqrBracket) }}{% endif %}{% if data.collspcname %}
+ COLLATE {{data.collspcname}}{% endif %}{% if data.attnotnull %}
+ NOT NULL{% endif %}{% if data.defval is defined and data.defval is not none and data.defval != '' and data.colconstype != 'g' %}
+ DEFAULT {{data.defval}}{% endif %}{% if data.colconstype == 'i' %}{% if data.attidentity and data.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif data.attidentity and data.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %}
+{% endif %}{% endif %}{% if data.colconstype == 'g' and data.genexpr and data.genexpr != '' %} GENERATED ALWAYS AS ({{data.genexpr}}) STORED{% endif %};
+
+{### Add comments ###}
+{% if data and data.description and data.description != None %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Add variables to column ###}
+{% if data.attoptions %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, data.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != data.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if data.attacl %}
+{% for priv in data.attacl %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..085053b65017aca34af748755b3acb25b139146b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/12_plus/properties.sql
@@ -0,0 +1,42 @@
+SELECT DISTINCT ON (att.attnum) att.attname as name, att.atttypid, att.attlen, att.attnum, att.attndims,
+ att.atttypmod, att.attacl, att.attnotnull, att.attoptions, att.attfdwoptions, att.attstattarget,
+ att.attstorage, att.attidentity,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval,
+ pg_catalog.format_type(ty.oid,NULL) AS typname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS displaytypname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS cltype,
+ CASE WHEN ty.typelem > 0 THEN ty.typelem ELSE ty.oid END as elemoid,
+ (SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = ty.typnamespace) as typnspname,
+ ty.typstorage AS defaultstorage,
+ description, pi.indkey,
+ (SELECT count(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=ty.typname) > 1 AS isdup,
+ CASE WHEN length(coll.collname::text) > 0 AND length(nspc.nspname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspc.nspname),'.',pg_catalog.quote_ident(coll.collname))
+ ELSE '' END AS collspcname,
+ EXISTS(SELECT 1 FROM pg_catalog.pg_constraint WHERE conrelid=att.attrelid AND contype='f' AND att.attnum=ANY(conkey)) As is_fk,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=att.attrelid AND sl1.objsubid=att.attnum) AS seclabels,
+ (CASE WHEN (att.attnum < 1) THEN true ElSE false END) AS is_sys_column,
+ (CASE WHEN (att.attidentity in ('a', 'd')) THEN 'i' WHEN (att.attgenerated in ('s')) THEN 'g' ELSE 'n' END) AS colconstype,
+ (CASE WHEN (att.attgenerated in ('s')) THEN pg_catalog.pg_get_expr(def.adbin, def.adrelid) END) AS genexpr, tab.relname as relname,
+ (CASE WHEN tab.relkind = 'v' THEN true ELSE false END) AS is_view_only,
+ seq.*
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type ty ON ty.oid=atttypid
+ LEFT OUTER JOIN pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.objsubid=att.attnum AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN (pg_catalog.pg_depend dep JOIN pg_catalog.pg_class cs ON dep.classid='pg_class'::regclass AND dep.objid=cs.oid AND cs.relkind='S') ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_index pi ON pi.indrelid=att.attrelid AND indisprimary
+ LEFT OUTER JOIN pg_catalog.pg_collation coll ON att.attcollation=coll.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+ LEFT OUTER JOIN pg_catalog.pg_sequence seq ON cs.oid=seq.seqrelid
+ LEFT OUTER JOIN pg_catalog.pg_class tab on tab.oid = att.attrelid
+WHERE att.attrelid = {{tid}}::oid
+{% if clid %}
+ AND att.attnum = {{clid}}::int
+{% endif %}
+{### To show system objects ###}
+{% if not show_sys_objects %}
+ AND att.attnum > 0
+{% endif %}
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4de4d365a66822633197103728972f25b0709d98
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/create.sql
@@ -0,0 +1,66 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Add column ###}
+{% if data.name and data.cltype %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ADD COLUMN {{conn|qtIdent(data.name)}} {% if is_sql %}{{data.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.attlen, data.attprecision, data.hasSqrBracket) }}{% endif %}{% if data.collspcname %}
+ COLLATE {{data.collspcname}}{% endif %}{% if data.attnotnull %}
+ NOT NULL{% endif %}{% if data.defval is defined and data.defval is not none and data.defval != '' and data.colconstype != 'g' %}
+ DEFAULT {{data.defval}}{% endif %}{% if data.colconstype == 'i' %}{% if data.attidentity and data.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif data.attidentity and data.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %}
+{% endif %}{% endif %}{% if data.colconstype == 'g' and data.genexpr and data.genexpr != '' %} GENERATED ALWAYS AS ({{data.genexpr}}) STORED{% endif %};
+
+{### Add comments ###}
+{% if data and data.description and data.description != None %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Add variables to column ###}
+{% if data.attoptions %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, data.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != data.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### Alter column compression value ###}
+{% if data.attcompression is defined and data.attcompression is not none and data.attcompression != '' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET COMPRESSION {{data.attcompression}};
+
+{% endif %}
+{### ACL ###}
+{% if data.attacl %}
+{% for priv in data.attacl %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fe6d037639284f04319e2b2c24a1b19ae7553355
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/properties.sql
@@ -0,0 +1,61 @@
+WITH INH_TABLES AS
+ (SELECT
+ at.attname AS name, ph.inhparent AS inheritedid, ph.inhseqno,
+ pg_catalog.concat(nmsp_parent.nspname, '.',parent.relname ) AS inheritedfrom
+ FROM
+ pg_catalog.pg_attribute at
+ JOIN
+ pg_catalog.pg_inherits ph ON ph.inhparent = at.attrelid AND ph.inhrelid = 33896::oid
+ JOIN
+ pg_catalog.pg_class parent ON ph.inhparent = parent.oid
+ JOIN
+ pg_catalog.pg_namespace nmsp_parent ON nmsp_parent.oid = parent.relnamespace
+ GROUP BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ ORDER BY at.attname, ph.inhparent, ph.inhseqno, inheritedfrom
+ )
+SELECT DISTINCT ON (att.attnum) att.attname as name, att.atttypid, att.attlen, att.attnum, att.attndims,
+ att.atttypmod, att.attacl, att.attnotnull, att.attoptions, att.attfdwoptions, att.attstattarget,
+ att.attstorage, att.attidentity,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval,
+ pg_catalog.format_type(ty.oid,NULL) AS typname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS displaytypname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS cltype,
+ inh.inheritedfrom,
+ inh.inheritedid,
+ CASE WHEN ty.typelem > 0 THEN ty.typelem ELSE ty.oid END as elemoid,
+ (SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = ty.typnamespace) as typnspname,
+ ty.typstorage AS defaultstorage,
+ description, pi.indkey,
+ (SELECT count(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=ty.typname) > 1 AS isdup,
+ CASE WHEN length(coll.collname::text) > 0 AND length(nspc.nspname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspc.nspname),'.',pg_catalog.quote_ident(coll.collname))
+ ELSE '' END AS collspcname,
+ EXISTS(SELECT 1 FROM pg_catalog.pg_constraint WHERE conrelid=att.attrelid AND contype='f' AND att.attnum=ANY(conkey)) As is_fk,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=att.attrelid AND sl1.objsubid=att.attnum) AS seclabels,
+ (CASE WHEN (att.attnum < 1) THEN true ElSE false END) AS is_sys_column,
+ (CASE WHEN (att.attidentity in ('a', 'd')) THEN 'i' WHEN (att.attgenerated in ('s')) THEN 'g' ELSE 'n' END) AS colconstype,
+ (CASE WHEN (att.attgenerated in ('s')) THEN pg_catalog.pg_get_expr(def.adbin, def.adrelid) END) AS genexpr, tab.relname as relname,
+ (CASE WHEN tab.relkind = 'v' THEN true ELSE false END) AS is_view_only,
+ (CASE WHEN att.attcompression = 'p' THEN 'pglz' WHEN att.attcompression = 'l' THEN 'lz4' END) AS attcompression,
+ seq.*
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type ty ON ty.oid=atttypid
+ LEFT OUTER JOIN pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.objsubid=att.attnum AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN (pg_catalog.pg_depend dep JOIN pg_catalog.pg_class cs ON dep.classid='pg_class'::regclass AND dep.objid=cs.oid AND cs.relkind='S') ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_index pi ON pi.indrelid=att.attrelid AND indisprimary
+ LEFT OUTER JOIN pg_catalog.pg_collation coll ON att.attcollation=coll.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+ LEFT OUTER JOIN pg_catalog.pg_sequence seq ON cs.oid=seq.seqrelid
+ LEFT OUTER JOIN pg_catalog.pg_class tab on tab.oid = att.attrelid
+ LEFT OUTER join INH_TABLES as INH ON att.attname = INH.name
+WHERE att.attrelid = {{tid}}::oid
+{% if clid %}
+ AND att.attnum = {{clid}}::int
+{% endif %}
+{### To show system objects ###}
+{% if not show_sys_objects %}
+ AND att.attnum > 0
+{% endif %}
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..97009be7361050a0d17905cd140f2f9891f0e883
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/14_plus/update.sql
@@ -0,0 +1,215 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Rename column name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ RENAME {{conn|qtIdent(o_data.name)}} TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{### Alter column type and collation ###}
+{% if (data.cltype and data.cltype != o_data.cltype) or (data.attlen is defined and data.attlen != o_data.attlen) or (data.attprecision is defined and data.attprecision != o_data.attprecision) or (data.collspcname and data.collspcname != o_data.collspcname) or data.col_type_conversion is defined %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %}
+-- WARNING:
+-- The SQL statement below would normally be used to alter the datatype for the {{o_data.name}} column, however,
+-- the current datatype cannot be cast to the target datatype so this conversion cannot be made automatically.
+
+{% endif %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %}ALTER TABLE {{conn|qtIdent(data.schema, data.table)}}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %} ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} TYPE {{ GET_TYPE.UPDATE_TYPE_SQL(conn, data, o_data) }}{% if data.collspcname and data.collspcname != o_data.collspcname and data.cltype != '"char"' %}
+ COLLATE {{data.collspcname}}{% elif o_data.collspcname and data.cltype != '"char"' %} COLLATE {{o_data.collspcname}}{% endif %};
+{% endif %}
+{### Alter column default value ###}
+{% if is_view_only and data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER VIEW {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% elif data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% endif %}
+{### Drop column default value ###}
+{% if data.defval is defined and (data.defval == '' or data.defval is none) and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP DEFAULT;
+
+{% endif %}
+{### Alter column not null value ###}
+{% if 'attnotnull' in data and data.attnotnull != o_data.attnotnull %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attnotnull %}SET{% else %}DROP{% endif %} NOT NULL;
+
+{% endif %}
+{% if data.seqincrement or (data.seqcycle or (data.seqcycle == False and data.seqcycle != o_data.seqcycle)) or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}
+{% set attidentity_params = true %}{% else %}
+{% set attidentity_params = false %}{% endif %}
+{### Alter column - add identity ###}
+{% if data.colconstype == 'i' and 'attidentity' in data and o_data.attidentity == '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attidentity == 'a' %}ADD GENERATED ALWAYS AS IDENTITY{% else%}ADD GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %};
+
+{### Alter column - change identity - sequence options ###}
+{% elif 'attidentity' in data or attidentity_params %}
+{% if 'attidentity' in data and data.attidentity != '' and o_data.attidentity != '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET GENERATED {% if data.attidentity == 'a' %}ALWAYS{% else%}BY DEFAULT{% endif %}{% if attidentity_params == false %};{% endif %}
+{% elif attidentity_params %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %}{% endif %}
+{% if data.seqcycle %} SET CYCLE{% elif (data.seqcycle == False and o_data.seqcycle and data.seqcycle != o_data.seqcycle) %} SET NO CYCLE{% endif %}
+{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %} SET INCREMENT {{data.seqincrement|int}}{% endif %}
+{% if data.seqstart is defined and data.seqstart|int(-1) > -1%} RESTART SET START {{data.seqstart|int}}{% endif %}
+{% if data.seqmin is defined and data.seqmin|int(-1) > -1%} SET MINVALUE {{data.seqmin|int}}{% endif %}
+{% if data.seqmax is defined and data.seqmax|int(-1) > -1%} SET MAXVALUE {{data.seqmax|int}}{% endif %}
+{% if data.seqcache is defined and data.seqcache|int(-1) > -1%} SET CACHE {{data.seqcache|int}}{% endif %}{% if attidentity_params == true %};{% endif %}
+
+
+{% endif %}
+{### Alter column - drop identity when column constraint is changed###}
+{% if 'colconstype' in data and data.colconstype == 'n' and 'colconstype' in o_data and o_data.colconstype == 'i' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP IDENTITY;
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget != o_data.attstattarget %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != o_data.attstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### Alter column compression value ###}
+{% if data.attcompression is defined and data.attcompression is not none and data.attcompression != '' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET COMPRESSION {{data.attcompression}};
+
+{% endif %}
+{% if data.description is defined and data.description != None %}
+{% if data.name %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+{% else %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, o_data.name)}}
+{% endif %}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Update column variables ###}
+{% if 'attoptions' in data and data.attoptions != None and data.attoptions|length > 0 %}
+{% set variables = data.attoptions %}
+{% if 'deleted' in variables and variables.deleted|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', data.name, variables.deleted) }}
+{% else %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', o_data.name, variables.deleted) }}
+{% endif %}
+{% endif %}
+{% if 'added' in variables and variables.added|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.added) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.added) }}
+{% endif %}
+{% endif %}
+{% if 'changed' in variables and variables.changed|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.changed) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.changed) }}
+{% endif %}
+{% endif %}
+{% endif %}
+{### Update column privileges ###}
+{# Change the privileges #}
+{% if data.attacl %}
+{% if 'deleted' in data.attacl %}
+{% for priv in data.attacl.deleted %}
+{% if data.name %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.attacl %}
+{% for priv in data.attacl.changed %}
+{% set is_grantee_changed = (priv.grantee != priv.old_grantee) %}
+{% if data.name %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.attacl %}
+{% for priv in data.attacl.added %}
+{% if data.name %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{### Uppdate tablespace securitylabel ###}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{% if data.name %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, data.name, r.provider) }}
+{% else %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, o_data.name, r.provider) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89ac8fe62577bc74004317e7b82750e4d3111f4e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/create.sql
@@ -0,0 +1,67 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Add column ###}
+{% if data.name and data.cltype %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ADD COLUMN {{conn|qtIdent(data.name)}} {% if is_sql %}{{data.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.attlen, data.attprecision, data.hasSqrBracket) }}{% endif %}{% if data.collspcname %}
+ COLLATE {{data.collspcname}}{% endif %}{% if data.attnotnull %}
+ NOT NULL{% endif %}{% if data.defval is defined and data.defval is not none and data.defval != '' and data.colconstype != 'g' %}
+ DEFAULT {{data.defval}}{% endif %}{% if data.colconstype == 'i' %}{% if data.attidentity and data.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif data.attidentity and data.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %}
+{% endif %}{% endif %}{% if data.colconstype == 'g' and data.genexpr and data.genexpr != '' %} GENERATED ALWAYS AS ({{data.genexpr}}) STORED{% endif %};
+
+{### Add comments ###}
+{% if data and data.description and data.description != None %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Add variables to column ###}
+{% if data.attoptions %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, data.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != data.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% elif data.attstorage == 'd' %}
+DEFAULT{% endif %};
+
+{% endif %}
+{### Alter column compression value ###}
+{% if data.attcompression is defined and data.attcompression is not none and data.attcompression != '' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET COMPRESSION {{data.attcompression}};
+
+{% endif %}
+{### ACL ###}
+{% if data.attacl %}
+{% for priv in data.attacl %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3d00b9062d7e96acc863315430e37e3df43d2a4b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/16_plus/update.sql
@@ -0,0 +1,216 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Rename column name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ RENAME {{conn|qtIdent(o_data.name)}} TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{### Alter column type and collation ###}
+{% if (data.cltype and data.cltype != o_data.cltype) or (data.attlen is defined and data.attlen != o_data.attlen) or (data.attprecision is defined and data.attprecision != o_data.attprecision) or (data.collspcname and data.collspcname != o_data.collspcname) or data.col_type_conversion is defined %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %}
+-- WARNING:
+-- The SQL statement below would normally be used to alter the datatype for the {{o_data.name}} column, however,
+-- the current datatype cannot be cast to the target datatype so this conversion cannot be made automatically.
+
+{% endif %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %}ALTER TABLE {{conn|qtIdent(data.schema, data.table)}}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %} ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} TYPE {{ GET_TYPE.UPDATE_TYPE_SQL(conn, data, o_data) }}{% if data.collspcname and data.collspcname != o_data.collspcname and data.cltype != '"char"' %}
+ COLLATE {{data.collspcname}}{% elif o_data.collspcname and data.cltype != '"char"' %} COLLATE {{o_data.collspcname}}{% endif %};
+{% endif %}
+{### Alter column default value ###}
+{% if is_view_only and data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER VIEW {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% elif data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% endif %}
+{### Drop column default value ###}
+{% if data.defval is defined and (data.defval == '' or data.defval is none) and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP DEFAULT;
+
+{% endif %}
+{### Alter column not null value ###}
+{% if 'attnotnull' in data and data.attnotnull != o_data.attnotnull %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attnotnull %}SET{% else %}DROP{% endif %} NOT NULL;
+
+{% endif %}
+{% if data.seqincrement or (data.seqcycle or (data.seqcycle == False and data.seqcycle != o_data.seqcycle)) or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}
+{% set attidentity_params = true %}{% else %}
+{% set attidentity_params = false %}{% endif %}
+{### Alter column - add identity ###}
+{% if data.colconstype == 'i' and 'attidentity' in data and o_data.attidentity == '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attidentity == 'a' %}ADD GENERATED ALWAYS AS IDENTITY{% else%}ADD GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %};
+
+{### Alter column - change identity - sequence options ###}
+{% elif 'attidentity' in data or attidentity_params %}
+{% if 'attidentity' in data and data.attidentity != '' and o_data.attidentity != '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET GENERATED {% if data.attidentity == 'a' %}ALWAYS{% else%}BY DEFAULT{% endif %}{% if attidentity_params == false %};{% endif %}
+{% elif attidentity_params %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %}{% endif %}
+{% if data.seqcycle %} SET CYCLE{% elif (data.seqcycle == False and o_data.seqcycle and data.seqcycle != o_data.seqcycle) %} SET NO CYCLE{% endif %}
+{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %} SET INCREMENT {{data.seqincrement|int}}{% endif %}
+{% if data.seqstart is defined and data.seqstart|int(-1) > -1%} RESTART SET START {{data.seqstart|int}}{% endif %}
+{% if data.seqmin is defined and data.seqmin|int(-1) > -1%} SET MINVALUE {{data.seqmin|int}}{% endif %}
+{% if data.seqmax is defined and data.seqmax|int(-1) > -1%} SET MAXVALUE {{data.seqmax|int}}{% endif %}
+{% if data.seqcache is defined and data.seqcache|int(-1) > -1%} SET CACHE {{data.seqcache|int}}{% endif %}{% if attidentity_params == true %};{% endif %}
+
+
+{% endif %}
+{### Alter column - drop identity when column constraint is changed###}
+{% if 'colconstype' in data and data.colconstype == 'n' and 'colconstype' in o_data and o_data.colconstype == 'i' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP IDENTITY;
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget != o_data.attstattarget %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != o_data.attstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% elif data.attstorage == 'd'%}
+DEFAULT{% endif %};
+
+{% endif %}
+{### Alter column compression value ###}
+{% if data.attcompression is defined and data.attcompression is not none and data.attcompression != '' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET COMPRESSION {{data.attcompression}};
+
+{% endif %}
+{% if data.description is defined and data.description != None %}
+{% if data.name %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+{% else %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, o_data.name)}}
+{% endif %}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Update column variables ###}
+{% if 'attoptions' in data and data.attoptions != None and data.attoptions|length > 0 %}
+{% set variables = data.attoptions %}
+{% if 'deleted' in variables and variables.deleted|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', data.name, variables.deleted) }}
+{% else %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', o_data.name, variables.deleted) }}
+{% endif %}
+{% endif %}
+{% if 'added' in variables and variables.added|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.added) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.added) }}
+{% endif %}
+{% endif %}
+{% if 'changed' in variables and variables.changed|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.changed) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.changed) }}
+{% endif %}
+{% endif %}
+{% endif %}
+{### Update column privileges ###}
+{# Change the privileges #}
+{% if data.attacl %}
+{% if 'deleted' in data.attacl %}
+{% for priv in data.attacl.deleted %}
+{% if data.name %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.attacl %}
+{% for priv in data.attacl.changed %}
+{% set is_grantee_changed = (priv.grantee != priv.old_grantee) %}
+{% if data.name %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.attacl %}
+{% for priv in data.attacl.added %}
+{% if data.name %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{### Uppdate tablespace securitylabel ###}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{% if data.name %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, data.name, r.provider) }}
+{% else %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, o_data.name, r.provider) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fa9c3c5ef3bb3e83291489005fd8eb2f4a6e0961
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/acl.sql
@@ -0,0 +1,39 @@
+SELECT 'attacl' as deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(privilege_type order by privilege_type) as privileges,
+ pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT attacl
+ FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attnum = {{clid}}::int
+ ) acl,
+ (SELECT (d).grantee AS grantee, (d).grantor AS grantor, (d).is_grantable
+ AS is_grantable, (d).privilege_type AS privilege_type FROM (SELECT
+ pg_catalog.aclexplode(attacl) as d FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attnum = {{clid}}::int) a) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3d63214db4f0c8bbb9f12d52f12aa445771b38bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/count.sql
@@ -0,0 +1,9 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_attribute att
+WHERE
+ att.attrelid = {{ tid|qtLiteral(conn) }}::oid
+{### To show system objects ###}
+{% if not showsysobj %}
+ AND att.attnum > 0
+{% endif %}
+ AND att.attisdropped IS FALSE
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7fa814ad125aad670ed599782e69f27a321b109d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/create.sql
@@ -0,0 +1,60 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Add column ###}
+{% if data.name and data.cltype %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ADD COLUMN IF NOT EXISTS {{conn|qtIdent(data.name)}} {% if is_sql %}{{data.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.attlen, data.attprecision, data.hasSqrBracket) }}{% endif %}{% if data.collspcname %}
+ COLLATE {{data.collspcname}}{% endif %}{% if data.attnotnull %}
+ NOT NULL{% endif %}{% if data.defval is defined and data.defval is not none and data.defval != '' %}
+ DEFAULT {{data.defval}}{% endif %}{% if data.colconstype == 'i' %}{% if data.attidentity and data.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif data.attidentity and data.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %}
+{% endif %}{% endif %};
+
+{### Add comments ###}
+{% if data and data.description and data.description != None %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Add variables to column ###}
+{% if data.attoptions %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, data.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != data.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {{conn|qtTypeIdent(data.name)}} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if data.attacl %}
+{% for priv in data.attacl %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6102c6823f32e419aaf78ed58b29bf9b1f008391
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/delete.sql
@@ -0,0 +1 @@
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}} DROP COLUMN IF EXISTS {{conn|qtIdent(data.name)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/depend.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/depend.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0371561fcdb3dfe047a4e4ff014f63a493d43878
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/depend.sql
@@ -0,0 +1,9 @@
+SELECT
+ ref.relname AS refname, d2.refclassid, dep.deptype AS deptype
+FROM pg_catalog.pg_depend dep
+ LEFT JOIN pg_catalog.pg_depend d2 ON dep.objid=d2.objid AND dep.refobjid != d2.refobjid
+ LEFT JOIN pg_catalog.pg_class ref ON ref.oid=d2.refobjid
+ LEFT JOIN pg_catalog.pg_attribute att ON d2.refclassid=att.attrelid AND d2.refobjsubid=att.attnum
+ {{ where }} AND
+ dep.classid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_attrdef') AND
+ dep.refobjid NOT IN (SELECT d3.refobjid FROM pg_catalog.pg_depend d3 WHERE d3.objid=d2.refobjid)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4832ac654ee26cd34c9a8884abae6aee670cf5f8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types.sql
@@ -0,0 +1,9 @@
+SELECT tt.oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+ JOIN pg_catalog.pg_cast pc ON tt.oid=pc.casttarget
+ WHERE pc.castsource= {{type_id}}
+ AND pc.castcontext IN ('i', 'a')
+UNION
+SELECT tt.oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+WHERE tt.typbasetype = {{type_id}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types_multi.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types_multi.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9cbd793f0990884a3078f7be6ddd97a60eaca8e1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/edit_mode_types_multi.sql
@@ -0,0 +1,13 @@
+SELECT t.main_oid, pg_catalog.ARRAY_AGG(t.typname) as edit_types
+FROM
+(SELECT pc.castsource AS main_oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+ JOIN pg_catalog.pg_cast pc ON tt.oid=pc.casttarget
+ WHERE pc.castsource IN ({{type_ids}})
+ AND pc.castcontext IN ('i', 'a')
+UNION
+SELECT tt.typbasetype AS main_oid, pg_catalog.format_type(tt.oid,NULL) AS typname
+FROM pg_catalog.pg_type tt
+WHERE tt.typbasetype IN ({{type_ids}})
+) t
+GROUP BY t.main_oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2a258f8a49b4b09a316f590586753e0e005dd28b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_collations.sql
@@ -0,0 +1,7 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
+ ELSE '' END AS collation
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+ WHERE c.collnamespace=n.oid
+ORDER BY nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_inherited_tables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_inherited_tables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f934b3e6464f6d136676e3cc90a8f5e2da4e56b2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_inherited_tables.sql
@@ -0,0 +1,12 @@
+SELECT pg_catalog.array_to_string(pg_catalog.array_agg(inhrelname), ', ') inhrelname, attrname
+FROM
+ (SELECT
+ inhparent::regclass AS inhrelname,
+ a.attname AS attrname
+ FROM pg_catalog.pg_inherits i
+ LEFT JOIN pg_catalog.pg_attribute a ON
+ (attrelid = inhparent AND attnum > 0)
+ WHERE inhrelid = {{tid}}::oid
+ ORDER BY inhseqno
+ ) a
+GROUP BY attrname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_position.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_position.sql
new file mode 100644
index 0000000000000000000000000000000000000000..367fa4f437a218fcb3bc737f4b4a432bfa4dabe3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_position.sql
@@ -0,0 +1,4 @@
+SELECT att.attnum
+FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attname = {{data.name|qtLiteral(conn)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..87de62356c950a1c24fa6c6dc0515a323a13e662
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/get_types.sql
@@ -0,0 +1,14 @@
+SELECT * FROM
+ (SELECT pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END AS elemoid
+ ,typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup
+FROM pg_catalog.pg_type t
+ JOIN pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+WHERE (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r')
+ AND NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = typname and relkind != 'c')
+ AND (typname not like '_%' OR NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = substring(typname from 2)::name and relkind != 'c'))
+ AND nsp.nspname != 'information_schema'
+ ) AS dummy
+ ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1167f088659ee07d1fc408635202f4505f22c6fb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/nodes.sql
@@ -0,0 +1,35 @@
+SELECT DISTINCT att.attname as name, att.attnum as OID, pg_catalog.format_type(ty.oid,NULL) AS datatype,
+att.attnotnull as not_null, att.atthasdef as has_default_val, des.description, seq.seqtypid
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type ty ON ty.oid=atttypid
+ JOIN pg_catalog.pg_namespace tn ON tn.oid=ty.typnamespace
+ JOIN pg_catalog.pg_class cl ON cl.oid=att.attrelid
+ JOIN pg_catalog.pg_namespace na ON na.oid=cl.relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_type et ON et.oid=ty.typelem
+ LEFT OUTER JOIN pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+ LEFT OUTER JOIN (pg_catalog.pg_depend JOIN pg_catalog.pg_class cs ON classid='pg_class'::regclass AND objid=cs.oid AND cs.relkind='S') ON refobjid=att.attrelid AND refobjsubid=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_namespace ns ON ns.oid=cs.relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_index pi ON pi.indrelid=att.attrelid AND indisprimary
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.objsubid=att.attnum AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_sequence seq ON cs.oid=seq.seqrelid
+WHERE
+
+{% if tid %}
+ att.attrelid = {{ tid|qtLiteral(conn) }}::oid
+{% endif %}
+{% if table_name and table_nspname %}
+ cl.relname= {{table_name |qtLiteral(conn)}} and na.nspname={{table_nspname|qtLiteral(conn)}}
+{% endif %}
+{% if clid %}
+ AND att.attnum = {{ clid|qtLiteral(conn) }}
+{% endif %}
+{### To show system objects ###}
+{% if not show_sys_objects and not has_oids %}
+ AND att.attnum > 0
+{% endif %}
+{### To show oids in view data ###}
+{% if has_oids %}
+ AND (att.attnum > 0 OR (att.attname = 'oid' AND att.attnum < 0))
+{% endif %}
+ AND att.attisdropped IS FALSE
+ORDER BY att.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1d12ef0c4f09985bb84d9111606958656649dcf5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/properties.sql
@@ -0,0 +1,41 @@
+SELECT att.attname as name, att.atttypid, att.attlen, att.attnum, att.attndims,
+ att.atttypmod, att.attacl, att.attnotnull, att.attoptions, att.attfdwoptions, att.attstattarget,
+ att.attstorage, att.attidentity,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval,
+ pg_catalog.format_type(ty.oid,NULL) AS typname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS displaytypname,
+ pg_catalog.format_type(ty.oid,att.atttypmod) AS cltype,
+ CASE WHEN ty.typelem > 0 THEN ty.typelem ELSE ty.oid END as elemoid,
+ (SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = ty.typnamespace) as typnspname,
+ ty.typstorage AS defaultstorage,
+ description, pi.indkey,
+ (SELECT count(1) FROM pg_catalog.pg_type t2 WHERE t2.typname=ty.typname) > 1 AS isdup,
+ CASE WHEN length(coll.collname::text) > 0 AND length(nspc.nspname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspc.nspname),'.',pg_catalog.quote_ident(coll.collname))
+ ELSE '' END AS collspcname,
+ EXISTS(SELECT 1 FROM pg_catalog.pg_constraint WHERE conrelid=att.attrelid AND contype='f' AND att.attnum=ANY(conkey)) As is_fk,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=att.attrelid AND sl1.objsubid=att.attnum) AS seclabels,
+ (CASE WHEN (att.attnum < 1) THEN true ElSE false END) AS is_sys_column,
+ (CASE WHEN (att.attidentity in ('a', 'd')) THEN 'i' ELSE 'n' END) AS colconstype, tab.relname as relname,
+ (CASE WHEN tab.relkind = 'v' THEN true ELSE false END) AS is_view_only,
+ seq.*
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type ty ON ty.oid=atttypid
+ LEFT OUTER JOIN pg_catalog.pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=att.attrelid AND des.objsubid=att.attnum AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN (pg_catalog.pg_depend dep JOIN pg_catalog.pg_class cs ON dep.classid='pg_class'::regclass AND dep.objid=cs.oid AND cs.relkind='S') ON dep.refobjid=att.attrelid AND dep.refobjsubid=att.attnum
+ LEFT OUTER JOIN pg_catalog.pg_index pi ON pi.indrelid=att.attrelid AND indisprimary
+ LEFT OUTER JOIN pg_catalog.pg_collation coll ON att.attcollation=coll.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+ LEFT OUTER JOIN pg_catalog.pg_sequence seq ON cs.oid=seq.seqrelid
+ LEFT OUTER JOIN pg_catalog.pg_class tab on tab.oid = att.attrelid
+WHERE att.attrelid = {{tid}}::oid
+{% if clid %}
+ AND att.attnum = {{clid}}::int
+{% endif %}
+{### To show system objects ###}
+{% if not show_sys_objects %}
+ AND att.attnum > 0
+{% endif %}
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6aa4754e6cda7d711a728fe15f7e3dc75781fb8d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/stats.sql
@@ -0,0 +1,14 @@
+SELECT
+ null_frac AS {{ conn|qtIdent(_('Null fraction')) }},
+ avg_width AS {{ conn|qtIdent(_('Average width')) }},
+ n_distinct AS {{ conn|qtIdent(_('Distinct values')) }},
+ most_common_vals AS {{ conn|qtIdent(_('Most common values')) }},
+ most_common_freqs AS {{ conn|qtIdent(_('Most common frequencies')) }},
+ histogram_bounds AS {{ conn|qtIdent(_('Histogram bounds')) }},
+ correlation AS {{ conn|qtIdent(_('Correlation')) }}
+FROM
+ pg_catalog.pg_stats
+WHERE
+ schemaname = {{schema|qtLiteral(conn)}}
+ AND tablename = {{table|qtLiteral(conn)}}
+ AND attname = {{column|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..34445e3c2acc931cae3c1e5632f2e9398efd523b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/columns/sql/default/update.sql
@@ -0,0 +1,209 @@
+{% import 'columns/macros/security.macros' as SECLABEL %}
+{% import 'columns/macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{### Rename column name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ RENAME {{conn|qtIdent(o_data.name)}} TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{### Alter column type and collation ###}
+{% if (data.cltype and data.cltype != o_data.cltype) or (data.attlen is defined and data.attlen != o_data.attlen) or (data.attprecision is defined and data.attprecision != o_data.attprecision) or (data.collspcname and data.collspcname != o_data.collspcname) or data.col_type_conversion is defined %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %}
+-- WARNING:
+-- The SQL statement below would normally be used to alter the datatype for the {{o_data.name}} column, however,
+-- the current datatype cannot be cast to the target datatype so this conversion cannot be made automatically.
+
+{% endif %}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %}ALTER TABLE {{conn|qtIdent(data.schema, data.table)}}
+{% if data.col_type_conversion is defined and data.col_type_conversion == False %} -- {% endif %} ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} TYPE {{ GET_TYPE.UPDATE_TYPE_SQL(conn, data, o_data) }}{%if data.collspcname and data.collspcname != o_data.collspcname and data.cltype != '"char"' %}
+ COLLATE {{data.collspcname}}{% elif o_data.collspcname and data.cltype != '"char"' %} COLLATE {{o_data.collspcname}}{% endif %};
+{% endif %}
+{### Alter column default value ###}
+{% if is_view_only and data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER VIEW {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% elif data.defval is defined and data.defval is not none and data.defval != '' and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET DEFAULT {{data.defval}};
+
+{% endif %}
+{### Drop column default value ###}
+{% if data.defval is defined and (data.defval == '' or data.defval is none) and data.defval != o_data.defval %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP DEFAULT;
+
+{% endif %}
+{### Alter column not null value ###}
+{% if 'attnotnull' in data and data.attnotnull != o_data.attnotnull %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attnotnull %}SET{% else %}DROP{% endif %} NOT NULL;
+
+{% endif %}
+{% if data.seqincrement or (data.seqcycle or (data.seqcycle == False and data.seqcycle != o_data.seqcycle)) or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}
+{% set attidentity_params = true %}{% else %}
+{% set attidentity_params = false %}{% endif %}
+{### Alter column - add identity ###}
+{% if data.colconstype == 'i' and 'attidentity' in data and o_data.attidentity == '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} {% if data.attidentity == 'a' %}ADD GENERATED ALWAYS AS IDENTITY{% else%}ADD GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %} ( {% endif %}
+{% if data.seqcycle is defined and data.seqcycle %}
+CYCLE {% endif %}{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %}
+INCREMENT {{data.seqincrement|int}} {% endif %}{% if data.seqstart is defined and data.seqstart|int(-1) > -1%}
+START {{data.seqstart|int}} {% endif %}{% if data.seqmin is defined and data.seqmin|int(-1) > -1%}
+MINVALUE {{data.seqmin|int}} {% endif %}{% if data.seqmax is defined and data.seqmax|int(-1) > -1%}
+MAXVALUE {{data.seqmax|int}} {% endif %}{% if data.seqcache is defined and data.seqcache|int(-1) > -1%}
+CACHE {{data.seqcache|int}} {% endif %}
+{% if data.seqincrement or data.seqcycle or data.seqincrement or data.seqstart or data.seqmin or data.seqmax or data.seqcache %}){% endif %};
+
+{### Alter column - change identity - sequence options ###}
+{% elif 'attidentity' in data or attidentity_params %}
+{% if 'attidentity' in data and data.attidentity != '' and o_data.attidentity != '' and data.attidentity != o_data.attidentity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET GENERATED {% if data.attidentity == 'a' %}ALWAYS{% else%}BY DEFAULT{% endif %}{% if attidentity_params == false %};{% endif %}
+{% elif attidentity_params %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %}{% endif %}
+{% if data.seqcycle %} SET CYCLE{% elif (data.seqcycle == False and o_data.seqcycle and data.seqcycle != o_data.seqcycle) %} SET NO CYCLE{% endif %}
+{% if data.seqincrement is defined and data.seqincrement|int(-1) > -1 %} SET INCREMENT {{data.seqincrement|int}}{% endif %}
+{% if data.seqstart is defined and data.seqstart|int(-1) > -1%} RESTART SET START {{data.seqstart|int}}{% endif %}
+{% if data.seqmin is defined and data.seqmin|int(-1) > -1%} SET MINVALUE {{data.seqmin|int}}{% endif %}
+{% if data.seqmax is defined and data.seqmax|int(-1) > -1%} SET MAXVALUE {{data.seqmax|int}}{% endif %}
+{% if data.seqcache is defined and data.seqcache|int(-1) > -1%} SET CACHE {{data.seqcache|int}}{% endif %}{% if attidentity_params == true %};{% endif %}
+
+
+{% endif %}
+{### Alter column - drop identity when column constraint is changed###}
+{% if 'colconstype' in data and data.colconstype == 'n' and 'colconstype' in o_data and o_data.colconstype == 'i' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} DROP IDENTITY;
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if data.attstattarget is defined and data.attstattarget != o_data.attstattarget %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STATISTICS {{data.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if data.attstorage is defined and data.attstorage != o_data.attstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ ALTER COLUMN {% if data.name %}{{conn|qtTypeIdent(data.name)}}{% else %}{{conn|qtTypeIdent(o_data.name)}}{% endif %} SET STORAGE {%if data.attstorage == 'p' %}
+PLAIN{% elif data.attstorage == 'm'%}MAIN{% elif data.attstorage == 'e'%}
+EXTERNAL{% elif data.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{% if data.description is defined and data.description != None %}
+{% if data.name %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, data.name)}}
+{% else %}
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.table, o_data.name)}}
+{% endif %}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{### Update column variables ###}
+{% if 'attoptions' in data and data.attoptions != None and data.attoptions|length > 0 %}
+{% set variables = data.attoptions %}
+{% if 'deleted' in variables and variables.deleted|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', data.name, variables.deleted) }}
+{% else %}
+ {{ VARIABLE.UNSET(conn, 'COLUMN', o_data.name, variables.deleted) }}
+{% endif %}
+{% endif %}
+{% if 'added' in variables and variables.added|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.added) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.added) }}
+{% endif %}
+{% endif %}
+{% if 'changed' in variables and variables.changed|length > 0 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+{% if data.name %}
+ {{ VARIABLE.SET(conn, 'COLUMN', data.name, variables.changed) }}
+{% else %}
+ {{ VARIABLE.SET(conn, 'COLUMN', o_data.name, variables.changed) }}
+{% endif %}
+{% endif %}
+{% endif %}
+{### Update column privileges ###}
+{# Change the privileges #}
+{% if data.attacl %}
+{% if 'deleted' in data.attacl %}
+{% for priv in data.attacl.deleted %}
+{% if data.name %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.attacl %}
+{% for priv in data.attacl.changed %}
+{% set is_grantee_changed = (priv.grantee != priv.old_grantee) %}
+{% if data.name %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{% if is_grantee_changed %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.old_grantee) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, data.schema, data.table, o_data.name, priv.grantee) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.attacl %}
+{% for priv in data.attacl.added %}
+{% if data.name %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% else %}
+{{ PRIVILEGE.APPLY(conn, data.schema, data.table, o_data.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{### Uppdate tablespace securitylabel ###}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{% if data.name %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, data.name, r.provider) }}
+{% else %}
+{{ SECLABEL.DROP(conn, 'COLUMN', data.schema, data.table, o_data.name, r.provider) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{% if data.name %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, data.name, r.provider, r.label) }}
+{% else %}
+{{ SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.table, o_data.name, r.provider, r.label) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b9b6b9af3e27133c51da3b2851eb00c055f2363
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is materialized view========#}
+{% if vid %}
+SELECT
+ CASE WHEN c.relkind = 'm' THEN False ELSE True END As m_view
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ vid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b5fea5662cfb1fd13a3341b2995b35274af06fbf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/count.sql
@@ -0,0 +1,5 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_trigger t
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid != 0
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..82e97c250beb932be7e794f85e17ea776ec903e6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/create.sql
@@ -0,0 +1,26 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+ FOR {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE{% if data.columns|length > 0 %} OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.whenclause %}
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}
+
+{% endif %}
+ COMPOUND TRIGGER
+{% if data.prosrc is defined %}{{ data.prosrc }}{% endif%}
+
+END {{ conn|qtIdent(data.name) }};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0a916a196e9153bbcdbbc3b7e8af03dacf05e072
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/delete.sql
@@ -0,0 +1 @@
+DROP TRIGGER IF EXISTS {{conn|qtIdent(data.name)}} ON {{conn|qtIdent(data.nspname, data.relname )}}{% if cascade %} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/enable_disable_trigger.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/enable_disable_trigger.sql
new file mode 100644
index 0000000000000000000000000000000000000000..174a37be49b20971b01c9fcab14ab8760a1fb918
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/enable_disable_trigger.sql
@@ -0,0 +1,3 @@
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(data.schema, data.table) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d9c7341147dc625a7a6e78e575ffbcc12dea7614
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_columns.sql
@@ -0,0 +1,6 @@
+SELECT att.attname as name
+FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attnum IN ({{ clist }})
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5407b486835a5f334d2fdd6b576e79dfe9f83f2d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_oid.sql
@@ -0,0 +1,4 @@
+SELECT t.oid
+FROM pg_catalog.pg_trigger t
+ WHERE tgrelid = {{tid}}::OID
+ AND tgname = {{data.name|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4e6d29453b156912eb3079e1a5da24440da15523
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/nodes.sql
@@ -0,0 +1,14 @@
+SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger, des.description
+FROM pg_catalog.pg_trigger t
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid != 0
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..694266ea501fcab05d64b706c58b14c2b69be85d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/properties.sql
@@ -0,0 +1,23 @@
+SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.tgtype, t.tgattr, relname,
+ CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
+ nspname, des.description,
+ pg_catalog.regexp_replace(
+ regexp_replace(
+ pg_catalog.pg_get_triggerdef(t.oid),
+ 'CREATE TRIGGER (.*) FOR (.*) ON (.*) \nCOMPOUND TRIGGER (.*)\n', ''), '[\n]?END$', ''
+ ) AS prosrc,
+{% if datlastsysoid %}
+ (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
+{% endif %}
+ COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid), 'WHEN (.*) \nCOMPOUND'), NULL) AS whenclause
+FROM pg_catalog.pg_trigger t
+ JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
+ JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid != 0
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..765592634e58be4f52f4c3f50c9315219dec768d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/compound_triggers/sql/ppas/12_plus/update.sql
@@ -0,0 +1,44 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_truncate is defined or data.evnt_update is defined) and (o_data.prosrc != data.prosrc or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_truncate != o_data.evnt_truncate or data.evnt_update != o_data.evnt_update)) %}
+{% set or_flag = False %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+ FOR {% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE{% if o_data.columns|length > 0 %} OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE{% if o_data.columns|length > 0 %} OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+
+{% endif %}
+ COMPOUND TRIGGER
+{% if (data.prosrc is not defined) %}{{ o_data.prosrc }}{% else %}{{ data.prosrc }}{% endif %}
+
+END {{ conn|qtIdent(data.name) }};
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e9f2ecc22b34ad582aef798fa8f508eea6131e5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/create.sql
@@ -0,0 +1,21 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} EXCLUDE {% if data.amname and data.amname != '' %}USING {{data.amname}}{% endif %} (
+ {% for col in data.columns %}{% if loop.index != 1 %},
+ {% endif %}{% if col.is_exp %}{{col.column}}{% else %}{{ conn|qtIdent(col.column)}}{% endif %}{% if col.oper_class and col.oper_class != '' %} {{col.oper_class}}{% endif%}{% if col.order is defined and col.is_sort_nulls_applicable %}{% if col.order %} ASC{% else %} DESC{% endif %} NULLS{% endif %} {% if col.nulls_order is defined and col.is_sort_nulls_applicable %}{% if col.nulls_order %}FIRST {% else %}LAST {% endif %}{% endif %}WITH {{col.operator}}{% endfor %}){% if data.include|length > 0 %}
+
+ INCLUDE ({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %}){% endif %}{% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% if data.indconstraint %}
+
+ WHERE ({{data.indconstraint}}){% endif%}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}{% endif%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/get_constraint_include.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/get_constraint_include.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8b35db8151b6a30c328eaf259c05173e4e2899e3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/get_constraint_include.sql
@@ -0,0 +1,16 @@
+-- pg_get_indexdef did not support INCLUDE columns
+
+SELECT a.attname as colname
+FROM (
+ SELECT
+ i.indnkeyatts,
+ i.indrelid,
+ pg_catalog.unnest(indkey) AS table_colnum,
+ pg_catalog.unnest(ARRAY(SELECT pg_catalog.generate_series(1, i.indnatts) AS n)) attnum
+ FROM
+ pg_catalog.pg_index i
+ WHERE i.indexrelid = {{cid}}::OID
+) i JOIN pg_catalog.pg_attribute a
+ON (a.attrelid = i.indrelid AND i.table_colnum = a.attnum)
+WHERE i.attnum > i.indnkeyatts
+ORDER BY i.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6d3fd1a20896be3417286e9b9f88efb681e1cb39
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/11_plus/properties.sql
@@ -0,0 +1,33 @@
+SELECT cls.oid,
+ cls.relname as name,
+ indnkeyatts as col_count,
+ amname,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment,
+ condeferrable,
+ condeferred,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
+ pg_catalog.pg_get_expr(idx.indpred, idx.indrelid, true) AS indconstraint
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
+AND contype='x'
+ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/16_plus/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/16_plus/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3d21250a5fa7a03a997162007b449ba4936c41e0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/16_plus/stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_catalog.pg_relation_size({{ exid }}::OID) AS {{ conn|qtIdent(_('Index size')) }},
+ last_idx_scan AS {{ conn|qtIdent(_('Last index scan')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ exid }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/begin.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/begin.sql
new file mode 100644
index 0000000000000000000000000000000000000000..58bfee11802d40d03156bae51ace61f4c1d3b77d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/begin.sql
@@ -0,0 +1 @@
+BEGIN;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8ebe6f9f8a7cc412eaf7cbbc931206f5fc477e5d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/create.sql
@@ -0,0 +1,19 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} EXCLUDE {% if data.amname and data.amname != '' %}USING {{data.amname}}{% endif %} (
+ {% for col in data.columns %}{% if loop.index != 1 %},
+ {% endif %}{% if col.is_exp %}{{col.column}}{% else %}{{ conn|qtIdent(col.column)}}{% endif %}{% if col.oper_class and col.oper_class != '' %} {{col.oper_class}}{% endif%}{% if col.order is defined and col.is_sort_nulls_applicable %}{% if col.order %} ASC{% else %} DESC{% endif %} NULLS{% endif %} {% if col.nulls_order is defined and col.is_sort_nulls_applicable %}{% if col.nulls_order %}FIRST {% else %}LAST {% endif %}{% endif %}WITH {{col.operator}}{% endfor %}){% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% if data.indconstraint %}
+
+ WHERE ({{data.indconstraint}}){% endif%}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}{% endif%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f45675655905a99b737dffb0b1ae6b7a24bd242
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/delete.sql
@@ -0,0 +1,3 @@
+{% if data %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/end.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/end.sql
new file mode 100644
index 0000000000000000000000000000000000000000..92d09d5d0c82128cb7534e0456c1e8a55857d73a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/end.sql
@@ -0,0 +1 @@
+END;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_access_methods.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_access_methods.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e469554334219709ebb92677d741360773a7de8c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_access_methods.sql
@@ -0,0 +1,6 @@
+SELECT amname
+FROM pg_catalog.pg_am
+WHERE EXISTS (SELECT 1
+ FROM pg_catalog.pg_proc
+ WHERE oid=amhandler)
+ORDER BY amname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_constraint_cols.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_constraint_cols.sql
new file mode 100644
index 0000000000000000000000000000000000000000..56f830362df166a47e86428ae1468fab45f8ff9e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_constraint_cols.sql
@@ -0,0 +1,23 @@
+{% for n in range(colcnt|int) %}
+{% if loop.index != 1 %}
+UNION
+{% endif %}
+SELECT
+ i.indoption[{{loop.index -1}}] AS options,
+ pg_catalog.pg_get_indexdef(i.indexrelid, {{loop.index}}, true) AS coldef,
+ op.oprname,
+ CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname
+,
+ coll.collname,
+ nspc.nspname as collnspname,
+ pg_catalog.format_type(ty.oid,NULL) AS datatype,
+ CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, {{loop.index}}, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp
+FROM pg_catalog.pg_index i
+JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = {{loop.index}})
+JOIN pg_catalog.pg_type ty ON ty.oid=a.atttypid
+LEFT OUTER JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[{{loop.index -1}}])
+LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid) LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[{{loop.index}}])
+LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
+LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+WHERE i.indexrelid = {{cid}}::oid
+{% endfor %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..42d8e5b54816bc8ac2f6435c74e0225cfbedd8e3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_name.sql
@@ -0,0 +1,3 @@
+SELECT conname as name
+FROM pg_catalog.pg_constraint ct
+WHERE ct.conindid = {{cid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3eda508ec5385511b67165f2aa5f4c67489f36d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid.sql
@@ -0,0 +1,4 @@
+SELECT ct.conindid AS oid
+FROM pg_catalog.pg_constraint ct
+WHERE contype='x' AND
+ct.conname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid_with_transaction.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid_with_transaction.sql
new file mode 100644
index 0000000000000000000000000000000000000000..abc785c86517797bdc4b684b0373af03dabe3435
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oid_with_transaction.sql
@@ -0,0 +1,7 @@
+SELECT ct.conindid AS oid,
+ ct.conname AS name,
+ NOT convalidated AS convalidated
+FROM pg_catalog.pg_constraint ct
+WHERE contype='x' AND
+ conrelid = {{tid}}::oid
+ORDER BY oid DESC LIMIT 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oper_class.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oper_class.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cdabbb0a293a0f33027babdbb44eb5c1e6654ff6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_oper_class.sql
@@ -0,0 +1,7 @@
+SELECT opcname
+FROM pg_catalog.pg_opclass opc,
+pg_catalog.pg_am am
+WHERE opcmethod=am.oid AND
+ am.amname ={{indextype|qtLiteral(conn)}} AND
+ NOT opcdefault
+ORDER BY 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_operator.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_operator.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ba0c5ebee58008063489f49a9a8a6370c4f6f375
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_operator.sql
@@ -0,0 +1,36 @@
+{% if type is not none %}
+SELECT DISTINCT op.oprname as oprname
+FROM pg_catalog.pg_operator op,
+( SELECT oid
+ FROM (SELECT pg_catalog.format_type(t.oid,NULL) AS typname,
+ t.oid as oid
+ FROM pg_catalog.pg_type t
+ JOIN pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE (NOT (typname = 'unknown' AND nspname = 'pg_catalog')) AND
+ typisdefined AND
+ typtype IN ('b', 'c', 'd', 'e', 'r') AND
+ NOT EXISTS (SELECT 1
+ FROM pg_catalog.pg_class
+ WHERE relnamespace=typnamespace AND
+ relname = typname AND
+ relkind != 'c') AND
+ (typname NOT LIKE '_%' OR
+ NOT EXISTS (SELECT 1
+ FROM pg_catalog.pg_class
+ WHERE relnamespace=typnamespace AND
+ relname = SUBSTRING(typname FROM 2)::name AND
+ relkind != 'c'))
+ {% if not show_sysobj %}
+ AND nsp.nspname != 'information_schema'
+ {% endif %}
+ UNION SELECT 'smallserial', 0
+ UNION SELECT 'bigserial', 0
+ UNION SELECT 'serial', 0) t1
+ WHERE typname = {{type|qtLiteral(conn)}}) AS types
+WHERE oprcom > 0 AND
+ (op.oprleft=types.oid OR op.oprright=types.oid)
+{% else %}
+SELECT DISTINCT op.oprname as oprname
+FROM pg_catalog.pg_operator op
+WHERE oprcom > 0
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e8e5a1eb6c62a19bfb646655c6e0e874c447531
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/get_parent.sql
@@ -0,0 +1,7 @@
+SELECT nsp.nspname AS schema,
+ rel.relname AS table
+FROM
+ pg_catalog.pg_class rel
+JOIN pg_catalog.pg_namespace nsp
+ON rel.relnamespace = nsp.oid::oid
+WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7091f1bb7bd085866c935a82a7d56be8a9c57e0f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/nodes.sql
@@ -0,0 +1,12 @@
+SELECT conindid as oid,
+ conname as name,
+ NOT convalidated as convalidated,
+ desp.description AS comment
+FROM pg_catalog.pg_constraint ct
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=ct.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE contype='x' AND
+ conrelid = {{tid}}::oid
+{% if exid %}
+ AND conindid = {{exid}}::oid
+{% endif %}
+ORDER BY conname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d27fcced430083a43b0ee9de193acfd133fe5952
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/properties.sql
@@ -0,0 +1,33 @@
+SELECT cls.oid,
+ cls.relname as name,
+ indnatts as col_count,
+ amname,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment,
+ condeferrable,
+ condeferred,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
+ pg_catalog.pg_get_expr(idx.indpred, idx.indrelid, true) AS indconstraint
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
+AND contype='x'
+ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e127f1a65ab9273c23ba4fdc68da58728f078e27
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/stats.sql
@@ -0,0 +1,28 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_catalog.pg_relation_size({{ exid }}::OID) AS {{ conn|qtIdent(_('Index size')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ exid }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a79c3d1f86c2d1f36950573f8bcff5be40cc27cd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/exclusion_constraint/sql/default/update.sql
@@ -0,0 +1,26 @@
+{### SQL to update exclusion constraint object ###}
+{% if data %}
+{# ==== To update exclusion constraint name ==== #}
+{% if data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{# ==== To update exclusion constraint tablespace ==== #}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER INDEX IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ SET TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% endif %}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER INDEX IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ SET (FILLFACTOR={{ data.fillfactor }});
+{% endif %}
+{% if data.fillfactor == "" and data.fillfactor != o_data.fillfactor %}
+ALTER INDEX IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ RESET (FILLFACTOR);
+{% endif %}
+{# ==== To update exclusion constraint comments ==== #}
+{% if data.comment is defined and data.comment != o_data.comment %}
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/begin.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/begin.sql
new file mode 100644
index 0000000000000000000000000000000000000000..58bfee11802d40d03156bae51ace61f4c1d3b77d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/begin.sql
@@ -0,0 +1 @@
+BEGIN;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bf53512ee32bb44c071c7a1c2bad78acf5b736f4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create.sql
@@ -0,0 +1,33 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} FOREIGN KEY ({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
+ REFERENCES {{ conn|qtIdent(data.remote_schema, data.remote_table) }} ({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}){% if data.confmatchtype is defined %} {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}{% endif%}{% if data.confupdtype is defined %}
+
+ ON UPDATE{% if data.confupdtype == 'a' %}
+ NO ACTION{% elif data.confupdtype == 'r' %}
+ RESTRICT{% elif data.confupdtype == 'c' %}
+ CASCADE{% elif data.confupdtype == 'n' %}
+ SET NULL{% elif data.confupdtype == 'd' %}
+ SET DEFAULT{% endif %}{% endif %}{% if data.confdeltype is defined %}
+
+ ON DELETE{% if data.confdeltype == 'a' %}
+ NO ACTION{% elif data.confdeltype == 'r' %}
+ RESTRICT{% elif data.confdeltype == 'c' %}
+ CASCADE{% elif data.confdeltype == 'n' %}
+ SET NULL{% elif data.confdeltype == 'd' %}
+ SET DEFAULT{% endif %}{% endif %}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif%}
+{% if not data.convalidated %}
+
+ NOT VALID{% endif%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create_index.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create_index.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec789ee3006f481df4771562f0736d96bf2229be
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/create_index.sql
@@ -0,0 +1,5 @@
+{% if data.autoindex and data.coveringindex%}
+CREATE INDEX IF NOT EXISTS {{ conn|qtIdent(data.coveringindex) }}
+ ON {{ conn|qtIdent(data.schema, data.table) }}({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %});
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f45675655905a99b737dffb0b1ae6b7a24bd242
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/delete.sql
@@ -0,0 +1,3 @@
+{% if data %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/end.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/end.sql
new file mode 100644
index 0000000000000000000000000000000000000000..92d09d5d0c82128cb7534e0456c1e8a55857d73a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/end.sql
@@ -0,0 +1 @@
+END;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_cols.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_cols.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bd3d0697d4d911add281dc162de04a9f51b327e8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_cols.sql
@@ -0,0 +1,7 @@
+{% for n in range(colcnt|int) %}
+{% if loop.index != 1 %}
+UNION SELECT pg_catalog.pg_get_indexdef({{ cid|string }}, {{ loop.index|string }}, true) AS column
+{% else %}
+SELECT pg_catalog.pg_get_indexdef({{ cid|string }} , {{ loop.index|string }} , true) AS column
+{% endif %}
+{% endfor %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraint_cols.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraint_cols.sql
new file mode 100644
index 0000000000000000000000000000000000000000..aa6b63ca367b361bf9d96ec24fd5ad8d7f5fa53b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraint_cols.sql
@@ -0,0 +1,13 @@
+{% for keypair in keys %}
+{% if loop.index != 1 %}
+UNION ALL
+{% endif %}
+SELECT a1.attname as conattname,
+ a2.attname as confattname
+FROM pg_catalog.pg_attribute a1,
+ pg_catalog.pg_attribute a2
+WHERE a1.attrelid={{tid}}::oid
+ AND a1.attnum={{keypair[1]}}
+ AND a2.attrelid={{confrelid}}::oid
+ AND a2.attnum={{keypair[0]}}
+{% endfor %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c89a6f31084e8de8cb76e9a64e8a22cb8ffc2dff
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_constraints.sql
@@ -0,0 +1,37 @@
+SELECT cls.oid, cls.relname as idxname, indnatts as col_count
+ FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE idx.indrelid = {{tid}}::oid
+ AND con.contype='p'
+
+UNION
+
+SELECT cls.oid, cls.relname as idxname, indnatts
+ FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE idx.indrelid = {{tid}}::oid
+ AND con.contype='x'
+
+UNION
+
+SELECT cls.oid, cls.relname as idxname, indnatts
+ FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE idx.indrelid = {{tid}}::oid
+ AND con.contype='u'
+
+UNION
+
+SELECT cls.oid, cls.relname as idxname, indnatts
+ FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE idx.indrelid = {{tid}}::oid
+ AND conname IS NULL
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..39d830edf765388133adf4126212441c8c9b5952
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_name.sql
@@ -0,0 +1,3 @@
+SELECT conname as name
+FROM pg_catalog.pg_constraint ct
+WHERE ct.oid = {{fkid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b0f3455371805360ecc5d16c35a868a6744cbd68
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid.sql
@@ -0,0 +1,5 @@
+SELECT ct.oid,
+ NOT convalidated as convalidated
+FROM pg_catalog.pg_constraint ct
+WHERE contype='f' AND
+ct.conname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid_with_transaction.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid_with_transaction.sql
new file mode 100644
index 0000000000000000000000000000000000000000..15bc7d097aa6a06b2b9c641c1268f4fccd273c80
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_oid_with_transaction.sql
@@ -0,0 +1,7 @@
+SELECT ct.oid,
+ ct.conname as name,
+ NOT convalidated as convalidated
+FROM pg_catalog.pg_constraint ct
+WHERE contype='f' AND
+ conrelid = {{tid}}::oid
+ORDER BY ct.oid DESC LIMIT 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e8e5a1eb6c62a19bfb646655c6e0e874c447531
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/get_parent.sql
@@ -0,0 +1,7 @@
+SELECT nsp.nspname AS schema,
+ rel.relname AS table
+FROM
+ pg_catalog.pg_class rel
+JOIN pg_catalog.pg_namespace nsp
+ON rel.relnamespace = nsp.oid::oid
+WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bd925d8467c5460930f23281d6ac24dd5ab483d0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/nodes.sql
@@ -0,0 +1,9 @@
+SELECT ct.oid,
+ conname as name,
+ NOT convalidated as convalidated,
+ description as comment
+FROM pg_catalog.pg_constraint ct
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
+WHERE contype='f' AND
+ conrelid = {{tid}}::oid
+ORDER BY conname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..06834fe257793d17de7adb2eff825af8c12e6715
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/properties.sql
@@ -0,0 +1,33 @@
+SELECT ct.oid,
+ conname as name,
+ condeferrable,
+ condeferred,
+ confupdtype,
+ confdeltype,
+ CASE confmatchtype
+ WHEN 's' THEN FALSE
+ WHEN 'f' THEN TRUE
+ END AS confmatchtype,
+ conkey,
+ confkey,
+ confrelid,
+ nl.nspname as fknsp,
+ cl.relname as fktab,
+ nr.oid as refnspoid,
+ nr.nspname as refnsp,
+ cr.relname as reftab,
+ description as comment,
+ convalidated,
+ conislocal
+FROM pg_catalog.pg_constraint ct
+JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
+JOIN pg_catalog.pg_namespace nl ON nl.oid=cl.relnamespace
+JOIN pg_catalog.pg_class cr ON cr.oid=confrelid
+JOIN pg_catalog.pg_namespace nr ON nr.oid=cr.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
+WHERE contype='f' AND
+conrelid = {{tid}}::oid
+{% if cid %}
+AND ct.oid = {{cid}}::oid
+{% endif %}
+ORDER BY conname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0938bab18bc8d561fb7f3d7027b140a591ebaf95
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/update.sql
@@ -0,0 +1,20 @@
+{### SQL to update foreign key object ###}
+{% if data %}
+{# ==== To update foreign key name ==== #}
+{% if data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ==== To update foreign key validate ==== #}
+{% if 'convalidated' in data and o_data.convalidated != data.convalidated and data.convalidated %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ==== To update foreign key comments ==== #}
+{% if data.comment is defined and data.comment != o_data.comment %}
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/validate.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/validate.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d447cf9af9a4a4bf63d482e7230e5f5074c79221
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/foreign_key/sql/default/validate.sql
@@ -0,0 +1,2 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ VALIDATE CONSTRAINT {{ conn|qtIdent(data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c5c54a12fe9cb4c86066469ec433f911b2317ecf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/create.sql
@@ -0,0 +1,20 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} {{constraint_name}} {% if data.index %}USING INDEX {{ conn|qtIdent(data.index) }}{% else %}
+({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.column)}}{% endfor %}){% if data.include|length > 0 %}
+
+ INCLUDE ({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %}){% endif %}
+{% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% endif %}{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif -%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/get_constraint_include.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/get_constraint_include.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8b35db8151b6a30c328eaf259c05173e4e2899e3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/get_constraint_include.sql
@@ -0,0 +1,16 @@
+-- pg_get_indexdef did not support INCLUDE columns
+
+SELECT a.attname as colname
+FROM (
+ SELECT
+ i.indnkeyatts,
+ i.indrelid,
+ pg_catalog.unnest(indkey) AS table_colnum,
+ pg_catalog.unnest(ARRAY(SELECT pg_catalog.generate_series(1, i.indnatts) AS n)) attnum
+ FROM
+ pg_catalog.pg_index i
+ WHERE i.indexrelid = {{cid}}::OID
+) i JOIN pg_catalog.pg_attribute a
+ON (a.attrelid = i.indrelid AND i.table_colnum = a.attnum)
+WHERE i.attnum > i.indnkeyatts
+ORDER BY i.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..220a3d84fb7853806f4fa18adb91dd95751e2f11
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/11_plus/properties.sql
@@ -0,0 +1,31 @@
+SELECT cls.oid,
+ cls.relname as name,
+ indnkeyatts as col_count,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment,
+ condeferrable,
+ condeferred,
+ conislocal,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
+AND contype='{{constraint_type}}'
+ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a6cf5a03c3e990507b190bc9a7c9884cd4fa677e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/create.sql
@@ -0,0 +1,20 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} {{constraint_name}}{% if data.indnullsnotdistinct %} NULLS NOT DISTINCT{% endif %} {% if data.index %}USING INDEX {{ conn|qtIdent(data.index) }}{% else %}
+({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.column)}}{% endfor %}){% if data.include|length > 0 %}
+
+ INCLUDE ({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %}){% endif %}
+{% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% endif %}{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif -%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f2556a2d6d8ab1d3b7aff98bf2983c18cdfe7388
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/15_plus/properties.sql
@@ -0,0 +1,32 @@
+SELECT cls.oid,
+ cls.relname as name,
+ indnkeyatts as col_count,
+ indnullsnotdistinct,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment,
+ condeferrable,
+ condeferred,
+ conislocal,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
+AND contype='{{constraint_type}}'
+ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/16_plus/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/16_plus/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2c3438d75c08c4c5f907d6f9538365324f83212c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/16_plus/stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_catalog.pg_relation_size({{ cid }}::OID) AS {{ conn|qtIdent(_('Index size')) }},
+ last_idx_scan AS {{ conn|qtIdent(_('Last index scan')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ cid }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/begin.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/begin.sql
new file mode 100644
index 0000000000000000000000000000000000000000..58bfee11802d40d03156bae51ace61f4c1d3b77d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/begin.sql
@@ -0,0 +1 @@
+BEGIN;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..521dc504150e44fb8b4112f845d5ee2a24e8b4e2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/create.sql
@@ -0,0 +1,17 @@
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
+ ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} {{constraint_name}} {% if data.index %}USING INDEX {{ conn|qtIdent(data.index) }}{% else %}
+({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.column)}}{% endfor %}){% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% endif %}{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif -%};
+{% if data.comment and data.name %}
+
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f45675655905a99b737dffb0b1ae6b7a24bd242
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/delete.sql
@@ -0,0 +1,3 @@
+{% if data %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }} DROP CONSTRAINT IF EXISTS {{ conn|qtIdent(data.name) }}{% if cascade%} CASCADE{% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/end.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/end.sql
new file mode 100644
index 0000000000000000000000000000000000000000..92d09d5d0c82128cb7534e0456c1e8a55857d73a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/end.sql
@@ -0,0 +1 @@
+END;
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_constraint_cols.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_constraint_cols.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b2106137e492a0e2ce77f59e08ed55bd5e69bfff
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_constraint_cols.sql
@@ -0,0 +1,14 @@
+{###
+We need outer SELECT & dummy column to preserve the ordering
+because we lose ordering when we use UNION
+###}
+SELECT * FROM (
+{% for n in range(colcnt|int) %}
+{% if loop.index != 1 %}
+UNION SELECT pg_catalog.pg_get_indexdef({{ cid|string }}, {{ loop.index|string }}, true) AS column, {{ n }} AS dummy
+{% else %}
+SELECT pg_catalog.pg_get_indexdef({{ cid|string }} , {{ loop.index|string }} , true) AS column, {{ n }} AS dummy
+{% endif %}
+{% endfor %}
+) tmp
+ORDER BY dummy
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_indices.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_indices.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3e10bbd87ffcebab5deeec6c2f84c68c7bf380df
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_indices.sql
@@ -0,0 +1,3 @@
+SELECT relname FROM pg_catalog.pg_class, pg_catalog.pg_index
+WHERE pg_catalog.pg_class.oid=indexrelid
+AND indrelid={{ tid }}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a46813521b64f9bdf09ca7d24a24f4f702967515
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_name.sql
@@ -0,0 +1,15 @@
+SELECT cls.relname as name
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
+ dep.objid = cls.oid AND
+ dep.refobjsubid = '0'
+ AND dep.refclassid=(SELECT oid
+ FROM pg_catalog.pg_class
+ WHERE relname='pg_constraint') AND
+ dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
+ con.oid = dep.refobjid)
+WHERE indrelid = {{tid}}::oid
+AND contype='{{constraint_type}}'
+AND cls.oid = {{cid}}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6901effa769a66e9ffc5db2284ae9fc3c55529e9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid.sql
@@ -0,0 +1,4 @@
+SELECT ct.conindid as oid
+FROM pg_catalog.pg_constraint ct
+WHERE contype='{{constraint_type}}' AND
+ct.conname = {{ name|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid_with_transaction.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid_with_transaction.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2c59bc5e56b529a2c35f7be81dc62cc7b70eed65
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_oid_with_transaction.sql
@@ -0,0 +1,6 @@
+SELECT ct.conindid as oid,
+ ct.conname as name
+FROM pg_catalog.pg_constraint ct
+WHERE contype='{{constraint_type}}' AND
+ conrelid = {{tid}}::oid
+ORDER BY oid DESC LIMIT 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0e8e5a1eb6c62a19bfb646655c6e0e874c447531
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/get_parent.sql
@@ -0,0 +1,7 @@
+SELECT nsp.nspname AS schema,
+ rel.relname AS table
+FROM
+ pg_catalog.pg_class rel
+JOIN pg_catalog.pg_namespace nsp
+ON rel.relnamespace = nsp.oid::oid
+WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..53c37f50a7482013894e61124830a7e9747dc6bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/nodes.sql
@@ -0,0 +1,25 @@
+SELECT cls.oid, cls.relname as name,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND
+ dep.objid = cls.oid AND
+ dep.refobjsubid = '0' AND
+ dep.refclassid=(SELECT oid
+ FROM pg_catalog.pg_class
+ WHERE relname='pg_constraint') AND
+ dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND
+ con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+AND contype='{{constraint_type}}'
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..83ade7ff0c108e1c294252acdc58046d1c759c20
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/properties.sql
@@ -0,0 +1,31 @@
+SELECT cls.oid,
+ cls.relname as name,
+ indnatts as col_count,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ CASE contype
+ WHEN 'p' THEN desp.description
+ WHEN 'u' THEN desp.description
+ WHEN 'x' THEN desp.description
+ ELSE des.description
+ END AS comment,
+ condeferrable,
+ condeferred,
+ conislocal,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
+FROM pg_catalog.pg_index idx
+JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::oid
+{% if cid %}
+AND cls.oid = {{cid}}::oid
+{% endif %}
+AND contype='{{constraint_type}}'
+ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8c55db597dd681b2b61439eab56fe749ab7d7d32
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/stats.sql
@@ -0,0 +1,28 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_relation_size({{ cid }}::OID) AS {{ conn|qtIdent(_('Index size')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(name)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ cid }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5b30e993aaa65e34c48e1252344f527ccd75838e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/index_constraint/sql/default/update.sql
@@ -0,0 +1,25 @@
+{### SQL to update constraint object ###}
+{% if data %}
+{# ==== To update constraint name ==== #}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE {{ conn|qtIdent(data.schema, data.table) }}
+ RENAME CONSTRAINT {{ conn|qtIdent(o_data.name) }} TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{# ==== To update constraint tablespace ==== #}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER INDEX {{ conn|qtIdent(data.schema, data.name) }}
+ SET TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% endif %}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER INDEX {{ conn|qtIdent(data.schema, data.name) }}
+ SET (FILLFACTOR={{ data.fillfactor }});
+{% elif data.fillfactor is defined and data.fillfactor == '' %}
+ALTER INDEX {{ conn|qtIdent(data.schema, data.name) }}
+ RESET (FILLFACTOR);
+{% endif %}
+{# ==== To update constraint comments ==== #}
+{% if data.comment is defined and data.comment != o_data.comment %}
+COMMENT ON CONSTRAINT {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/column_details.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/column_details.sql
new file mode 100644
index 0000000000000000000000000000000000000000..05c468df5f26584766da3c4f73912350bf6eb786
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/column_details.sql
@@ -0,0 +1,33 @@
+SELECT
+ i.indexrelid,
+ CASE i.indoption[i.attnum - 1]
+ WHEN 0 THEN ARRAY['ASC', 'NULLS LAST']
+ WHEN 1 THEN ARRAY['DESC', 'NULLS LAST']
+ WHEN 2 THEN ARRAY['ASC', 'NULLS FIRST']
+ WHEN 3 THEN ARRAY['DESC', 'NULLS FIRST']
+ ELSE ARRAY['UNKNOWN OPTION' || i.indoption[i.attnum - 1]::text, '']
+ END::text[] AS options,
+ i.attnum,
+ pg_catalog.pg_get_indexdef(i.indexrelid, i.attnum, true) as attdef,
+ CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, i.attnum, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp,
+ a.attstattarget as statistics,
+ CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname,
+ op.oprname AS oprname,
+ CASE WHEN length(nspc.nspname::text) > 0 AND length(coll.collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspc.nspname), '.', pg_catalog.quote_ident(coll.collname))
+ ELSE '' END AS collnspname
+FROM (
+ SELECT
+ indexrelid, i.indoption, i.indclass,
+ pg_catalog.unnest(ARRAY(SELECT pg_catalog.generate_series(1, i.indnkeyatts) AS n)) AS attnum
+ FROM
+ pg_catalog.pg_index i
+ WHERE i.indexrelid = {{idx}}::OID
+) i
+ LEFT JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[i.attnum - 1])
+ LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid)
+ LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[i.attnum])
+ LEFT JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND a.attnum = i.attnum)
+ LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+ORDER BY i.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2800857d5d59728ed9f575a47665d1fa20a7a54d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/create.sql
@@ -0,0 +1,26 @@
+CREATE{% if data.indisunique %} UNIQUE{% endif %} INDEX{% if add_not_exists_clause %} IF NOT EXISTS{% endif %}{% if data.isconcurrent %} CONCURRENTLY{% endif %}{% if data.name %} {{conn|qtIdent(data.name)}}{% endif %}
+
+ ON {{conn|qtIdent(data.schema, data.table)}} {% if data.amname %}USING {{conn|qtIdent(data.amname)}}{% endif %}
+
+{% if mode == 'create' %}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{% if c.is_exp %}({{c.colname}}){% else %}{{conn|qtIdent(c.colname)}}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if data.amname is defined %}{% if c.sort_order is defined and c.is_sort_nulls_applicable %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined and c.is_sort_nulls_applicable %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endif %}{% endfor %})
+{% if data.include|length > 0 %}
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
+{% endif %}
+{% else %}
+{## We will get indented data from postgres for column ##}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{c.colname}}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if c.sort_order is defined %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endfor %})
+{% if data.include|length > 0 %}
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
+{% endif %}
+{% endif %}
+{% if data.storage_parameters %}
+ WITH ({% for key, value in data.storage_parameters.items() %}{% if loop.index != 1 %}, {% endif %}{{key}}={{value}}{% endfor %})
+{% endif %}{% if data.spcname %}
+ TABLESPACE {{conn|qtIdent(data.spcname)}}{% endif %}{% if data.indconstraint %}
+
+ WHERE {{data.indconstraint}}{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/include_details.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/include_details.sql
new file mode 100644
index 0000000000000000000000000000000000000000..38daa85c4c332fab1ea71b3f2a36cf3e96f20817
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/include_details.sql
@@ -0,0 +1,16 @@
+-- pg_get_indexdef did not support INCLUDE columns
+
+SELECT a.attname as colname
+FROM (
+ SELECT
+ i.indnkeyatts,
+ i.indrelid,
+ pg_catalog.unnest(indkey) AS table_colnum,
+ pg_catalog.unnest(ARRAY(SELECT pg_catalog.generate_series(1, i.indnatts) AS n)) attnum
+ FROM
+ pg_catalog.pg_index i
+ WHERE i.indexrelid = {{idx}}::OID
+) i JOIN pg_catalog.pg_attribute a
+ON (a.attrelid = i.indrelid AND i.table_colnum = a.attnum)
+WHERE i.attnum > i.indnkeyatts
+ORDER BY i.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2a67c61ac63556b0e85811284084f29036c7d04b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/11_plus/properties.sql
@@ -0,0 +1,36 @@
+SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
+ indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
+ CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname, conname,
+ tab.relname as tabname, indclass, con.oid AS conoid,
+ CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
+ ELSE des.description END AS description,
+ pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
+ (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'gin_pending_list_limit=([0-9]*)') AS gin_pending_list_limit,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'pages_per_range=([0-9]*)') AS pages_per_range,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'buffering=([a-z]*)') AS buffering,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fastupdate=([a-z]*)')::boolean AS fastupdate,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'autosummarize=([a-z]*)')::boolean AS autosummarize,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'lists=([0-9]*)') AS lists
+ {% if datlastsysoid %}, (CASE WHEN cls.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_idx {% endif %}
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+ JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::OID
+{% if not show_sys_objects %}
+ AND conname is NULL
+{% endif %}
+ {% if idx %}AND cls.oid = {{idx}}::OID {% endif %}
+ ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/13_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/13_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6cafb23571810b0e3d8728d2cdb39624dedadc4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/13_plus/properties.sql
@@ -0,0 +1,37 @@
+SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
+ indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
+ CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname, conname,
+ tab.relname as tabname, indclass, con.oid AS conoid,
+ CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
+ ELSE des.description END AS description,
+ pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
+ (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'deduplicate_items=([a-z]*)')::boolean AS deduplicate_items,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'gin_pending_list_limit=([0-9]*)') AS gin_pending_list_limit,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'pages_per_range=([0-9]*)') AS pages_per_range,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'buffering=([a-z]*)') AS buffering,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fastupdate=([a-z]*)')::boolean AS fastupdate,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'autosummarize=([a-z]*)')::boolean AS autosummarize,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'lists=([0-9]*)') AS lists
+ {% if datlastsysoid %}, (CASE WHEN cls.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_idx {% endif %}
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+ JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::OID
+{% if not show_sys_objects %}
+ AND conname is NULL
+{% endif %}
+ {% if idx %}AND cls.oid = {{idx}}::OID {% endif %}
+ ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f1994631c7072d34992a46f664c0227e29c13e00
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/create.sql
@@ -0,0 +1,32 @@
+CREATE{% if data.indisunique %} UNIQUE{% endif %} INDEX{% if add_not_exists_clause %} IF NOT EXISTS{% endif %}{% if data.isconcurrent %} CONCURRENTLY{% endif %}{% if data.name %} {{conn|qtIdent(data.name)}}{% endif %}
+
+ ON {{conn|qtIdent(data.schema, data.table)}} {% if data.amname %}USING {{conn|qtIdent(data.amname)}}{% endif %}
+
+{% if mode == 'create' %}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{% if c.is_exp %}({{c.colname}}){% else %}{{conn|qtIdent(c.colname)}}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if data.amname is defined %}{% if c.sort_order is defined and c.is_sort_nulls_applicable %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined and c.is_sort_nulls_applicable %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endif %}{% endfor %})
+{% if data.include|length > 0 %}
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
+{% endif %}
+{% if data.indnullsnotdistinct %}
+ NULLS NOT DISTINCT
+{% endif %}
+{% else %}
+{## We will get indented data from postgres for column ##}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{c.colname}}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if c.sort_order is defined %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endfor %})
+{% if data.include|length > 0 %}
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
+{% endif %}
+{% if data.indnullsnotdistinct %}
+ NULLS NOT DISTINCT
+{% endif %}
+{% endif %}
+{% if data.storage_parameters %}
+ WITH ({% for key, value in data.storage_parameters.items() %}{% if loop.index != 1 %}, {% endif %}{{key}}={{value}}{% endfor %})
+{% endif %}{% if data.spcname %}
+ TABLESPACE {{conn|qtIdent(data.spcname)}}{% endif %}{% if data.indconstraint %}
+
+ WHERE {{data.indconstraint}}{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..71613bea095e00351f43c1eb72ff353cf1f35253
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/15_plus/properties.sql
@@ -0,0 +1,37 @@
+SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
+ indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid, indnullsnotdistinct,
+ CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname, conname,
+ tab.relname as tabname, indclass, con.oid AS conoid,
+ CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
+ ELSE des.description END AS description,
+ pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
+ (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'deduplicate_items=([a-z]*)')::boolean AS deduplicate_items,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'gin_pending_list_limit=([0-9]*)') AS gin_pending_list_limit,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'pages_per_range=([0-9]*)') AS pages_per_range,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'buffering=([a-z]*)') AS buffering,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fastupdate=([a-z]*)')::boolean AS fastupdate,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'autosummarize=([a-z]*)')::boolean AS autosummarize,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'lists=([0-9]*)') AS lists
+ {% if datlastsysoid %}, (CASE WHEN cls.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_idx {% endif %}
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+ JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::OID
+{% if not show_sys_objects %}
+ AND conname is NULL
+{% endif %}
+ {% if idx %}AND cls.oid = {{idx}}::OID {% endif %}
+ ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c5482bb21403a4bd70c7299acbec28a90d114dbd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/coll_stats.sql
@@ -0,0 +1,18 @@
+SELECT
+ indexrelname AS {{ conn|qtIdent(_('Index name')) }},
+ pg_catalog.pg_relation_size(indexrelid) AS {{ conn|qtIdent(_('Size')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ last_idx_scan AS {{ conn|qtIdent(_('Last index scan')) }}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0'
+ AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint'))
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE
+ schemaname = '{{schema}}'
+ AND stat.relname = '{{table}}'
+ AND con.contype IS NULL
+ORDER BY indexrelname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0a127ac60b5dec174b197a2546cc16a38be7c3b3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/16_plus/stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_catalog.pg_relation_size({{ idx }}::OID) AS {{ conn|qtIdent(_('Index size')) }},
+ last_idx_scan AS {{ conn|qtIdent(_('Last index scan')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(index)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ idx }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/alter.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/alter.sql
new file mode 100644
index 0000000000000000000000000000000000000000..837789ef260b9847b6df94fc3dd97d6edb111940
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/alter.sql
@@ -0,0 +1,11 @@
+{## Alter index to use cluster type ##}
+{% if data.indisclustered %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ CLUSTER ON {{conn|qtIdent(data.name)}};
+{% endif %}
+{## Changes description ##}
+{% if data.description is defined and data.description %}
+
+COMMENT ON INDEX {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb6264517fd6b7110c823d7d76a133500fb19e92
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is materialized view========#}
+{% if vid %}
+SELECT
+ CASE WHEN c.relkind = 'm' THEN True ELSE False END As m_view
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ vid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/coll_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/coll_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..35e55ccd095522a10f01d2ff55e6e5ae1454ca3e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/coll_stats.sql
@@ -0,0 +1,17 @@
+SELECT
+ indexrelname AS {{ conn|qtIdent(_('Index name')) }},
+ pg_catalog.pg_relation_size(indexrelid) AS {{ conn|qtIdent(_('Size')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0'
+ AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint'))
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE
+ schemaname = '{{schema}}'
+ AND stat.relname = '{{table}}'
+ AND con.contype IS NULL
+ORDER BY indexrelname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/column_details.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/column_details.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9e79b0cff67f7ea8b7e6248a8c811cda1cb6645e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/column_details.sql
@@ -0,0 +1,33 @@
+SELECT
+ i.indexrelid,
+ CASE i.indoption[i.attnum - 1]
+ WHEN 0 THEN ARRAY['ASC', 'NULLS LAST']
+ WHEN 1 THEN ARRAY['DESC', 'NULLS LAST']
+ WHEN 2 THEN ARRAY['ASC', 'NULLS FIRST']
+ WHEN 3 THEN ARRAY['DESC', 'NULLS FIRST']
+ ELSE ARRAY['UNKNOWN OPTION' || i.indoption[i.attnum - 1]::text, '']
+ END::text[] AS options,
+ i.attnum,
+ pg_catalog.pg_get_indexdef(i.indexrelid, i.attnum, true) as attdef,
+ CASE WHEN pg_catalog.pg_get_indexdef(i.indexrelid, i.attnum, true) = a.attname THEN FALSE ELSE TRUE END AS is_exp,
+ a.attstattarget as statistics,
+ CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname,
+ op.oprname AS oprname,
+ CASE WHEN length(nspc.nspname::text) > 0 AND length(coll.collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspc.nspname), '.', pg_catalog.quote_ident(coll.collname))
+ ELSE '' END AS collnspname
+FROM (
+ SELECT
+ indexrelid, i.indoption, i.indclass,
+ pg_catalog.unnest(ARRAY(SELECT pg_catalog.generate_series(1, i.indnatts) AS n)) AS attnum
+ FROM
+ pg_catalog.pg_index i
+ WHERE i.indexrelid = {{idx}}::OID
+) i
+ LEFT JOIN pg_catalog.pg_opclass o ON (o.oid = i.indclass[i.attnum - 1])
+ LEFT OUTER JOIN pg_catalog.pg_constraint c ON (c.conindid = i.indexrelid)
+ LEFT OUTER JOIN pg_catalog.pg_operator op ON (op.oid = c.conexclop[i.attnum])
+ LEFT JOIN pg_catalog.pg_attribute a ON (a.attrelid = i.indexrelid AND a.attnum = i.attnum)
+ LEFT OUTER JOIN pg_catalog.pg_collation coll ON a.attcollation=coll.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON coll.collnamespace=nspc.oid
+ORDER BY i.attnum;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ba340c8cd3c1ab62c733f4b25a80848c93130262
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/count.sql
@@ -0,0 +1,10 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+WHERE indrelid = {{tid}}::OID
+{### To show system objects ###}
+{% if not showsysobj %}
+ AND conname is NULL
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..38f5b9d2865bbb07613f0a8e940be956afcf61d1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/create.sql
@@ -0,0 +1,20 @@
+CREATE{% if data.indisunique %} UNIQUE{% endif %} INDEX{% if add_not_exists_clause %} IF NOT EXISTS{% endif %}{% if data.isconcurrent %} CONCURRENTLY{% endif %}{% if data.name %} {{conn|qtIdent(data.name)}}{% endif %}
+
+ ON {{conn|qtIdent(data.schema, data.table)}} {% if data.amname %}USING {{conn|qtIdent(data.amname)}}{% endif %}
+
+{% if mode == 'create' %}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{% if c.is_exp %}({{c.colname}}){% else %}{{conn|qtIdent(c.colname)}}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if data.amname is defined %}{% if c.sort_order is defined and c.is_sort_nulls_applicable %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined and c.is_sort_nulls_applicable %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endif %}{% endfor %})
+{% else %}
+{## We will get indented data from postgres for column ##}
+ ({% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{c.colname}}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.op_class %}
+ {{c.op_class}}{% endif %}{% if c.sort_order is defined %}{% if c.sort_order %} DESC{% else %} ASC{% endif %}{% endif %}{% if c.nulls is defined %} NULLS {% if c.nulls %}
+FIRST{% else %}LAST{% endif %}{% endif %}{% endfor %})
+{% endif %}
+{% if data.fillfactor %}
+ WITH (fillfactor={{data.fillfactor}})
+{% endif %}{% if data.spcname %}
+ TABLESPACE {{conn|qtIdent(data.spcname)}}{% endif %}{% if data.indconstraint %}
+
+ WHERE {{data.indconstraint}}{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb059c78509866030d1e1a51d6dd0402bb9b47b1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP INDEX IF EXISTS {{conn|qtIdent(data.nspname, data.name)}}{% if cascade %} cascade{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_am.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_am.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b268eaef3c35ba3a40dce3c5f9372164b1cc0af
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_am.sql
@@ -0,0 +1,3 @@
+-- Fetches access methods
+SELECT oid, amname
+FROM pg_catalog.pg_am
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..06c40a81abcb88240c9ed97d82b9ba28d390bbdc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_collations.sql
@@ -0,0 +1,7 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
+ ELSE '' END AS collation
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+ WHERE c.collnamespace=n.oid
+ ORDER BY nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..94c99ddda047342a2e8ba59d234427b3eaa48b55
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid.sql
@@ -0,0 +1,7 @@
+SELECT DISTINCT ON(cls.relname) cls.oid
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+WHERE indrelid = {{tid}}::OID
+ AND cls.relname = {{data.name|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8d3a603ca79e6824e21529e43c08b4a2aba30fce
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_oid_name.sql
@@ -0,0 +1,5 @@
+SELECT cls.relname, cls.oid
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+WHERE indrelid = {{tid}}::OID
+ORDER BY cls.oid DESC LIMIT 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_op_class.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_op_class.sql
new file mode 100644
index 0000000000000000000000000000000000000000..79f8c6ff3c5895ed5862796bfc9903ec9461cb59
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_op_class.sql
@@ -0,0 +1,5 @@
+SELECT opcname, opcmethod
+FROM pg_catalog.pg_opclass
+ WHERE opcmethod = {{oid}}::OID
+ AND NOT opcdefault
+ ORDER BY 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0af0576800bb1f5e0486612b3be0298082f17fed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/nodes.sql
@@ -0,0 +1,25 @@
+SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name,
+(SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
+CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description ELSE des.description END AS description
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+ JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::OID
+{% if not show_sys_objects %}
+ AND conname is NULL
+{% endif %}
+{% if idx %}
+ AND cls.oid = {{ idx }}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = cls.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..23214d8bd3f7f2e33393b01b4d38fc23ad6d10be
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/properties.sql
@@ -0,0 +1,30 @@
+SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as name, indrelid, indkey, indisclustered,
+ indisvalid, indisunique, indisprimary, n.nspname,indnatts,cls.reltablespace AS spcoid,
+ CASE WHEN (length(spcname::text) > 0 OR cls.relkind = 'I') THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname, conname,
+ tab.relname as tabname, indclass, con.oid AS conoid,
+ CASE WHEN contype IN ('p', 'u', 'x') THEN desp.description
+ ELSE des.description END AS description,
+ pg_catalog.pg_get_expr(indpred, indrelid, true) as indconstraint, contype, condeferrable, condeferred, amname,
+ (SELECT (CASE WHEN count(i.inhrelid) > 0 THEN true ELSE false END) FROM pg_inherits i WHERE i.inhrelid = cls.oid) as is_inherited,
+ substring(pg_catalog.array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor
+ {% if datlastsysoid %}, (CASE WHEN cls.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_idx {% endif %}
+FROM pg_catalog.pg_index idx
+ JOIN pg_catalog.pg_class cls ON cls.oid=indexrelid
+ JOIN pg_catalog.pg_class tab ON tab.oid=indrelid
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta on ta.oid=cls.reltablespace
+ JOIN pg_catalog.pg_namespace n ON n.oid=tab.relnamespace
+ JOIN pg_catalog.pg_am am ON am.oid=cls.relam
+ LEFT JOIN pg_catalog.pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_constraint') AND dep.deptype='i')
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)
+WHERE indrelid = {{tid}}::OID
+{% if not show_sys_objects %}
+ AND conname is NULL
+{% endif %}
+ {% if idx %}AND cls.oid = {{idx}}::OID {% endif %}
+ ORDER BY cls.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..73bbed979e1a6b3606e7fa974725c84a650d03a0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/stats.sql
@@ -0,0 +1,28 @@
+SELECT
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_read AS {{ conn|qtIdent(_('Index tuples read')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ pg_catalog.pg_relation_size({{ idx }}::OID) AS {{ conn|qtIdent(_('Index size')) }}
+{#=== Extended stats ===#}
+{% if is_pgstattuple %}
+ ,version AS {{ conn|qtIdent(_('Version')) }},
+ tree_level AS {{ conn|qtIdent(_('Tree level')) }},
+ index_size AS {{ conn|qtIdent(_('Index size')) }},
+ root_block_no AS {{ conn|qtIdent(_('Root block no')) }},
+ internal_pages AS {{ conn|qtIdent(_('Internal pages')) }},
+ leaf_pages AS {{ conn|qtIdent(_('Leaf pages')) }},
+ empty_pages AS {{ conn|qtIdent(_('Empty pages')) }},
+ deleted_pages AS {{ conn|qtIdent(_('Deleted pages')) }},
+ avg_leaf_density AS {{ conn|qtIdent(_('Average leaf density')) }},
+ leaf_fragmentation AS {{ conn|qtIdent(_('Leaf fragmentation')) }}
+FROM
+ pgstatindex('{{conn|qtIdent(schema)}}.{{conn|qtIdent(index)}}'), pg_catalog.pg_stat_all_indexes stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_indexes stat
+{% endif %}
+ JOIN pg_catalog.pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid
+ JOIN pg_catalog.pg_class cl ON cl.oid=stat.indexrelid
+ WHERE stat.indexrelid = {{ idx }}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bef61d07f1db91dc6d490efa77413b91a20b362e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/indexes/sql/default/update.sql
@@ -0,0 +1,96 @@
+{## Changes name ##}
+{% if data.name and o_data.name != data.name %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{## Changes fillfactor ##}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (fillfactor={{data.fillfactor}});
+
+{% elif (data.fillfactor == '' or data.fillfactor == None) and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (fillfactor);
+
+{% endif %}
+{## Changes gin_pending_list_limit ##}
+{% if data.gin_pending_list_limit and o_data.gin_pending_list_limit != data.gin_pending_list_limit %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (gin_pending_list_limit={{data.gin_pending_list_limit}});
+
+{% elif (data.gin_pending_list_limit == '' or data.gin_pending_list_limit == None) and o_data.gin_pending_list_limit|default('', 'true') != data.gin_pending_list_limit %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (gin_pending_list_limit);
+
+{% endif %}
+{## Changes deduplicate_items ##}
+{% if data.deduplicate_items in [True, False] and o_data.deduplicate_items != data.deduplicate_items %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (deduplicate_items={{data.deduplicate_items}});
+
+{% endif %}
+
+{## Changes pages_per_range ##}
+{% if data.pages_per_range and o_data.pages_per_range != data.pages_per_range %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (pages_per_range={{data.pages_per_range}});
+
+{% elif (data.pages_per_range == '' or data.pages_per_range == None) and o_data.pages_per_range|default('', 'true') != data.pages_per_range %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (pages_per_range);
+
+{% endif %}
+{## Changes buffering ##}
+{% if data.buffering and o_data.buffering != data.buffering %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (buffering={{data.buffering}});
+
+{% elif (data.buffering == '' or data.buffering == None) and o_data.buffering|default('', 'true') != data.buffering %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (buffering);
+
+{% endif %}
+{## Changes fastupdate ##}
+{% if data.fastupdate in [True, False] and o_data.fastupdate != data.fastupdate %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (fastupdate={{data.fastupdate}});
+
+{% endif %}
+{## Changes autosummarize ##}
+{% if data.autosummarize in [True, False] and o_data.autosummarize != data.autosummarize %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (autosummarize={{data.autosummarize}});
+
+{% endif %}
+{## Changes tablespace ##}
+{% if data.spcname and o_data.spcname != data.spcname %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET TABLESPACE {{conn|qtIdent(data.spcname)}};
+
+{% endif %}
+{## Alter index to use cluster type ##}
+{% if data.indisclustered is defined and o_data.indisclustered != data.indisclustered %}
+{% if data.indisclustered %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ CLUSTER ON {{conn|qtIdent(data.name)}};
+
+{% else %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.table)}}
+ SET WITHOUT CLUSTER;
+
+{% endif %}
+{% endif %}
+{## Changes description ##}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON INDEX {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};{% endif %}
+
+{## Alter column statistics##}
+{% if update_column %}
+{% for col in update_column_data %}
+ALTER INDEX IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{col.col_num}} SET STATISTICS {{col.statistics}};
+
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/11_plus/partition_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/11_plus/partition_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ab65e87fb33bb9b47460a5342b4b49f6673ed060
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/11_plus/partition_diff.sql
@@ -0,0 +1,24 @@
+CREATE TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.name)}} (
+ LIKE {{conn|qtIdent(data.schema, data.orig_name)}} INCLUDING ALL
+) PARTITION BY {{ data.partition_scheme }};
+{{partition_sql}}{{partition_data.default_partition_header}}
+CREATE TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.default_partition_name)}} PARTITION OF {{conn|qtIdent(data.schema, data.name)}} DEFAULT;
+
+INSERT INTO {{conn|qtIdent(data.schema, data.name)}}(
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %} {{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %})
+SELECT {% if data.columns and data.columns|length > 0 %}{% for c in data.columns %}{{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %}
+ FROM {{conn|qtIdent(data.schema, data.orig_name)}};
+
+{% if partition_data.partitions and partition_data.partitions|length > 0 %}
+{% for part in partition_data.partitions %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, part.partition_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, part.temp_partition_name)}}
+ RENAME TO {{conn|qtIdent(part.partition_name)}};
+
+{% endfor %}{% endif %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, data.orig_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RENAME TO {{data.orig_name}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..77f5064c44357f22917d64f75fb37f7eb0c5c732
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/create.sql
@@ -0,0 +1,74 @@
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{### CREATE TABLE STATEMENT FOR partitions ###}
+
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{% if data.relispartition is defined and data.relispartition %} PARTITION OF {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}}{% endif %}
+
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+( {% endif %}
+{% if data.primary_key|length > 0 %}{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+)
+{% endif %}
+ {{ data.partition_value }}{% if data.is_partitioned is defined and data.is_partitioned %}
+
+ PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if data.default_amname and data.default_amname != data.amname and data.amname is not none %}
+
+USING {{data.amname}}
+{% elif not data.default_amname and data.amname %}
+
+USING {{data.amname}}
+{% endif %}
+{% if data.fillfactor or data.autovacuum_custom or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum or data.toast_autovacuum_enabled in ('t', 'f') or (data.autovacuum_enabled in ('t', 'f') and data.vacuum_table|length > 0) or (data.toast_autovacuum_enabled in ('t', 'f') and data.vacuum_toast|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+
+){% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+;
+
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec1d4ff021247ee1e8104c1c9f4fa2c0453a47ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/nodes.sql
@@ -0,0 +1,55 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, am.amname
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b4c1b907d7f9ab6aa2c768115012586163f7d723
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/12_plus/properties.sql
@@ -0,0 +1,77 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 OR rel.relkind = 'p' THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as parent_schema,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, rel.relispartition,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, am.amname,
+ (SELECT st.setting from pg_catalog.pg_settings st WHERE st.name = 'default_table_access_method') as default_amname,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table,
+ -- Added for partition table
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ {% if ptid %}
+ (CASE WHEN rel.relispartition THEN pg_catalog.pg_get_expr(rel.relpartbound, {{ ptid }}::oid) ELSE '' END) AS partition_value,
+ (SELECT relname FROM pg_catalog.pg_class WHERE oid = {{ tid }}::oid) AS partitioned_table_name
+ {% else %}
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value
+ {% endif %}
+
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ LEFT JOIN pg_catalog.pg_inherits inh ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+WHERE rel.relispartition AND inh.inhparent = {{ tid }}::oid
+{% if ptid %} AND rel.oid = {{ ptid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/14_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/14_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..01f90b66a3bf074b5d7bbfe0f81608fbe9d81a82
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/14_plus/nodes.sql
@@ -0,0 +1,55 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, inh.inhdetachpending, am.amname
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/attach.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/attach.sql
new file mode 100644
index 0000000000000000000000000000000000000000..710eb05614cfea2c29c3de922cd06d724e437211
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/attach.sql
@@ -0,0 +1,2 @@
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} ATTACH PARTITION {{conn|qtIdent(data.schema, data.name)}}
+ {{ data.partition_value }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..aa0326f5d341477cf264425e441f4f0bc8a43404
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is partitioned table========#}
+{% if tid %}
+SELECT
+ CASE WHEN c.relkind = 'p' THEN True ELSE False END As ptable
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ tid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f39edda7202c664b2e46c6ff9c2ecfb6747e453b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/create.sql
@@ -0,0 +1,67 @@
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{### CREATE TABLE STATEMENT FOR partitions ###}
+
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{% if data.relispartition is defined and data.relispartition %} PARTITION OF {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}}{% endif %}
+
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+( {% endif %}
+{% if data.primary_key|length > 0 %}{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+)
+{% endif %}
+ {{ data.partition_value }}{% if data.is_partitioned is defined and data.is_partitioned %}
+
+ PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if data.fillfactor or data.autovacuum_custom or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum or data.toast_autovacuum_enabled in ('t', 'f') or (data.autovacuum_enabled in ('t', 'f') and data.vacuum_table|length > 0) or (data.toast_autovacuum_enabled in ('t', 'f') and data.vacuum_toast|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+
+){% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+;
+
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/detach.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/detach.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6ba3bd91f524085d5f3721072ac6889e88837184
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/detach.sql
@@ -0,0 +1,7 @@
+{% if data.mode is defined and data.mode == 'concurrently' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}} CONCURRENTLY;
+{% elif data.mode is defined and data.mode == 'finalize' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}} FINALIZE;
+{% else %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/get_attach_tables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/get_attach_tables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..db22e4a8f39b504d741f27b2b541dd9828fc585d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/get_attach_tables.sql
@@ -0,0 +1,23 @@
+SELECT oid, pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(relname) AS table_name FROM
+(SELECT
+ r.oid, r.relname, n.nspname, pg_catalog.array_agg(a.attname) attnames, pg_catalog.array_agg(a.atttypid) atttypes
+FROM
+ (SELECT oid, relname, relnamespace FROM pg_catalog.pg_class
+ WHERE relkind in ('r', 'p') AND NOT relispartition) r
+ JOIN (SELECT oid AS nspoid, nspname FROM
+ pg_catalog.pg_namespace WHERE nspname NOT LIKE 'pg\_%') n
+ ON (r.relnamespace = n.nspoid)
+ JOIN (SELECT attrelid, attname, atttypid FROM
+ pg_catalog.pg_attribute WHERE attnum > 0 ORDER BY attrelid, attnum) a
+ ON (r.oid = a.attrelid)
+GROUP BY r.oid, r.relname, r.relnamespace, n.nspname) all_tables
+JOIN
+(SELECT
+ attrelid, pg_catalog.array_agg(attname) attnames, pg_catalog.array_agg(atttypid) atttypes
+FROM
+ (SELECT * FROM pg_catalog.pg_attribute
+ WHERE attrelid = {{ tid }} AND attnum > 0
+ ORDER BY attrelid, attnum) attributes
+GROUP BY attrelid) current_table ON current_table.attrelid != all_tables.oid
+ AND current_table.attnames = all_tables.attnames
+ AND current_table.atttypes = all_tables.atttypes
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9e60f9f8605e6e591ca483e04d3fdab2cdde085c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/nodes.sql
@@ -0,0 +1,54 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/partition_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/partition_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7cbf95733c870f83787e93a415069e4db38ff4c6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/partition_diff.sql
@@ -0,0 +1,22 @@
+CREATE TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.name)}} (
+ LIKE {{conn|qtIdent(data.schema, data.orig_name)}} INCLUDING ALL
+) PARTITION BY {{ data.partition_scheme }};
+{{partition_sql}}
+INSERT INTO {{conn|qtIdent(data.schema, data.name)}}(
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %} {{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %})
+SELECT {% if data.columns and data.columns|length > 0 %}{% for c in data.columns %}{{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %}
+ FROM {{conn|qtIdent(data.schema, data.orig_name)}};
+
+{% if partition_data.partitions and partition_data.partitions|length > 0 %}
+{% for part in partition_data.partitions %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, part.partition_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, part.temp_partition_name)}}
+ RENAME TO {{conn|qtIdent(part.partition_name)}};
+
+{% endfor %}{% endif %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, data.orig_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RENAME TO {{data.orig_name}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c1365a2ae7195258db81458e7cb80d7065de41d9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/pg/default/properties.sql
@@ -0,0 +1,75 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as parent_schema,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, rel.relhasoids, rel.relispartition,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table,
+ -- Added for partition table
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ {% if ptid %}
+ (CASE WHEN rel.relispartition THEN pg_catalog.pg_get_expr(rel.relpartbound, {{ ptid }}::oid) ELSE '' END) AS partition_value,
+ (SELECT relname FROM pg_catalog.pg_class WHERE oid = {{ tid }}::oid) AS partitioned_table_name
+ {% else %}
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value
+ {% endif %}
+
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ LEFT JOIN pg_catalog.pg_inherits inh ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+WHERE rel.relispartition AND inh.inhparent = {{ tid }}::oid
+{% if ptid %} AND rel.oid = {{ ptid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/11_plus/partition_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/11_plus/partition_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bfc063c0f799e32385b1fe9d7fe056d36440fb3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/11_plus/partition_diff.sql
@@ -0,0 +1,24 @@
+CREATE TABLE {{conn|qtIdent(data.schema, data.name)}} (
+ LIKE {{conn|qtIdent(data.schema, data.orig_name)}} INCLUDING ALL
+) PARTITION BY {{ data.partition_scheme }};
+{{partition_sql}}{{partition_data.default_partition_header}}
+CREATE TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.default_partition_name)}} PARTITION OF {{conn|qtIdent(data.schema, data.name)}} DEFAULT;
+
+INSERT INTO {{conn|qtIdent(data.schema, data.name)}}(
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %} {{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %})
+SELECT {% if data.columns and data.columns|length > 0 %}{% for c in data.columns %}{{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %}
+ FROM {{conn|qtIdent(data.schema, data.orig_name)}};
+
+{% if partition_data.partitions and partition_data.partitions|length > 0 %}
+{% for part in partition_data.partitions %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, part.partition_name)}};
+
+ALTER TABLE {{conn|qtIdent(data.schema, part.temp_partition_name)}}
+ RENAME TO {{conn|qtIdent(part.partition_name)}};
+
+{% endfor %}{% endif %}
+DROP TABLE {{conn|qtIdent(data.schema, data.orig_name)}};
+
+ALTER TABLE {{conn|qtIdent(data.schema, data.name)}}
+ RENAME TO {{data.orig_name}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d837366f0ff88d1abe77c41c75c9a7db6e4e217f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/create.sql
@@ -0,0 +1,72 @@
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{### CREATE TABLE STATEMENT FOR partitions ###}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.name)}}{% if data.relispartition is defined and data.relispartition %} PARTITION OF {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}}{% endif %}
+
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+( {% endif %}
+{% if data.primary_key|length > 0 %}{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+)
+{% endif %}
+ {{ data.partition_value }}{% if data.is_partitioned is defined and data.is_partitioned %}
+
+ PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if data.default_amname and data.default_amname != data.amname and data.amname is not none %}
+
+USING {{data.amname}}
+{% elif not data.default_amname and data.amname %}
+
+USING {{data.amname}}
+{% endif %}
+{% if data.fillfactor or data.autovacuum_custom or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum or data.toast_autovacuum_enabled in ('t', 'f') or (data.autovacuum_enabled in ('t', 'f') and data.vacuum_table|length > 0) or (data.toast_autovacuum_enabled in ('t', 'f') and data.vacuum_toast|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}
+
+){% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+;
+
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ec1d4ff021247ee1e8104c1c9f4fa2c0453a47ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/nodes.sql
@@ -0,0 +1,55 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, am.amname
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..db03b0310a86bbbd27b1047b1accbee6d3021b65
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/12_plus/properties.sql
@@ -0,0 +1,77 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 OR rel.relkind = 'p' THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as parent_schema,
+ nsp.nspname as schema,
+ pg_get_userbyid(rel.relowner) AS relowner, rel.relispartition,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, am.amname,
+ (SELECT st.setting from pg_catalog.pg_settings st WHERE st.name = 'default_table_access_method') as default_amname,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table,
+ -- Added for partition table
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ {% if ptid %}
+ (CASE WHEN rel.relispartition THEN pg_catalog.pg_get_expr(rel.relpartbound, {{ ptid }}::oid) ELSE '' END) AS partition_value,
+ (SELECT relname FROM pg_catalog.pg_class WHERE oid = {{ tid }}::oid) AS partitioned_table_name
+ {% else %}
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value
+ {% endif %}
+
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ LEFT JOIN pg_catalog.pg_inherits inh ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+WHERE rel.relispartition AND inh.inhparent = {{ tid }}::oid
+{% if ptid %} AND rel.oid = {{ ptid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/14_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/14_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..01f90b66a3bf074b5d7bbfe0f81608fbe9d81a82
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/14_plus/nodes.sql
@@ -0,0 +1,55 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, inh.inhdetachpending, am.amname
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/attach.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/attach.sql
new file mode 100644
index 0000000000000000000000000000000000000000..710eb05614cfea2c29c3de922cd06d724e437211
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/attach.sql
@@ -0,0 +1,2 @@
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} ATTACH PARTITION {{conn|qtIdent(data.schema, data.name)}}
+ {{ data.partition_value }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..aa0326f5d341477cf264425e441f4f0bc8a43404
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is partitioned table========#}
+{% if tid %}
+SELECT
+ CASE WHEN c.relkind = 'p' THEN True ELSE False END As ptable
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ tid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d54e98d2ec4e626f21a68764ba45378791e21180
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/create.sql
@@ -0,0 +1,65 @@
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{### CREATE TABLE STATEMENT FOR partitions ###}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.name)}}{% if data.relispartition is defined and data.relispartition %} PARTITION OF {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}}{% endif %}
+
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+( {% endif %}
+{% if data.primary_key|length > 0 %}{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+)
+{% endif %}
+ {{ data.partition_value }}{% if data.is_partitioned is defined and data.is_partitioned %}
+
+ PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if data.fillfactor or data.autovacuum_custom or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum or data.toast_autovacuum_enabled in ('t', 'f') or (data.autovacuum_enabled in ('t', 'f') and data.vacuum_table|length > 0) or (data.toast_autovacuum_enabled in ('t', 'f') and data.vacuum_toast|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% endif %}{% if opt.name and opt.value is defined %}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}
+
+){% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+;
+
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/detach.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/detach.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6ba3bd91f524085d5f3721072ac6889e88837184
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/detach.sql
@@ -0,0 +1,7 @@
+{% if data.mode is defined and data.mode == 'concurrently' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}} CONCURRENTLY;
+{% elif data.mode is defined and data.mode == 'finalize' %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}} FINALIZE;
+{% else %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.parent_schema, data.partitioned_table_name)}} DETACH PARTITION {{conn|qtIdent(data.schema, data.name)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/get_attach_tables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/get_attach_tables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..db22e4a8f39b504d741f27b2b541dd9828fc585d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/get_attach_tables.sql
@@ -0,0 +1,23 @@
+SELECT oid, pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(relname) AS table_name FROM
+(SELECT
+ r.oid, r.relname, n.nspname, pg_catalog.array_agg(a.attname) attnames, pg_catalog.array_agg(a.atttypid) atttypes
+FROM
+ (SELECT oid, relname, relnamespace FROM pg_catalog.pg_class
+ WHERE relkind in ('r', 'p') AND NOT relispartition) r
+ JOIN (SELECT oid AS nspoid, nspname FROM
+ pg_catalog.pg_namespace WHERE nspname NOT LIKE 'pg\_%') n
+ ON (r.relnamespace = n.nspoid)
+ JOIN (SELECT attrelid, attname, atttypid FROM
+ pg_catalog.pg_attribute WHERE attnum > 0 ORDER BY attrelid, attnum) a
+ ON (r.oid = a.attrelid)
+GROUP BY r.oid, r.relname, r.relnamespace, n.nspname) all_tables
+JOIN
+(SELECT
+ attrelid, pg_catalog.array_agg(attname) attnames, pg_catalog.array_agg(atttypid) atttypes
+FROM
+ (SELECT * FROM pg_catalog.pg_attribute
+ WHERE attrelid = {{ tid }} AND attnum > 0
+ ORDER BY attrelid, attnum) attributes
+GROUP BY attrelid) current_table ON current_table.attrelid != all_tables.oid
+ AND current_table.attnames = all_tables.attnames
+ AND current_table.atttypes = all_tables.atttypes
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9e60f9f8605e6e591ca483e04d3fdab2cdde085c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/nodes.sql
@@ -0,0 +1,54 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ pg_catalog.pg_get_expr(rel.relpartbound, rel.oid) AS partition_value,
+ rel.relnamespace AS schema_id,
+ nsp.nspname AS schema_name,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_sub_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS sub_partition_scheme,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid, des.description, pg_catalog.pg_get_userbyid(rel.relowner) AS relowner
+FROM
+ (SELECT * FROM pg_catalog.pg_inherits WHERE inhparent = {{ tid }}::oid) inh
+ LEFT JOIN pg_catalog.pg_class rel ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relispartition
+ {% if ptid %} AND rel.oid = {{ ptid }}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/partition_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/partition_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7cbf95733c870f83787e93a415069e4db38ff4c6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/partition_diff.sql
@@ -0,0 +1,22 @@
+CREATE TABLE IF NOT EXISTS {{conn|qtIdent(data.schema, data.name)}} (
+ LIKE {{conn|qtIdent(data.schema, data.orig_name)}} INCLUDING ALL
+) PARTITION BY {{ data.partition_scheme }};
+{{partition_sql}}
+INSERT INTO {{conn|qtIdent(data.schema, data.name)}}(
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %} {{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %})
+SELECT {% if data.columns and data.columns|length > 0 %}{% for c in data.columns %}{{c.name}}{% if not loop.last %},{% endif %}{% endfor %}{% endif %}
+ FROM {{conn|qtIdent(data.schema, data.orig_name)}};
+
+{% if partition_data.partitions and partition_data.partitions|length > 0 %}
+{% for part in partition_data.partitions %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, part.partition_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, part.temp_partition_name)}}
+ RENAME TO {{conn|qtIdent(part.partition_name)}};
+
+{% endfor %}{% endif %}
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, data.orig_name)}};
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RENAME TO {{data.orig_name}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1799b6b92fce2fd0d7aedb7aac1c8116c6f38a72
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/partitions/sql/ppas/default/properties.sql
@@ -0,0 +1,75 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as parent_schema,
+ nsp.nspname as schema,
+ pg_get_userbyid(rel.relowner) AS relowner, rel.relhasoids, rel.relispartition,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, typ.typname,
+ typ.typrelid AS typoid,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table,
+ -- Added for partition table
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (CASE WHEN rel.relkind = 'p' THEN pg_get_partkeydef(rel.oid::oid) ELSE '' END) AS partition_scheme,
+ {% if ptid %}
+ (CASE WHEN rel.relispartition THEN pg_get_expr(rel.relpartbound, {{ ptid }}::oid) ELSE '' END) AS partition_value,
+ (SELECT relname FROM pg_catalog.pg_class WHERE oid = {{ tid }}::oid) AS partitioned_table_name
+ {% else %}
+ pg_get_expr(rel.relpartbound, rel.oid) AS partition_value
+ {% endif %}
+
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ LEFT JOIN pg_catalog.pg_inherits inh ON inh.inhrelid = rel.oid
+ LEFT JOIN pg_catalog.pg_namespace nsp ON rel.relnamespace = nsp.oid
+WHERE rel.relispartition AND inh.inhparent = {{ tid }}::oid
+{% if ptid %} AND rel.oid = {{ ptid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..31e455a6acba4343c713f0f1ef8267765ee12016
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_policy pl
+WHERE
+{% if tid %}
+ pl.polrelid = {{ tid }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..27c7c374128b99334bf5a3c76071348a2546c1ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/create.sql
@@ -0,0 +1,27 @@
+{% set add_semicolon_after = 'to' %}
+{% if data.withcheck is defined and data.withcheck != None and data.withcheck != '' %}
+{% set add_semicolon_after = 'with_check' %}
+{% elif data.using is defined and data.using != None and data.using != '' %}
+{% set add_semicolon_after = 'using' %}
+{% endif %}
+CREATE POLICY {{ conn|qtIdent(data.name) }}
+ ON {{conn|qtIdent(data.schema, data.table)}}
+{%if data.type %}
+ AS {{ data.type|upper }}
+{% endif %}
+{% if data.event %}
+ FOR {{ data.event|upper }}
+{% endif %}
+{% if data.policyowner %}
+ TO {{ conn|qtTypeIdent(data.policyowner) }}{% if add_semicolon_after == 'to' %};{% endif %}
+{% else %}
+ TO public{% if add_semicolon_after == 'to' %};{% endif %}
+{% endif %}
+{% if data.using %}
+
+ USING ({{ data.using }}){% if add_semicolon_after == 'using' %};{% endif %}
+{% endif %}
+{% if data.withcheck %}
+
+ WITH CHECK ({{ data.withcheck }});
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ffe32a05fcb3c4b96d3439529602648b5fc1c499
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP POLICY IF EXISTS {{ conn|qtIdent(policy_name) }} ON {{conn|qtIdent(result.schema, result.table)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_policy_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_policy_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..90fe16bd28feb6da0dc6b89967abbe7d061f842b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_policy_name.sql
@@ -0,0 +1,9 @@
+{% if plid %}
+SELECT
+ pl.oid AS oid,
+ pl.polname AS name
+FROM
+ pg_catalog.pg_policy pl
+WHERE
+ pl.oid = {{ plid }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_position.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_position.sql
new file mode 100644
index 0000000000000000000000000000000000000000..9dbf8df84e778b3dd053646bdf4ec77be44f31f9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/get_position.sql
@@ -0,0 +1,2 @@
+SELECT pl.oid FROM pg_catalog.pg_policy pl
+WHERE pl.polrelid = {{tid}}::oid AND pl.polname = {{data.name|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8aeba94ae8125eb5e95d7970984fcb2105078e58
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/nodes.sql
@@ -0,0 +1,17 @@
+SELECT
+ pl.oid AS oid,
+ pl.polname AS name
+FROM
+ pg_catalog.pg_policy pl
+WHERE
+{% if tid %}
+ pl.polrelid = {{ tid }}
+{% elif plid %}
+ pl.oid = {{ plid }}
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = pl.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ pl.polname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8a672967c9981213bde52acdfdd6f97bfed1bf92
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/properties.sql
@@ -0,0 +1,23 @@
+SELECT
+ pl.oid AS oid,
+ pl.polname AS name,
+ rw.permissive as type,
+ rw.cmd AS event,
+ rw.qual AS using,
+ rw.qual AS using_orig,
+ rw.with_check AS withcheck,
+ rw.with_check AS withcheck_orig,
+
+ pg_catalog.array_to_string(rw.roles::name[], ', ') AS policyowner
+FROM
+ pg_catalog.pg_policy pl
+JOIN pg_catalog.pg_policies rw ON pl.polname=rw.policyname
+JOIN pg_catalog.pg_namespace n ON n.nspname=rw.schemaname
+JOIN pg_catalog.pg_class rel on rel.relname=rw.tablename
+WHERE
+{% if plid %}
+ pl.oid = {{ plid }} and n.oid = {{ scid }} and rel.oid = {{ policy_table_id }};
+{% endif %}
+{% if tid %}
+ pl.polrelid = {{ tid }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7fa1e3f40091f307f359c5283450c69ef1ede0be
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/row_security_policies/sql/default/update.sql
@@ -0,0 +1,33 @@
+{#####################################################}
+{## Change policy owner ##}
+{#####################################################}
+{% if data.policyowner and o_data.policyowner != data.policyowner %}
+ALTER POLICY {{ conn|qtIdent(o_data.name) }} ON {{conn|qtIdent(o_data.schema, o_data.table)}}
+ TO {{ conn|qtTypeIdent(data.policyowner) }};
+{% endif %}
+
+{#####################################################}
+{## Change policy using condition ##}
+{#####################################################}
+{% if data.using and o_data.using != data.using %}
+ALTER POLICY {{ conn|qtIdent(o_data.name) }} ON {{conn|qtIdent(o_data.schema, o_data.table)}}
+ USING ({{ data.using }});
+{% endif %}
+
+{#####################################################}
+{## Change policy with check condition ##}
+{#####################################################}
+{% if data.withcheck and o_data.withcheck != data.withcheck %}
+ALTER POLICY {{ conn|qtIdent(o_data.name) }} ON {{conn|qtIdent(o_data.schema, o_data.table)}}
+ WITH CHECK ({{ data.withcheck }});
+{% endif %}
+
+{#####################################################}
+{## Change policy name ##}
+{#####################################################}
+{% if data.name and o_data.name != data.name %}
+ALTER POLICY {{ conn|qtIdent(o_data.name) }} ON {{conn|qtIdent(o_data.schema, o_data.table)}}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b9b6b9af3e27133c51da3b2851eb00c055f2363
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is materialized view========#}
+{% if vid %}
+SELECT
+ CASE WHEN c.relkind = 'm' THEN False ELSE True END As m_view
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ vid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e9cd0b40b901fe8b0ba161321a781ca4c36d56d1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_rewrite rw
+WHERE
+{% if tid %}
+ rw.ev_class = {{ tid }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..394afb45aaebbacc338833bc45eeccc6dbf2a001
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/create.sql
@@ -0,0 +1,27 @@
+{# ============Create Rule============= #}
+{% if display_comments %}
+-- Rule: {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.view) }}
+
+-- DROP Rule IF EXISTS {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.view) }};
+
+{% endif %}
+{% if data.name and data.schema and data.view %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} RULE {{ conn|qtIdent(data.name) }} AS
+ ON {{ data.event|upper if data.event else 'SELECT' }} TO {{ conn|qtIdent(data.schema, data.view) }}
+{% if data.condition %}
+ WHERE ({{ data.condition }})
+{% endif %}
+ DO{% if data.do_instead in ['true', True] %}
+{{ ' INSTEAD' }}{% else %}{{ '' }}{% endif %}
+{% if data.statements is defined and data.statements.strip() in ['', 'NOTHING'] %}
+ NOTHING;
+{% elif data.statements is defined %}
+
+({{ data.statements.rstrip(';') }});
+{% else %}
+ NOTHING;
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON RULE {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.view) }} IS {{ data.comment|qtLiteral(conn) }};{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6d92d9b645675a21e55ac5a7ea048b7ed5d7ae63
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/delete.sql
@@ -0,0 +1,16 @@
+{# ======== Drop/Cascade Rule ========= #}
+{% if rid %}
+SELECT
+ rw.rulename,
+ cl.relname,
+ nsp.nspname
+FROM
+ pg_catalog.pg_rewrite rw
+JOIN pg_catalog.pg_class cl ON cl.oid=rw.ev_class
+JOIN pg_catalog.pg_namespace nsp ON nsp.oid=cl.relnamespace
+WHERE
+ rw.oid={{ rid }};
+{% endif %}
+{% if rulename and relname and nspname %}
+DROP RULE IF EXISTS {{ conn|qtIdent(rulename) }} ON {{ conn|qtIdent(nspname, relname) }} {% if cascade %} CASCADE {% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7e8e47e14a0bd86f1ed5678cb7099ffd9d63ac45
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/nodes.sql
@@ -0,0 +1,22 @@
+SELECT
+ rw.oid AS oid,
+ rw.rulename AS name,
+ CASE WHEN rw.ev_enabled != 'D' THEN True ELSE False END AS enabled,
+ rw.ev_enabled AS is_enable_rule,
+ description AS comment
+FROM
+ pg_catalog.pg_rewrite rw
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rw.oid AND des.classoid='pg_rewrite'::regclass)
+WHERE
+{% if tid %}
+ rw.ev_class = {{ tid }}
+{% elif rid %}
+ rw.oid = {{ rid }}
+{% endif %}
+{% if schema_diff %}
+ AND rw.rulename != '_RETURN'
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rw.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ rw.rulename
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8f238bb8e5fad228f1e624dda427384b273c6075
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/properties.sql
@@ -0,0 +1,30 @@
+{# =================== Fetch Rules ==================== #}
+{% if tid or rid %}
+SELECT
+ rw.oid AS oid,
+ rw.rulename AS name,
+ rw.ev_type,
+ rw.is_instead,
+ relname AS view,
+ CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
+ nspname AS schema,
+ description AS comment,
+ {# ===== Check whether it is system rule or not ===== #}
+ CASE WHEN rw.rulename = '_RETURN' THEN True ELSE False END AS system_rule,
+ CASE WHEN rw.ev_enabled != 'D' THEN True ELSE False END AS enabled,
+ rw.ev_enabled AS is_enable_rule,
+ pg_catalog.pg_get_ruledef(rw.oid) AS definition
+FROM
+ pg_catalog.pg_rewrite rw
+JOIN pg_catalog.pg_class cl ON cl.oid=rw.ev_class
+JOIN pg_catalog.pg_namespace nsp ON nsp.oid=cl.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rw.oid AND des.classoid='pg_rewrite'::regclass)
+WHERE
+ {% if tid %}
+ ev_class = {{ tid }}
+ {% elif rid %}
+ rw.oid = {{ rid }}
+ {% endif %}
+ORDER BY
+ rw.rulename
+ {% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/rule_id.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/rule_id.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6bc9c832171e320bdd9add9ed4e51c3c29e6b4cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/rule_id.sql
@@ -0,0 +1,9 @@
+{#========Below will provide rule id for last created rule========#}
+{% if rule_name %}
+SELECT
+ rw.oid
+FROM
+ pg_catalog.pg_rewrite rw
+WHERE
+ rw.rulename={{ rule_name|qtLiteral(conn) }}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..567aae00cd75e92286b8c31a92e0ace678f59046
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/rules/sql/update.sql
@@ -0,0 +1,47 @@
+{# ===== Update Rule ===== #}
+{% if data.name is defined %}
+{% set rule_name = data.name %}
+{% else %}
+{% set rule_name = o_data.name %}
+{% endif %}
+{% if data.name and data.name != o_data.name %}
+ALTER RULE {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.schema, o_data.view) }} RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if data.event is defined or data.do_instead is defined or data.condition is defined or data.statements is defined %}
+CREATE OR REPLACE RULE {{ conn|qtIdent(rule_name) }} AS
+ ON {% if data.event and data.event != o_data.event %}{{ data.event|upper }}{% else %}{{ o_data.event|upper }}{% endif %}
+ TO {{ conn|qtIdent(o_data.schema, o_data.view) }}
+{% if data.condition and o_data.condition != data.condition %}
+ WHERE ({{ data.condition }})
+{% elif data.condition is not defined and o_data.condition %}
+ WHERE ({{ o_data.condition }})
+{% endif %}
+ DO{% if (('do_instead' not in data and o_data.do_instead in ['true', True]) or (data.do_instead in ['true', True])) %}{{ ' INSTEAD' }}{% endif %}
+{% if data.statements is defined %}
+{% if data.statements.strip() in ['', 'NOTHING'] %}
+ NOTHING;
+{% else %}
+
+({{ data.statements.rstrip(';') }});
+{% endif %}
+{% elif o_data.statements.strip() in ['', 'NOTHING'] %}
+ NOTHING;
+{% else %}
+({{ o_data.statements.rstrip(';') }});
+{% endif %}
+
+{% endif %}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+COMMENT ON RULE {{ conn|qtIdent(rule_name) }} ON {{ conn|qtIdent(o_data.schema, o_data.view) }} IS {{ data.comment|qtLiteral(conn) }};{% endif %}
+
+{% if data.enabled is defined and o_data.enabled != data.enabled %}
+ALTER TABLE {{ conn|qtIdent(o_data.schema, o_data.view) }} {% if (data.enabled in ['false', False]) %}DISABLE{% endif %}{% if (data.enabled in ['true', True]) %}ENABLE{% endif %} RULE {{ conn|qtIdent(o_data.name) }};
+{% endif %}
+
+{% if data.is_enable_rule is defined and o_data.is_enable_rule != data.is_enable_rule %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.schema, o_data.view) }}
+ {{ enable_map[data.is_enable_rule] }} RULE {{ conn|qtIdent(o_data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ea21997d6f0c21da22df864c336b85e7040eb333
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/create.sql
@@ -0,0 +1,213 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'columns/macros/security.macros' as COLUMN_SECLABEL %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{#
+ If user has not provided any details but only name then
+ add empty bracket with table name
+#}
+{% set empty_bracket = ""%}
+{% if data.coll_inherits|length == 0 and data.columns|length == 0 and not data.typname and not data.like_relation and data.primary_key|length == 0 and data.unique_constraint|length == 0 and data.foreign_key|length == 0 and data.check_constraint|length == 0 and data.exclude_constraint|length == 0 %}
+{% set empty_bracket = "\n(\n)"%}
+{% endif %}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{{empty_bracket}}
+{% if data.typname %}
+ OF {{ data.typname }}
+{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+(
+{% endif %}
+{% if data.like_relation %}
+ LIKE {{ data.like_relation }}{% if data.like_default_value %}
+
+ INCLUDING DEFAULTS{% endif %}{% if data.like_constraints %}
+
+ INCLUDING CONSTRAINTS{% endif %}{% if data.like_indexes %}
+
+ INCLUDING INDEXES{% endif %}{% if data.like_storage %}
+
+ INCLUDING STORAGE{% endif %}{% if data.like_comments %}
+
+ INCLUDING COMMENTS{% endif %}{% if data.like_identity %}
+
+ INCLUDING IDENTITY{% endif %}{% if data.like_statistics %}
+
+ INCLUDING STATISTICS{% endif %}{% if data.columns|length > 0 %},
+{% endif %}
+
+{% endif %}
+{### Add columns ###}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.name and c.cltype %}
+ {% if c.inheritedfromtable %}-- Inherited from table {{c.inheritedfromtable}}: {% elif c.inheritedfromtype %}-- Inherited from type {{c.inheritedfromtype}}: {% endif %}{{conn|qtIdent(c.name)}} {% if is_sql %}{{c.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, c.cltype, c.attlen, c.attprecision, c.hasSqrBracket) }}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.attnotnull %} NOT NULL{% endif %}{% if c.defval is defined and c.defval is not none and c.defval != '' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'i' and c.attidentity and c.attidentity != '' %}
+{% if c.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif c.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %} ( {% endif %}
+{% if c.seqcycle is defined and c.seqcycle %}
+CYCLE {% endif %}{% if c.seqincrement is defined and c.seqincrement|int(-1) > -1 %}
+INCREMENT {{c.seqincrement|int}} {% endif %}{% if c.seqstart is defined and c.seqstart|int(-1) > -1%}
+START {{c.seqstart|int}} {% endif %}{% if c.seqmin is defined and c.seqmin|int(-1) > -1%}
+MINVALUE {{c.seqmin|int}} {% endif %}{% if c.seqmax is defined and c.seqmax|int(-1) > -1%}
+MAXVALUE {{c.seqmax|int}} {% endif %}{% if c.seqcache is defined and c.seqcache|int(-1) > -1%}
+CACHE {{c.seqcache|int}} {% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %}){% endif %}
+{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 %}{% if data.columns|length > 0 %},{% endif %}
+{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+){% endif %}{% if data.relkind is defined and data.relkind == 'p' %} PARTITION BY {{ data.partition_scheme }}{% endif %}
+
+{### If we are inheriting it from another table(s) ###}
+{% if data.coll_inherits %}
+ INHERITS ({% for val in data.coll_inherits %}{% if loop.index != 1 %}, {% endif %}{{val}}{% endfor %})
+{% endif %}
+WITH (
+ OIDS = {% if data.relhasoids %}TRUE{% else %}FALSE{% endif %}{% if data.fillfactor %},
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.parallel_workers is defined and data.parallel_workers != '' and data.parallel_workers != None %},
+ parallel_workers = {{ data.parallel_workers }}{% endif %}{% if data.toast_tuple_target is defined and data.toast_tuple_target != '' and data.toast_tuple_target != None %},
+ toast_tuple_target = {{ data.toast_tuple_target }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %},
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %},
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}
+{% endif %}{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+,
+ {{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}
+
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+)
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+);
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{### Security Labels on Table ###}
+{% if data.seclabels and data.seclabels|length > 0 %}
+
+{% for r in data.seclabels %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{### ACL on Table ###}
+{% if data.revoke_all %}
+{% for priv in data.revoke_all %}
+{{ PRIVILEGE.UNSETALL(conn, "TABLE", priv, data.name, data.schema)}}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE ENDS HERE ======#}
+{#===========================================#}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if c.attstorage is defined and c.attstorage != c.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STORAGE {%if c.attstorage == 'p' %}
+PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}
+EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if c.attacl and c.attacl|length > 0 %}
+
+{% for priv in c.attacl %}
+{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.name, c.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if c.seclabels and c.seclabels|length > 0 %}
+
+{% for r in c.seclabels %}
+{{ COLUMN_SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.name, c.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES ENDS HERE #}
+{#===========================================#}
+{#======================================#}
+{# CONSTRAINTS SPECIFIC TEMPLATES #}
+{#======================================#}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.primary_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.unique_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.foreign_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.check_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.exclude_constraint)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/get_collation.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/get_collation.sql
new file mode 100644
index 0000000000000000000000000000000000000000..af8d33f4b4f375d987ecba66a71112fa020329c0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/get_collation.sql
@@ -0,0 +1,7 @@
+SELECT (PG_CATALOG.CONCAT(PG_CATALOG.QUOTE_IDENT(nspc.nspname),'.',PG_CATALOG.QUOTE_IDENT(PGCOL.COLLNAME))) AS collationame
+ FROM PG_PARTITIONED_TABLE PARTT
+ LEFT OUTER JOIN PG_CATALOG.PG_COLLATION PGCOL
+ ON PGCOL.OID = 950
+ LEFT OUTER JOIN PG_CATALOG.PG_NAMESPACE NSPC
+ ON PGCOL.COLLNAMESPACE = NSPC.OID
+ WHERE PARTRELID = 162140
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..151bd9be6163e62827c5a5b3d392414f4fd0d1a9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/properties.sql
@@ -0,0 +1,75 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (CASE rel.relreplident
+ WHEN 'd' THEN 'default'
+ WHEN 'n' THEN 'nothing'
+ WHEN 'f' THEN 'full'
+ WHEN 'i' THEN 'index'
+ END) as replica_identity,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as schema,
+ pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, rel.relhasoids, rel.relkind,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'parallel_workers=([0-9]*)') AS parallel_workers,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'toast_tuple_target=([0-9]*)') AS toast_tuple_target,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype,
+ CASE WHEN typ.typname IS NOT NULL THEN (select pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid )||'.'||pg_catalog.quote_ident(typ.typname) ELSE typ.typname END AS typname,
+ typ.typrelid AS typoid, rel.relrowsecurity as rlspolicy, rel.relforcerowsecurity as forcerlspolicy,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table
+ -- Added for partition table
+ {% if tid %}, (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef({{ tid }}::oid) ELSE '' END) AS partition_scheme {% endif %}
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+AND NOT rel.relispartition
+{% if tid %} AND rel.oid = {{ tid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..591ed675ee0e5afef23cec631eeaa21baee4a2c4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/11_plus/update.sql
@@ -0,0 +1,291 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{#####################################################}
+{## Rename table ##}
+{#####################################################}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{#####################################################}
+{## Change table schema ##}
+{#####################################################}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, data.name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+
+{% endif %}
+{#####################################################}
+{## Change table owner ##}
+{#####################################################}
+{% if data.relowner and data.relowner != o_data.relowner %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER TO {{conn|qtIdent(data.relowner)}};
+
+{% endif %}
+{#####################################################}
+{## Update Inherits table definition ##}
+{#####################################################}
+{% if data.coll_inherits_added|length > 0 %}
+{% for val in data.coll_inherits_added %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{% if data.coll_inherits_removed|length > 0 %}
+{% for val in data.coll_inherits_removed %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{#####################################################}
+{## Change hasOID attribute of table ##}
+{#####################################################}
+{% if data.relhasoids is defined and data.relhasoids != o_data.relhasoids %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET {% if data.relhasoids %}WITH{% else %}WITHOUT{% endif %} OIDS;
+
+{% endif %}
+{#####################################################}
+{## Change tablespace ##}
+{#####################################################}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET TABLESPACE {{conn|qtIdent(data.spcname)}};
+
+{% endif %}
+{#####################################################}
+{## change fillfactor settings ##}
+{#####################################################}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (FILLFACTOR={{data.fillfactor}});
+{% elif (data.fillfactor == '' or data.fillfactor == None) and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (FILLFACTOR);
+
+{% endif %}
+
+{## change parallel_workers settings ##}
+{#####################################################}
+{% if (data.parallel_workers == '' or data.parallel_workers == None) and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (parallel_workers);
+{% elif data.parallel_workers is defined and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (parallel_workers={{data.parallel_workers}});
+
+{% endif %}
+
+{## change toast_tuple_target settings ##}
+{#####################################################}
+{% if (data.toast_tuple_target == '' or data.toast_tuple_target == None) and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (toast_tuple_target);
+{% elif data.toast_tuple_target is defined and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (toast_tuple_target={{data.toast_tuple_target}});
+
+{% endif %}
+
+{###############################}
+{## Table AutoVacuum settings ##}
+{###############################}
+{% if data.vacuum_table is defined and data.vacuum_table.set_values|length > 0 %}
+{% set has_vacuum_set = true %}
+{% endif %}
+{% if data.vacuum_table is defined and data.vacuum_table.reset_values|length > 0 %}
+{% set has_vacuum_reset = true %}
+{% endif %}
+{% if o_data.autovacuum_custom and data.autovacuum_custom == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ autovacuum_enabled,
+ autovacuum_analyze_scale_factor,
+ autovacuum_analyze_threshold,
+ autovacuum_freeze_max_age,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_vacuum_threshold,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_table_age
+);
+{% else %}
+{% if (data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_set %}
+{% for opt in data.vacuum_table.set_values %}{% if opt.name and opt.value is defined %}
+ {{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.autovacuum_enabled == 'x' and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.autovacuum_enabled =='x' and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled{% if has_vacuum_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_reset %}
+{% for opt in data.vacuum_table.reset_values %}{% if opt.name %}
+ {{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################}
+{## Toast table AutoVacuum settings ##}
+{#####################################}
+{% if data.vacuum_toast is defined and data.vacuum_toast.set_values|length > 0 %}
+{% set has_vacuum_toast_set = true %}
+{% endif %}
+{% if data.vacuum_toast is defined and data.vacuum_toast.reset_values|length > 0 %}
+{% set has_vacuum_toast_reset = true %}
+{% endif %}
+{% if o_data.toast_autovacuum and data.toast_autovacuum == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ toast.autovacuum_enabled,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_table_age,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_analyze_scale_factor
+);
+{% else %}
+{% if (data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_toast_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_set %}
+{% for opt in data.vacuum_toast.set_values %}{% if opt.name and opt.value is defined %}
+ toast.{{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled{% if has_vacuum_toast_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_reset %}
+{% for opt in data.vacuum_toast.reset_values %}{% if opt.name %}
+ toast.{{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Change table comments ##}
+{#####################################################}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% elif data.rlspolicy is defined and data.rlspolicy != o_data.rlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ DISABLE ROW LEVEL SECURITY;
+
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% elif data.forcerlspolicy is defined and data.forcerlspolicy != o_data.forcerlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Update table Privileges ##}
+{#####################################################}
+{% if data.relacl %}
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Update table SecurityLabel ##}
+{#####################################################}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TABLE', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#####################################################}
+{## Change replica identity ##}
+{#####################################################}
+{% if data.replica_identity and data.replica_identity != o_data.replica_identity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} REPLICA IDENTITY {{data.replica_identity }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e3888b550119ec19656e7e644d4e67093d928727
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/create.sql
@@ -0,0 +1,239 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'columns/macros/security.macros' as COLUMN_SECLABEL %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{#
+ If user has not provided any details but only name then
+ add empty bracket with table name
+#}
+{% set empty_bracket = ""%}
+{% if data.coll_inherits|length == 0 and data.columns|length == 0 and not data.typname and not data.like_relation and data.primary_key|length == 0 and data.unique_constraint|length == 0 and data.foreign_key|length == 0 and data.check_constraint|length == 0 and data.exclude_constraint|length == 0 %}
+{% set empty_bracket = "\n(\n)"%}
+{% endif %}
+{% set with_clause = false%}
+{% if data.fillfactor or data.parallel_workers or data.toast_tuple_target or (data.autovacuum_custom and data.add_vacuum_settings_in_sql) or data.autovacuum_enabled in ('t', 'f') or (data.toast_autovacuum and data.add_vacuum_settings_in_sql) or data.toast_autovacuum_enabled in ('t', 'f') %}
+{% set with_clause = true%}
+{% endif %}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{{empty_bracket}}
+{% if data.typname %}
+ OF {{ data.typname }}
+{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+(
+{% endif %}
+{% if data.like_relation %}
+ LIKE {{ data.like_relation }}{% if data.like_default_value %}
+
+ INCLUDING DEFAULTS{% endif %}{% if data.like_constraints %}
+
+ INCLUDING CONSTRAINTS{% endif %}{% if data.like_indexes %}
+
+ INCLUDING INDEXES{% endif %}{% if data.like_storage %}
+
+ INCLUDING STORAGE{% endif %}{% if data.like_comments %}
+
+ INCLUDING COMMENTS{% endif %}{% if data.like_generated %}
+
+ INCLUDING GENERATED{% endif %}{% if data.like_identity %}
+
+ INCLUDING IDENTITY{% endif %}{% if data.like_statistics %}
+
+ INCLUDING STATISTICS{% endif %}{% if data.columns|length > 0 %},
+{% endif %}
+
+{% endif %}
+{### Add columns ###}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.name and c.cltype %}
+ {% if c.inheritedfromtable %}-- Inherited from table {{c.inheritedfromtable}}: {% elif c.inheritedfromtype %}-- Inherited from type {{c.inheritedfromtype}}: {% endif %}{{conn|qtIdent(c.name)}} {% if is_sql %}{{c.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, c.cltype, c.attlen, c.attprecision, c.hasSqrBracket) }}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.attnotnull %} NOT NULL{% endif %}{% if c.defval is defined and c.defval is not none and c.defval != '' and c.colconstype != 'g' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'i' and c.attidentity and c.attidentity != '' %}
+{% if c.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif c.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %} ( {% endif %}
+{% if c.seqcycle is defined and c.seqcycle %}
+CYCLE {% endif %}{% if c.seqincrement is defined and c.seqincrement|int(-1) > -1 %}
+INCREMENT {{c.seqincrement|int}} {% endif %}{% if c.seqstart is defined and c.seqstart|int(-1) > -1%}
+START {{c.seqstart|int}} {% endif %}{% if c.seqmin is defined and c.seqmin|int(-1) > -1%}
+MINVALUE {{c.seqmin|int}} {% endif %}{% if c.seqmax is defined and c.seqmax|int(-1) > -1%}
+MAXVALUE {{c.seqmax|int}} {% endif %}{% if c.seqcache is defined and c.seqcache|int(-1) > -1%}
+CACHE {{c.seqcache|int}} {% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %}){% endif %}
+{% endif %}
+{% if c.colconstype == 'g' and c.genexpr and c.genexpr != '' %} GENERATED ALWAYS AS ({{c.genexpr}}) STORED{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 %}{% if data.columns|length > 0 %},{% endif %}
+{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+){% endif %}{% if data.relkind is defined and data.relkind == 'p' %} PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if not data.coll_inherits and not data.spcname and not with_clause and not data.amname %};{% endif %}
+
+{### If we are inheriting it from another table(s) ###}
+{% if data.coll_inherits %}
+ INHERITS ({% for val in data.coll_inherits %}{% if loop.index != 1 %}, {% endif %}{{val}}{% endfor %}){% if not data.spcname and not with_clause and not data.amname %};{% endif %}
+{% endif %}
+
+{% if data.default_amname and data.default_amname != data.amname and data.amname is not none %}
+USING {{data.amname}}
+{% elif not data.default_amname and data.amname %}
+USING {{data.amname}}{% if not data.spcname and not with_clause %};{% endif %}
+{% endif %}
+
+{% if with_clause %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.parallel_workers %}
+{% if ns.add_comma %},
+{% endif %}
+ parallel_workers = {{ data.parallel_workers }}{% set ns.add_comma = true%}{% endif %}{% if data.toast_tuple_target %}
+{% if ns.add_comma %},
+{% endif %}
+ toast_tuple_target = {{ data.toast_tuple_target }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_custom %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.{{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+
+{% if data.spcname %}){% else %});{% endif %}
+
+{% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{### Security Labels on Table ###}
+{% if data.seclabels and data.seclabels|length > 0 %}
+
+{% for r in data.seclabels %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{### ACL on Table ###}
+{% if data.revoke_all %}
+{% for priv in data.revoke_all %}
+{{ PRIVILEGE.UNSETALL(conn, "TABLE", priv, data.name, data.schema)}}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE ENDS HERE ======#}
+{#===========================================#}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if c.attstorage is defined and c.attstorage != c.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STORAGE {%if c.attstorage == 'p' %}
+PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}
+EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if c.attacl and c.attacl|length > 0 %}
+
+{% for priv in c.attacl %}
+{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.name, c.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if c.seclabels and c.seclabels|length > 0 %}
+
+{% for r in c.seclabels %}
+{{ COLUMN_SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.name, c.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES ENDS HERE #}
+{#===========================================#}
+{#======================================#}
+{# CONSTRAINTS SPECIFIC TEMPLATES #}
+{#======================================#}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.primary_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.unique_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.foreign_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.check_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.exclude_constraint)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_access_methods.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_access_methods.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2a93232bfa64b16dcd90042a49e97b7c7c7d0f83
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_access_methods.sql
@@ -0,0 +1,3 @@
+-- Fetches access methods
+SELECT oid, amname
+FROM pg_catalog.pg_am WHERE amtype = 't';
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_tables_for_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_tables_for_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..594a00a70f116ccd4a965571abdd18d65c18a0ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/get_tables_for_constraints.sql
@@ -0,0 +1,8 @@
+SELECT cl.oid as value, pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(relname) AS label
+FROM pg_catalog.pg_namespace nsp, pg_class cl
+WHERE relnamespace=nsp.oid AND relkind in ('r', 'p')
+ AND nsp.nspname NOT LIKE E'pg\_temp\_%'
+ {% if not show_sysobj %}
+ AND (nsp.nspname NOT LIKE 'pg\_%' AND nsp.nspname NOT in ('information_schema'))
+ {% endif %}
+ORDER BY nspname, relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ea420a44f3432bf569812c3656290cb6475b08ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/properties.sql
@@ -0,0 +1,77 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 OR rel.relkind = 'p' THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (CASE rel.relreplident
+ WHEN 'd' THEN 'default'
+ WHEN 'n' THEN 'nothing'
+ WHEN 'f' THEN 'full'
+ WHEN 'i' THEN 'index'
+ END) as replica_identity,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as schema,
+ pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, rel.relkind,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ (SELECT st.setting from pg_catalog.pg_settings st WHERE st.name = 'default_table_access_method') as default_amname,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'parallel_workers=([0-9]*)') AS parallel_workers,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'toast_tuple_target=([0-9]*)') AS toast_tuple_target,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype, am.amname,
+ CASE WHEN typ.typname IS NOT NULL THEN (select pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid )||'.'||pg_catalog.quote_ident(typ.typname) ELSE typ.typname END AS typname,
+ typ.typrelid AS typoid, rel.relrowsecurity as rlspolicy, rel.relforcerowsecurity as forcerlspolicy,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table
+ -- Added for partition table
+ {% if tid %}, (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef({{ tid }}::oid) ELSE '' END) AS partition_scheme {% endif %}
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = rel.relam
+WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+AND NOT rel.relispartition
+{% if tid %} AND rel.oid = {{ tid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e14750395597fe3ae20dc6b5d7900d00bc75ad0f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/12_plus/update.sql
@@ -0,0 +1,284 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{#####################################################}
+{## Rename table ##}
+{#####################################################}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{#####################################################}
+{## Change table schema ##}
+{#####################################################}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, data.name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+
+{% endif %}
+{#####################################################}
+{## Change table owner ##}
+{#####################################################}
+{% if data.relowner and data.relowner != o_data.relowner %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER TO {{conn|qtIdent(data.relowner)}};
+
+{% endif %}
+{#####################################################}
+{## Update Inherits table definition ##}
+{#####################################################}
+{% if data.coll_inherits_added|length > 0 %}
+{% for val in data.coll_inherits_added %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{% if data.coll_inherits_removed|length > 0 %}
+{% for val in data.coll_inherits_removed %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{#####################################################}
+{## Change tablespace ##}
+{#####################################################}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET TABLESPACE {{conn|qtIdent(data.spcname)}};
+
+{% endif %}
+
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% elif data.rlspolicy is defined and data.rlspolicy != o_data.rlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ DISABLE ROW LEVEL SECURITY;
+
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% elif data.forcerlspolicy is defined and data.forcerlspolicy != o_data.forcerlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## change fillfactor settings ##}
+{#####################################################}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (FILLFACTOR={{data.fillfactor}});
+{% elif (data.fillfactor == '' or data.fillfactor == None) and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (FILLFACTOR);
+
+{% endif %}
+
+{## change parallel_workers settings ##}
+{#####################################################}
+{% if (data.parallel_workers == '' or data.parallel_workers == None) and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (parallel_workers);
+{% elif data.parallel_workers is defined and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (parallel_workers={{data.parallel_workers}});
+
+{% endif %}
+
+{## change toast_tuple_target settings ##}
+{#####################################################}
+{% if (data.toast_tuple_target == '' or data.toast_tuple_target == None) and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (toast_tuple_target);
+{% elif data.toast_tuple_target is defined and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (toast_tuple_target={{data.toast_tuple_target}});
+
+{% endif %}
+
+{###############################}
+{## Table AutoVacuum settings ##}
+{###############################}
+{% if data.vacuum_table is defined and data.vacuum_table.set_values|length > 0 %}
+{% set has_vacuum_set = true %}
+{% endif %}
+{% if data.vacuum_table is defined and data.vacuum_table.reset_values|length > 0 %}
+{% set has_vacuum_reset = true %}
+{% endif %}
+{% if o_data.autovacuum_custom and data.autovacuum_custom == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ autovacuum_enabled,
+ autovacuum_analyze_scale_factor,
+ autovacuum_analyze_threshold,
+ autovacuum_freeze_max_age,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_vacuum_threshold,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_table_age
+);
+{% else %}
+{% if (data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_set %}
+{% for opt in data.vacuum_table.set_values %}{% if opt.name and opt.value is defined %}
+ {{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.autovacuum_enabled == 'x' and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.autovacuum_enabled =='x' and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled{% if has_vacuum_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_reset %}
+{% for opt in data.vacuum_table.reset_values %}{% if opt.name %}
+ {{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################}
+{## Toast table AutoVacuum settings ##}
+{#####################################}
+{% if data.vacuum_toast is defined and data.vacuum_toast.set_values|length > 0 %}
+{% set has_vacuum_toast_set = true %}
+{% endif %}
+{% if data.vacuum_toast is defined and data.vacuum_toast.reset_values|length > 0 %}
+{% set has_vacuum_toast_reset = true %}
+{% endif %}
+{% if o_data.toast_autovacuum and data.toast_autovacuum == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ toast.autovacuum_enabled,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_table_age,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_analyze_scale_factor
+);
+{% else %}
+{% if (data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_toast_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_set %}
+{% for opt in data.vacuum_toast.set_values %}{% if opt.name and opt.value is defined %}
+ toast.{{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled{% if has_vacuum_toast_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_reset %}
+{% for opt in data.vacuum_toast.reset_values %}{% if opt.name %}
+ toast.{{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Change table comments ##}
+{#####################################################}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{#####################################################}
+{## Update table Privileges ##}
+{#####################################################}
+{% if data.relacl %}
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Update table SecurityLabel ##}
+{#####################################################}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TABLE', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#####################################################}
+{## Change replica identity ##}
+{#####################################################}
+{% if data.replica_identity and data.replica_identity != o_data.replica_identity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} REPLICA IDENTITY {{data.replica_identity }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..823e1f337e389d4fd6244667290cea22774e617d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/14_plus/create.sql
@@ -0,0 +1,241 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'columns/macros/security.macros' as COLUMN_SECLABEL %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{#
+ If user has not provided any details but only name then
+ add empty bracket with table name
+#}
+{% set empty_bracket = ""%}
+{% if data.coll_inherits|length == 0 and data.columns|length == 0 and not data.typname and not data.like_relation and data.primary_key|length == 0 and data.unique_constraint|length == 0 and data.foreign_key|length == 0 and data.check_constraint|length == 0 and data.exclude_constraint|length == 0 %}
+{% set empty_bracket = "\n(\n)"%}
+{% endif %}
+{% set with_clause = false%}
+{% if data.fillfactor or data.parallel_workers or data.toast_tuple_target or (data.autovacuum_custom and data.add_vacuum_settings_in_sql) or data.autovacuum_enabled in ('t', 'f') or (data.toast_autovacuum and data.add_vacuum_settings_in_sql) or data.toast_autovacuum_enabled in ('t', 'f') %}
+{% set with_clause = true%}
+{% endif %}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{{empty_bracket}}
+{% if data.typname %}
+ OF {{ data.typname }}
+{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+(
+{% endif %}
+{% if data.like_relation %}
+ LIKE {{ data.like_relation }}{% if data.like_default_value %}
+
+ INCLUDING DEFAULTS{% endif %}{% if data.like_constraints %}
+
+ INCLUDING CONSTRAINTS{% endif %}{% if data.like_indexes %}
+
+ INCLUDING INDEXES{% endif %}{% if data.like_storage %}
+
+ INCLUDING STORAGE{% endif %}{% if data.like_comments %}
+
+ INCLUDING COMMENTS{% endif %}{% if data.like_compression %}
+
+ INCLUDING COMPRESSION{% endif %}{% if data.like_generated %}
+
+ INCLUDING GENERATED{% endif %}{% if data.like_identity %}
+
+ INCLUDING IDENTITY{% endif %}{% if data.like_statistics %}
+
+ INCLUDING STATISTICS{% endif %}{% if data.columns|length > 0 %},
+{% endif %}
+
+{% endif %}
+{### Add columns ###}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.name and c.cltype %}
+ {% if c.inheritedfromtable %}-- Inherited from table {{c.inheritedfromtable}}: {% elif c.inheritedfromtype %}-- Inherited from type {{c.inheritedfromtype}}: {% endif %}{{conn|qtIdent(c.name)}} {% if is_sql %}{{c.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, c.cltype, c.attlen, c.attprecision, c.hasSqrBracket) }}{% endif %}{% if c.attcompression is defined and c.attcompression is not none and c.attcompression != '' %} COMPRESSION {{c.attcompression}}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.attnotnull %} NOT NULL{% endif %}{% if c.defval is defined and c.defval is not none and c.defval != '' and c.colconstype != 'g' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'i' and c.attidentity and c.attidentity != '' %}
+{% if c.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif c.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %} ( {% endif %}
+{% if c.seqcycle is defined and c.seqcycle %}
+CYCLE {% endif %}{% if c.seqincrement is defined and c.seqincrement|int(-1) > -1 %}
+INCREMENT {{c.seqincrement|int}} {% endif %}{% if c.seqstart is defined and c.seqstart|int(-1) > -1%}
+START {{c.seqstart|int}} {% endif %}{% if c.seqmin is defined and c.seqmin|int(-1) > -1%}
+MINVALUE {{c.seqmin|int}} {% endif %}{% if c.seqmax is defined and c.seqmax|int(-1) > -1%}
+MAXVALUE {{c.seqmax|int}} {% endif %}{% if c.seqcache is defined and c.seqcache|int(-1) > -1%}
+CACHE {{c.seqcache|int}} {% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %}){% endif %}
+{% endif %}
+{% if c.colconstype == 'g' and c.genexpr and c.genexpr != '' %} GENERATED ALWAYS AS ({{c.genexpr}}) STORED{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 %}{% if data.columns|length > 0 %},{% endif %}
+{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+){% endif %}{% if data.relkind is defined and data.relkind == 'p' %} PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if not data.coll_inherits and not data.spcname and not with_clause and not data.amname %};{% endif %}
+
+{### If we are inheriting it from another table(s) ###}
+{% if data.coll_inherits %}
+ INHERITS ({% for val in data.coll_inherits %}{% if loop.index != 1 %}, {% endif %}{{val}}{% endfor %}){% if not data.spcname and not with_clause and not data.amname %};{% endif %}
+{% endif %}
+
+{% if data.default_amname and data.default_amname != data.amname and data.amname is not none %}
+USING {{data.amname}}
+{% elif data.amname and not data.default_amname %}
+USING {{data.amname}}{% if not data.spcname and not with_clause %};{% endif %}
+{% endif %}
+
+{% if with_clause %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.parallel_workers %}
+{% if ns.add_comma %},
+{% endif %}
+ parallel_workers = {{ data.parallel_workers }}{% set ns.add_comma = true%}{% endif %}{% if data.toast_tuple_target %}
+{% if ns.add_comma %},
+{% endif %}
+ toast_tuple_target = {{ data.toast_tuple_target }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_custom %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.{{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+
+{% if data.spcname %}){% else %});{% endif %}
+
+{% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{### Security Labels on Table ###}
+{% if data.seclabels and data.seclabels|length > 0 %}
+
+{% for r in data.seclabels %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{### ACL on Table ###}
+{% if data.revoke_all %}
+{% for priv in data.revoke_all %}
+{{ PRIVILEGE.UNSETALL(conn, "TABLE", priv, data.name, data.schema)}}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE ENDS HERE ======#}
+{#===========================================#}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if c.attstorage is defined and c.attstorage != c.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STORAGE {%if c.attstorage == 'p' %}
+PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}
+EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if c.attacl and c.attacl|length > 0 %}
+
+{% for priv in c.attacl %}
+{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.name, c.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if c.seclabels and c.seclabels|length > 0 %}
+
+{% for r in c.seclabels %}
+{{ COLUMN_SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.name, c.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES ENDS HERE #}
+{#===========================================#}
+{#======================================#}
+{# CONSTRAINTS SPECIFIC TEMPLATES #}
+{#======================================#}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.primary_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.unique_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.foreign_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.check_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.exclude_constraint)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/15_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/15_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4483a08a307e1203d65b7cfcc687d3d551233a38
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/15_plus/update.sql
@@ -0,0 +1,292 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{#####################################################}
+{## Rename table ##}
+{#####################################################}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{#####################################################}
+{## change table access method ##}
+{#####################################################}
+{% if data.amname and data.amname != o_data.amname %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET ACCESS METHOD {{conn|qtIdent(data.amname)}};
+
+{% endif %}
+{#####################################################}
+{## Change table schema ##}
+{#####################################################}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, data.name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+
+{% endif %}
+{#####################################################}
+{## Change table owner ##}
+{#####################################################}
+{% if data.relowner and data.relowner != o_data.relowner %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER TO {{conn|qtIdent(data.relowner)}};
+
+{% endif %}
+{#####################################################}
+{## Update Inherits table definition ##}
+{#####################################################}
+{% if data.coll_inherits_added|length > 0 %}
+{% for val in data.coll_inherits_added %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{% if data.coll_inherits_removed|length > 0 %}
+{% for val in data.coll_inherits_removed %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{#####################################################}
+{## Change tablespace ##}
+{#####################################################}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET TABLESPACE {{conn|qtIdent(data.spcname)}};
+
+{% endif %}
+
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% elif data.rlspolicy is defined and data.rlspolicy != o_data.rlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ DISABLE ROW LEVEL SECURITY;
+
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% elif data.forcerlspolicy is defined and data.forcerlspolicy != o_data.forcerlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## change fillfactor settings ##}
+{#####################################################}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (FILLFACTOR={{data.fillfactor}});
+{% elif (data.fillfactor == '' or data.fillfactor == None) and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (FILLFACTOR);
+
+{% endif %}
+
+{## change parallel_workers settings ##}
+{#####################################################}
+{% if (data.parallel_workers == '' or data.parallel_workers == None) and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (parallel_workers);
+{% elif data.parallel_workers is defined and data.parallel_workers != o_data.parallel_workers %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (parallel_workers={{data.parallel_workers}});
+
+{% endif %}
+
+{## change toast_tuple_target settings ##}
+{#####################################################}
+{% if (data.toast_tuple_target == '' or data.toast_tuple_target == None) and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (toast_tuple_target);
+{% elif data.toast_tuple_target is defined and data.toast_tuple_target != o_data.toast_tuple_target %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (toast_tuple_target={{data.toast_tuple_target}});
+
+{% endif %}
+
+{###############################}
+{## Table AutoVacuum settings ##}
+{###############################}
+{% if data.vacuum_table is defined and data.vacuum_table.set_values|length > 0 %}
+{% set has_vacuum_set = true %}
+{% endif %}
+{% if data.vacuum_table is defined and data.vacuum_table.reset_values|length > 0 %}
+{% set has_vacuum_reset = true %}
+{% endif %}
+{% if o_data.autovacuum_custom and data.autovacuum_custom == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ autovacuum_enabled,
+ autovacuum_analyze_scale_factor,
+ autovacuum_analyze_threshold,
+ autovacuum_freeze_max_age,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_vacuum_threshold,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_table_age
+);
+{% else %}
+{% if (data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_set %}
+{% for opt in data.vacuum_table.set_values %}{% if opt.name and opt.value is defined %}
+ {{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.autovacuum_enabled == 'x' and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.autovacuum_enabled =='x' and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled{% if has_vacuum_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_reset %}
+{% for opt in data.vacuum_table.reset_values %}{% if opt.name %}
+ {{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################}
+{## Toast table AutoVacuum settings ##}
+{#####################################}
+{% if data.vacuum_toast is defined and data.vacuum_toast.set_values|length > 0 %}
+{% set has_vacuum_toast_set = true %}
+{% endif %}
+{% if data.vacuum_toast is defined and data.vacuum_toast.reset_values|length > 0 %}
+{% set has_vacuum_toast_reset = true %}
+{% endif %}
+{% if o_data.toast_autovacuum and data.toast_autovacuum == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ toast.autovacuum_enabled,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_table_age,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_analyze_scale_factor
+);
+{% else %}
+{% if (data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_toast_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_set %}
+{% for opt in data.vacuum_toast.set_values %}{% if opt.name and opt.value is defined %}
+ toast.{{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled{% if has_vacuum_toast_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_reset %}
+{% for opt in data.vacuum_toast.reset_values %}{% if opt.name %}
+ toast.{{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Change table comments ##}
+{#####################################################}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{#####################################################}
+{## Update table Privileges ##}
+{#####################################################}
+{% if data.relacl %}
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Update table SecurityLabel ##}
+{#####################################################}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TABLE', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#####################################################}
+{## Change replica identity ##}
+{#####################################################}
+{% if data.replica_identity and data.replica_identity != o_data.replica_identity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} REPLICA IDENTITY {{data.replica_identity }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/coll_table_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/coll_table_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0dbce15f31feecfbf3d7d491b6588cf706826634
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/coll_table_stats.sql
@@ -0,0 +1,30 @@
+SELECT
+ st.relname AS {{ conn|qtIdent(_('Table name')) }},
+ pg_catalog.pg_relation_size(st.relid)
+ + CASE WHEN cl.reltoastrelid = 0 THEN 0 ELSE pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0) END
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=st.relid)::int8, 0) AS {{ conn|qtIdent(_('Total Size')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ last_seq_scan AS {{ conn|qtIdent(_('Last sequential scan')) }},
+ vacuum_count AS {{ conn|qtIdent(_('Vacuum counter')) }},
+ autovacuum_count AS {{ conn|qtIdent(_('Autovacuum counter')) }},
+ analyze_count AS {{ conn|qtIdent(_('Analyze counter')) }},
+ autoanalyze_count AS {{ conn|qtIdent(_('Autoanalyze counter')) }}
+FROM
+ pg_catalog.pg_stat_all_tables st
+JOIN
+ pg_catalog.pg_class cl on cl.oid=st.relid and cl.relkind IN ('r','s','t','p')
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ORDER BY st.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..93ea6ecee3a15fe26b637ce686e6dc0623a0bbf9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/create.sql
@@ -0,0 +1,233 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'columns/macros/security.macros' as COLUMN_SECLABEL %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{#
+ If user has not provided any details but only name then
+ add empty bracket with table name
+#}
+{% set empty_bracket = ""%}
+{% if data.coll_inherits|length == 0 and data.columns|length == 0 and not data.typname and not data.like_relation and data.primary_key|length == 0 and data.unique_constraint|length == 0 and data.foreign_key|length == 0 and data.check_constraint|length == 0 and data.exclude_constraint|length == 0 %}
+{% set empty_bracket = "\n(\n)"%}
+{% endif %}
+{% set with_clause = false%}
+{% if data.fillfactor or data.parallel_workers or data.toast_tuple_target or (data.autovacuum_custom and data.add_vacuum_settings_in_sql) or data.autovacuum_enabled in ('t', 'f') or (data.toast_autovacuum and data.add_vacuum_settings_in_sql) or data.toast_autovacuum_enabled in ('t', 'f') %}
+{% set with_clause = true%}
+{% endif %}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{{empty_bracket}}
+{% if data.typname %}
+ OF {{ data.typname }}
+{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+(
+{% endif %}
+{% if data.like_relation %}
+ LIKE {{ data.like_relation }}{% if data.like_default_value %}
+
+ INCLUDING DEFAULTS{% endif %}{% if data.like_constraints %}
+
+ INCLUDING CONSTRAINTS{% endif %}{% if data.like_indexes %}
+
+ INCLUDING INDEXES{% endif %}{% if data.like_storage %}
+
+ INCLUDING STORAGE{% endif %}{% if data.like_comments %}
+
+ INCLUDING COMMENTS{% endif %}{% if data.like_compression %}
+
+ INCLUDING COMPRESSION{% endif %}{% if data.like_generated %}
+
+ INCLUDING GENERATED{% endif %}{% if data.like_identity %}
+
+ INCLUDING IDENTITY{% endif %}{% if data.like_statistics %}
+
+ INCLUDING STATISTICS{% endif %}{% if data.columns|length > 0 %},
+{% endif %}
+
+{% endif %}
+{### Add columns ###}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.name and c.cltype %}
+ {% if c.inheritedfromtable %}-- Inherited from table {{c.inheritedfromtable}}: {% elif c.inheritedfromtype %}-- Inherited from type {{c.inheritedfromtype}}: {% endif %}{{conn|qtIdent(c.name)}} {% if is_sql %}{{c.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, c.cltype, c.attlen, c.attprecision, c.hasSqrBracket) }}{% endif %}{%if c.attstorage is defined and c.attstorage != c.defaultstorage%} STORAGE {%if c.attstorage == 'p' %}PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% elif c.attstorage == 'd'%}DEFAULT{% endif %}{% endif %}{% if c.attcompression is defined and c.attcompression is not none and c.attcompression != '' %} COMPRESSION {{c.attcompression}}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.attnotnull %} NOT NULL{% endif %}{% if c.defval is defined and c.defval is not none and c.defval != '' and c.colconstype != 'g' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'i' and c.attidentity and c.attidentity != '' %}
+{% if c.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif c.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %} ( {% endif %}
+{% if c.seqcycle is defined and c.seqcycle %}
+CYCLE {% endif %}{% if c.seqincrement is defined and c.seqincrement|int(-1) > -1 %}
+INCREMENT {{c.seqincrement|int}} {% endif %}{% if c.seqstart is defined and c.seqstart|int(-1) > -1%}
+START {{c.seqstart|int}} {% endif %}{% if c.seqmin is defined and c.seqmin|int(-1) > -1%}
+MINVALUE {{c.seqmin|int}} {% endif %}{% if c.seqmax is defined and c.seqmax|int(-1) > -1%}
+MAXVALUE {{c.seqmax|int}} {% endif %}{% if c.seqcache is defined and c.seqcache|int(-1) > -1%}
+CACHE {{c.seqcache|int}} {% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %}){% endif %}
+{% endif %}
+{% if c.colconstype == 'g' and c.genexpr and c.genexpr != '' %} GENERATED ALWAYS AS ({{c.genexpr}}) STORED{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 %}{% if data.columns|length > 0 %},{% endif %}
+{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+){% endif %}{% if data.relkind is defined and data.relkind == 'p' %} PARTITION BY {{ data.partition_scheme }}{% endif %}
+{% if not data.coll_inherits and not data.spcname and not with_clause and not data.amname %};{% endif %}
+
+{### If we are inheriting it from another table(s) ###}
+{% if data.coll_inherits %}
+ INHERITS ({% for val in data.coll_inherits %}{% if loop.index != 1 %}, {% endif %}{{val}}{% endfor %}){% if not data.spcname and not with_clause and not data.amname %};{% endif %}
+{% endif %}
+
+{% if data.default_amname and data.default_amname != data.amname and data.amname is not none %}
+USING {{data.amname}}
+{% elif data.amname and not data.default_amname %}
+USING {{data.amname}}{% if not data.spcname and not with_clause %};{% endif %}
+{% endif %}
+
+{% if with_clause %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}{% set ns.add_comma = true%}
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.parallel_workers %}
+{% if ns.add_comma %},
+{% endif %}
+ parallel_workers = {{ data.parallel_workers }}{% set ns.add_comma = true%}{% endif %}{% if data.toast_tuple_target %}
+{% if ns.add_comma %},
+{% endif %}
+ toast_tuple_target = {{ data.toast_tuple_target }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_custom %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ {{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.{{opt.name}} = {{opt.value}}{% set ns.add_comma = true%}{% endif %}
+{% endfor %}{% endif %}
+
+{% if data.spcname %}){% else %});{% endif %}
+
+{% endif %}
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{### Security Labels on Table ###}
+{% if data.seclabels and data.seclabels|length > 0 %}
+
+{% for r in data.seclabels %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{### ACL on Table ###}
+{% if data.revoke_all %}
+{% for priv in data.revoke_all %}
+{{ PRIVILEGE.UNSETALL(conn, "TABLE", priv, data.name, data.schema)}}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE ENDS HERE ======#}
+{#===========================================#}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### ACL ###}
+{% if c.attacl and c.attacl|length > 0 %}
+
+{% for priv in c.attacl %}
+{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.name, c.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if c.seclabels and c.seclabels|length > 0 %}
+
+{% for r in c.seclabels %}
+{{ COLUMN_SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.name, c.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES ENDS HERE #}
+{#===========================================#}
+{#======================================#}
+{# CONSTRAINTS SPECIFIC TEMPLATES #}
+{#======================================#}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.primary_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.unique_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.foreign_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.check_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.exclude_constraint)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0ca8f6c826563613544ad9a9a3cec2d1c795d87a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/stats.sql
@@ -0,0 +1,54 @@
+SELECT
+ seq_scan AS {{ conn|qtIdent(_('Sequential scans')) }},
+ seq_tup_read AS {{ conn|qtIdent(_('Sequential tuples read')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ heap_blks_read AS {{ conn|qtIdent(_('Heap blocks read')) }},
+ heap_blks_hit AS {{ conn|qtIdent(_('Heap blocks hit')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ toast_blks_read AS {{ conn|qtIdent(_('Toast blocks read')) }},
+ toast_blks_hit AS {{ conn|qtIdent(_('Toast blocks hit')) }},
+ tidx_blks_read AS {{ conn|qtIdent(_('Toast index blocks read')) }},
+ tidx_blks_hit AS {{ conn|qtIdent(_('Toast index blocks hit')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ last_seq_scan AS {{ conn|qtIdent(_('Last sequential scan')) }},
+ pg_catalog.pg_relation_size(stat.relid) AS {{ conn|qtIdent(_('Table size')) }},
+ CASE WHEN cl.reltoastrelid = 0 THEN NULL ELSE pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0))
+ END AS {{ conn|qtIdent(_('Toast table size')) }},
+ COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=stat.relid)::int8, 0)
+ AS {{ conn|qtIdent(_('Indexes size')) }}
+{% if is_pgstattuple %}
+{#== EXTENDED STATS ==#}
+ ,tuple_count AS {{ conn|qtIdent(_('Tuple count')) }},
+ tuple_len AS {{ conn|qtIdent(_('Tuple length')) }},
+ tuple_percent AS {{ conn|qtIdent(_('Tuple percent')) }},
+ dead_tuple_count AS {{ conn|qtIdent(_('Dead tuple count')) }},
+ dead_tuple_len AS {{ conn|qtIdent(_('Dead tuple length')) }},
+ dead_tuple_percent AS {{ conn|qtIdent(_('Dead tuple percent')) }},
+ free_space AS {{ conn|qtIdent(_('Free space')) }},
+ free_percent AS {{ conn|qtIdent(_('Free percent')) }}
+FROM
+ pgstattuple('{{schema_name}}.{{table_name}}'), pg_catalog.pg_stat_all_tables stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_tables stat
+{% endif %}
+JOIN
+ pg_catalog.pg_statio_all_tables statio ON stat.relid = statio.relid
+JOIN
+ pg_catalog.pg_class cl ON cl.oid=stat.relid
+WHERE
+ stat.relid = {{ tid }}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a9f2bfa496a97d378ca21ee8810f2f85f2954369
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/acl.sql
@@ -0,0 +1,47 @@
+{### SQL to fetch privileges for tablespace ###}
+SELECT 'relacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor,
+ pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT rel.relacl
+ FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+ AND rel.oid = {{ tid }}::oid
+ ) acl,
+ (SELECT (d).grantee AS grantee, (d).grantor AS grantor, (d).is_grantable
+ AS is_grantable, (d).privilege_type AS privilege_type FROM (SELECT
+ aclexplode(rel.relacl) as d
+ FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+ WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+ AND rel.oid = {{ tid }}::oid
+ ) a ORDER BY privilege_type) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7c0f3642d32ca7be6573646b65aee316bd6dfb8d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/backend_support.sql
@@ -0,0 +1,18 @@
+SELECT
+ CASE WHEN nsp.nspname IN ('sys', 'information_schema') THEN true ELSE false END AS dbSupport
+FROM pg_catalog.pg_namespace nsp
+WHERE nsp.oid={{scid}}::oid
+AND (
+ (nspname = 'pg_catalog' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'pgagent' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname = 'information_schema' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1))
+ OR (nspname LIKE '_%' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1))
+)
+AND
+ nspname NOT LIKE E'pg\\temp\\%'
+AND
+ nspname NOT LIKE E'pg\\toast_temp\\%'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/coll_table_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/coll_table_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bcfd933ad45ca9362f756c10fbdfc7a1378f945a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/coll_table_stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ st.relname AS {{ conn|qtIdent(_('Table name')) }},
+ pg_catalog.pg_relation_size(st.relid)
+ + CASE WHEN cl.reltoastrelid = 0 THEN 0 ELSE pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0) END
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=st.relid)::int8, 0) AS {{ conn|qtIdent(_('Total Size')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ vacuum_count AS {{ conn|qtIdent(_('Vacuum counter')) }},
+ autovacuum_count AS {{ conn|qtIdent(_('Autovacuum counter')) }},
+ analyze_count AS {{ conn|qtIdent(_('Analyze counter')) }},
+ autoanalyze_count AS {{ conn|qtIdent(_('Autoanalyze counter')) }}
+FROM
+ pg_catalog.pg_stat_all_tables st
+JOIN
+ pg_catalog.pg_class cl on cl.oid=st.relid and cl.relkind IN ('r','s','t','p')
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ORDER BY st.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ee8b833e5c525ef41d29304e60096a7066b54a6a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/count.sql
@@ -0,0 +1,4 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class rel
+ WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+ AND NOT rel.relispartition;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3e57637813c29085867bc2f9c33f6f6659ecaaed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/create.sql
@@ -0,0 +1,212 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'columns/macros/security.macros' as COLUMN_SECLABEL %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{% import 'tables/sql/macros/constraints.macro' as CONSTRAINTS %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE STARTS HERE ======#}
+{#===========================================#}
+{#
+ If user has not provided any details but only name then
+ add empty bracket with table name
+#}
+{% set empty_bracket = ""%}
+{% if data.coll_inherits|length == 0 and data.columns|length == 0 and not data.typname and not data.like_relation and data.primary_key|length == 0 and data.unique_constraint|length == 0 and data.foreign_key|length == 0 and data.check_constraint|length == 0 and data.exclude_constraint|length == 0 %}
+{% set empty_bracket = "\n(\n)"%}
+{% endif %}
+CREATE {% if data.relpersistence %}UNLOGGED {% endif %}TABLE{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{conn|qtIdent(data.schema, data.name)}}{{empty_bracket}}
+{% if data.typname %}
+ OF {{ data.typname }}
+{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+(
+{% endif %}
+{% if data.like_relation %}
+ LIKE {{ data.like_relation }}{% if data.like_default_value %}
+
+ INCLUDING DEFAULTS{% endif %}{% if data.like_constraints %}
+
+ INCLUDING CONSTRAINTS{% endif %}{% if data.like_indexes %}
+
+ INCLUDING INDEXES{% endif %}{% if data.like_storage %}
+
+ INCLUDING STORAGE{% endif %}{% if data.like_comments %}
+
+ INCLUDING COMMENTS{% endif %}{% if data.like_identity %}
+
+ INCLUDING IDENTITY{% endif %}{% if data.like_statistics %}
+
+ INCLUDING STATISTICS{% endif %}{% if data.columns|length > 0 %},
+{% endif %}
+
+{% endif %}
+{### Add columns ###}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.name and c.cltype %}
+ {% if c.inheritedfromtable %}-- Inherited from table {{c.inheritedfromtable}}: {% elif c.inheritedfromtype %}-- Inherited from type {{c.inheritedfromtype}}: {% endif %}{{conn|qtIdent(c.name)}} {% if is_sql %}{{c.displaytypname}}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, c.cltype, c.attlen, c.attprecision, c.hasSqrBracket) }}{% endif %}{% if c.collspcname %} COLLATE {{c.collspcname}}{% endif %}{% if c.attnotnull %} NOT NULL{% endif %}{% if c.defval is defined and c.defval is not none and c.defval != '' %} DEFAULT {{c.defval}}{% endif %}
+{% if c.colconstype == 'i' and c.attidentity and c.attidentity != '' %}
+{% if c.attidentity == 'a' %} GENERATED ALWAYS AS IDENTITY{% elif c.attidentity == 'd' %} GENERATED BY DEFAULT AS IDENTITY{% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %} ( {% endif %}
+{% if c.seqcycle is defined and c.seqcycle %}
+CYCLE {% endif %}{% if c.seqincrement is defined and c.seqincrement|int(-1) > -1 %}
+INCREMENT {{c.seqincrement|int}} {% endif %}{% if c.seqstart is defined and c.seqstart|int(-1) > -1%}
+START {{c.seqstart|int}} {% endif %}{% if c.seqmin is defined and c.seqmin|int(-1) > -1%}
+MINVALUE {{c.seqmin|int}} {% endif %}{% if c.seqmax is defined and c.seqmax|int(-1) > -1%}
+MAXVALUE {{c.seqmax|int}} {% endif %}{% if c.seqcache is defined and c.seqcache|int(-1) > -1%}
+CACHE {{c.seqcache|int}} {% endif %}
+{% if c.seqincrement or c.seqcycle or c.seqincrement or c.seqstart or c.seqmin or c.seqmax or c.seqcache %}){% endif %}
+{% endif %}
+{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{# Macro to render for constraints #}
+{% if data.primary_key|length > 0 %}{% if data.columns|length > 0 %},{% endif %}
+{{CONSTRAINTS.PRIMARY_KEY(conn, data.primary_key[0])}}{% endif %}{% if data.unique_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.UNIQUE(conn, data.unique_constraint)}}{% endif %}{% if data.foreign_key|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.FOREIGN_KEY(conn, data.foreign_key)}}{% endif %}{% if data.check_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 %},{% endif %}
+{{CONSTRAINTS.CHECK(conn, data.check_constraint)}}{% endif %}{% if data.exclude_constraint|length > 0 %}{% if data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 %},{% endif %}
+{{CONSTRAINTS.EXCLUDE(conn, data.exclude_constraint)}}{% endif %}
+{% if data.like_relation or data.coll_inherits or data.columns|length > 0 or data.primary_key|length > 0 or data.unique_constraint|length > 0 or data.foreign_key|length > 0 or data.check_constraint|length > 0 or data.exclude_constraint|length > 0 %}
+
+){% endif %}{% if data.relkind is defined and data.relkind == 'p' %} PARTITION BY {{ data.partition_scheme }}{% endif %}
+
+{### If we are inheriting it from another table(s) ###}
+{% if data.coll_inherits %}
+ INHERITS ({% for val in data.coll_inherits %}{% if loop.index != 1 %}, {% endif %}{{val}}{% endfor %})
+{% endif %}
+WITH (
+ OIDS = {% if data.relhasoids %}TRUE{% else %}FALSE{% endif %}{% if data.fillfactor %},
+ FILLFACTOR = {{ data.fillfactor }}{% endif %}{% if data.parallel_workers is defined and data.parallel_workers != '' and data.parallel_workers != None %},
+ parallel_workers = {{ data.parallel_workers }}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %},
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %},
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}
+{% endif %}{% if data.autovacuum_custom and data.vacuum_table|length > 0 %}
+{% for opt in data.vacuum_table %}{% if opt.name and opt.value is defined %}
+,
+ {{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}{% if data.toast_autovacuum and data.vacuum_toast|length > 0 %}
+{% for opt in data.vacuum_toast %}{% if opt.name and opt.value is defined %}
+,
+ toast.{{opt.name}} = {{opt.value}}{% endif %}
+{% endfor %}{% endif %}
+
+{### SQL for Tablespace ###}
+{% if data.spcname %}
+)
+TABLESPACE {{ conn|qtIdent(data.spcname) }};
+{% else %}
+);
+{% endif %}
+{### Alter SQL for Owner ###}
+{% if data.relowner %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER to {{conn|qtIdent(data.relowner)}};
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{### Security Labels on Table ###}
+{% if data.seclabels and data.seclabels|length > 0 %}
+
+{% for r in data.seclabels %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{### ACL on Table ###}
+{% if data.revoke_all %}
+{% for priv in data.revoke_all %}
+{{ PRIVILEGE.UNSETALL(conn, "TABLE", priv, data.name, data.schema)}}
+{% endfor %}
+{% endif %}
+{% if data.relacl %}
+
+{% for priv in data.relacl %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### SQL for COMMENT ###}
+{% if data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{#===========================================#}
+{#====== MAIN TABLE TEMPLATE ENDS HERE ======#}
+{#===========================================#}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES STARTS HERE #}
+{#===========================================#}
+{% if data.columns and data.columns|length > 0 %}
+{% for c in data.columns %}
+{% if c.description %}
+
+COMMENT ON COLUMN {{conn|qtIdent(data.schema, data.name, c.name)}}
+ IS {{c.description|qtLiteral(conn)}};
+{% endif %}
+{### Add variables to column ###}
+{% if c.attoptions and c.attoptions|length > 0 %}
+
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ {{ VARIABLE.SET(conn, 'COLUMN', c.name, c.attoptions) }}
+
+{% endif %}
+{### Alter column statistics value ###}
+{% if c.attstattarget is defined and c.attstattarget > -1 %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STATISTICS {{c.attstattarget}};
+
+{% endif %}
+{### Alter column storage value ###}
+{% if c.attstorage is defined and c.attstorage != c.defaultstorage %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ALTER COLUMN {{conn|qtTypeIdent(c.name)}} SET STORAGE {%if c.attstorage == 'p' %}
+PLAIN{% elif c.attstorage == 'm'%}MAIN{% elif c.attstorage == 'e'%}
+EXTERNAL{% elif c.attstorage == 'x'%}EXTENDED{% endif %};
+
+{% endif %}
+{### ACL ###}
+{% if c.attacl and c.attacl|length > 0 %}
+
+{% for priv in c.attacl %}
+{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.name, c.name, priv.grantee, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if c.seclabels and c.seclabels|length > 0 %}
+
+{% for r in c.seclabels %}
+{{ COLUMN_SECLABEL.APPLY(conn, 'COLUMN',data.schema, data.name, c.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+{% endif %}
+{#===========================================#}
+{# COLUMN SPECIFIC TEMPLATES ENDS HERE #}
+{#===========================================#}
+{#======================================#}
+{# CONSTRAINTS SPECIFIC TEMPLATES #}
+{#======================================#}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.primary_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.unique_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.foreign_key)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.check_constraint)}}
+{{CONSTRAINTS.CONSTRAINT_COMMENTS(conn, data.schema, data.name, data.exclude_constraint)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..deb017b8c3886240d6eb825693e6de15c4c198b6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}{% if cascade %} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/depend.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/depend.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0371561fcdb3dfe047a4e4ff014f63a493d43878
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/depend.sql
@@ -0,0 +1,9 @@
+SELECT
+ ref.relname AS refname, d2.refclassid, dep.deptype AS deptype
+FROM pg_catalog.pg_depend dep
+ LEFT JOIN pg_catalog.pg_depend d2 ON dep.objid=d2.objid AND dep.refobjid != d2.refobjid
+ LEFT JOIN pg_catalog.pg_class ref ON ref.oid=d2.refobjid
+ LEFT JOIN pg_catalog.pg_attribute att ON d2.refclassid=att.attrelid AND d2.refobjsubid=att.attnum
+ {{ where }} AND
+ dep.classid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='pg_attrdef') AND
+ dep.refobjid NOT IN (SELECT d3.refobjid FROM pg_catalog.pg_depend d3 WHERE d3.objid=d2.refobjid)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/enable_disable_trigger.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/enable_disable_trigger.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d85d04e8f8a53d3afd3356dbde93517423559745
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/enable_disable_trigger.sql
@@ -0,0 +1,3 @@
+{% set enable_map = {'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(data.schema, data.name) }}
+ {{ enable_map[is_enable_trigger] }} TRIGGER ALL;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/fk_ref_tables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/fk_ref_tables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d4ad8c9e0135bad76ca18ced546236045d44c9a3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/fk_ref_tables.sql
@@ -0,0 +1,10 @@
+SELECT
+ co.conrelid as confrelid, co.conname, nl.oid as refnspoid
+FROM pg_catalog.pg_depend dep
+ JOIN pg_catalog.pg_constraint co ON dep.objid=co.oid
+ JOIN pg_catalog.pg_class cl ON cl.oid=co.conrelid
+ JOIN pg_catalog.pg_namespace nl ON nl.oid=cl.relnamespace
+ WHERE dep.refobjid={{oid}}::OID
+ AND deptype = 'n'
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_application_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_application_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7f97337e117c3275967a82f32e4085b8676d63e7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_application_name.sql
@@ -0,0 +1,8 @@
+SELECT
+ usename,
+ application_name
+FROM
+ pg_catalog.pg_stat_activity
+WHERE
+ pid = {{ pid }}
+ORDER BY pid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_columns_for_table.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_columns_for_table.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2b63fdab3dadca5b02c95f26014fe60527f27df1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_columns_for_table.sql
@@ -0,0 +1,19 @@
+SELECT
+ a.attname AS name, pg_catalog.format_type(a.atttypid, NULL) AS cltype,
+ pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval, a.attidentity as clidentity,
+ pg_catalog.quote_ident(n.nspname)||'.'||pg_catalog.quote_ident(c.relname) as inheritedfrom,
+ c.oid as inheritedid
+FROM
+ pg_catalog.pg_class c
+JOIN
+ pg_catalog.pg_namespace n ON c.relnamespace=n.oid
+JOIN
+ pg_catalog.pg_attribute a ON a.attrelid = c.oid AND NOT a.attisdropped AND a.attnum > 0
+LEFT OUTER JOIN
+ pg_catalog.pg_attrdef def ON adrelid=a.attrelid AND adnum=a.attnum
+WHERE
+{% if tid %}
+ c.oid = {{tid}}::OID
+{% else %}
+ c.relname = {{tname|qtLiteral(conn)}}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_inherits.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_inherits.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2e5df5f8fc110f2b74781ad1eaeea5452b6c93ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_inherits.sql
@@ -0,0 +1,17 @@
+{% import 'tables/sql/macros/db_catalogs.macro' as CATALOG %}
+SELECT c.oid, c.relname , nspname,
+CASE WHEN nspname NOT LIKE 'pg\_%' THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ELSE pg_catalog.quote_ident(c.relname)
+END AS inherits
+FROM pg_catalog.pg_class c
+JOIN pg_catalog.pg_namespace n
+ON n.oid=c.relnamespace
+WHERE relkind='r' AND NOT relispartition
+{% if not show_system_objects %}
+{{ CATALOG.VALID_CATALOGS(server_type) }}
+{% endif %}
+{% if tid %}
+AND c.oid != tid
+{% endif %}
+ORDER BY relnamespace, c.relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oftype.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oftype.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a1e05cda4055c5c27928ff7b36eda74f41cc30c5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oftype.sql
@@ -0,0 +1,9 @@
+{% import 'tables/sql/macros/db_catalogs.macro' as CATALOG %}
+SELECT c.oid,
+ pg_catalog.quote_ident(n.nspname)||'.'||pg_catalog.quote_ident(c.relname) AS typname
+ FROM pg_catalog.pg_namespace n, pg_catalog.pg_class c
+WHERE c.relkind = 'c' AND c.relnamespace=n.oid
+{% if not show_system_objects %}
+{{ CATALOG.VALID_CATALOGS(server_type) }}
+{% endif %}
+ORDER BY typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3f53d6f5a80f2238ed38e704c7fe3ff7f9f86011
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_oid.sql
@@ -0,0 +1,5 @@
+SELECT rel.oid as tid
+FROM pg_catalog.pg_class rel
+WHERE rel.relkind IN ('r','s','t','p')
+AND rel.relnamespace = {{ scid }}::oid
+AND rel.relname = {{data.name|qtLiteral(conn)}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_op_class.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_op_class.sql
new file mode 100644
index 0000000000000000000000000000000000000000..13704e067c64888f6f7a461fde4ed8671705708f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_op_class.sql
@@ -0,0 +1,3 @@
+SELECT opcname, opcmethod
+FROM pg_catalog.pg_opclass
+ ORDER BY 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_relations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_relations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d730176a1c7014ef92b67c561115549ddf00e3ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_relations.sql
@@ -0,0 +1,9 @@
+{% import 'tables/sql/macros/db_catalogs.macro' as CATALOG %}
+SELECT c.oid, pg_catalog.quote_ident(n.nspname)||'.'||pg_catalog.quote_ident(c.relname) AS like_relation
+FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n
+WHERE c.relnamespace=n.oid
+ AND c.relkind IN ('r', 'v', 'f')
+{% if not show_sys_objects %}
+{{ CATALOG.VALID_CATALOGS(server_type) }}
+{% endif %}
+ORDER BY 1;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..46f95c7cda0e608c7168c6166d9b8cf42b37beaf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_schema_oid.sql
@@ -0,0 +1,12 @@
+{# ===== fetch new assigned schema oid ===== #}
+SELECT
+ c.relnamespace as scid, nsp.nspname as nspname
+FROM
+ pg_catalog.pg_class c
+LEFT JOIN pg_catalog.pg_namespace nsp ON nsp.oid = c.relnamespace
+WHERE
+{% if tid %}
+ c.oid = {{tid}}::oid;
+{% else %}
+ c.relname = {{tname|qtLiteral(conn)}}::text AND nspname = {{sname|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table.sql
new file mode 100644
index 0000000000000000000000000000000000000000..df88c479150202de951bdb3a9383b7577f8bc10a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table.sql
@@ -0,0 +1,8 @@
+SELECT
+ rel.relname AS name
+FROM
+ pg_catalog.pg_class rel
+WHERE
+ rel.relkind IN ('r','s','t','p')
+ AND rel.relnamespace = {{ scid }}::oid
+ AND rel.oid = {{ tid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table_row_count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table_row_count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8788187e31b29dcb625689d94f7c1fdf486bb30a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_table_row_count.sql
@@ -0,0 +1 @@
+SELECT COUNT(*)::text FROM {{ conn|qtIdent(data.schema, data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_tables_for_constraints.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_tables_for_constraints.sql
new file mode 100644
index 0000000000000000000000000000000000000000..082c10cab1b91348d9396daf1adadd4323fb33c8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_tables_for_constraints.sql
@@ -0,0 +1,8 @@
+SELECT cl.oid as value, pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(relname) AS label
+FROM pg_catalog.pg_namespace nsp, pg_class cl
+WHERE relnamespace=nsp.oid AND relkind='r'
+ AND nsp.nspname NOT LIKE E'pg\_temp\_%'
+ {% if not show_sysobj %}
+ AND (nsp.nspname NOT LIKE 'pg\_%' AND nsp.nspname NOT in ('information_schema'))
+ {% endif %}
+ORDER BY nspname, relname
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_types_where_condition.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_types_where_condition.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2104d9c3c7c5c64a337e1d1cac22f62f43576f08
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/get_types_where_condition.sql
@@ -0,0 +1,10 @@
+{### Additional where condition for get_types route for column node ###}
+typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r', 'm')
+AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class WHERE relnamespace=typnamespace
+AND relname = typname AND relkind != 'c') AND
+(typname NOT LIKE '_%' OR NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class WHERE
+relnamespace=typnamespace AND relname = substring(typname FROM 2)::name
+AND relkind != 'c'))
+{% if not show_system_objects %}
+AND nsp.nspname != 'information_schema'
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/locks.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/locks.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b74f59ebd313a91826b62c4e33e6441f1c8fa4ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/locks.sql
@@ -0,0 +1,23 @@
+SELECT
+ pid,
+ locktype,
+ datname,
+ relation::regclass,
+ page,
+ tuple,
+ virtualxid
+ transactionid,
+ classid::regclass,
+ objid,
+ objsubid,
+ virtualtransaction,
+ mode,
+ granted,
+ fastpath
+FROM
+ pg_catalog.pg_locks l
+ LEFT OUTER JOIN pg_catalog.pg_database d ON (l.database = d.oid)
+{% if did %}WHERE
+ datname = (SELECT datname FROM pg_catalog.pg_database WHERE oid = {{ did }}){% endif %}
+ORDER BY
+ pid, locktype
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..db9749ab6eb5da715cfd52880de2c94a84ab88a7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/nodes.sql
@@ -0,0 +1,17 @@
+SELECT rel.oid, rel.relname AS name,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE AND tgenabled = 'O') AS has_enable_triggers,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ (SELECT count(1) FROM pg_catalog.pg_inherits WHERE inhrelid=rel.oid LIMIT 1) as is_inherits,
+ (SELECT count(1) FROM pg_catalog.pg_inherits WHERE inhparent=rel.oid LIMIT 1) as is_inherited,
+ des.description
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+ AND NOT rel.relispartition
+ {% if tid %} AND rel.oid = {{tid}}::OID {% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = rel.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..47e9a75dc85c06994ac066adf093fddf90f6b285
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/properties.sql
@@ -0,0 +1,74 @@
+SELECT rel.oid, rel.relname AS name, rel.reltablespace AS spcoid,rel.relacl AS relacl_str,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END) as spcname,
+ (CASE rel.relreplident
+ WHEN 'd' THEN 'default'
+ WHEN 'n' THEN 'nothing'
+ WHEN 'f' THEN 'full'
+ WHEN 'i' THEN 'index'
+ END) as replica_identity,
+ (select nspname FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid ) as schema,
+ pg_catalog.pg_get_userbyid(rel.relowner) AS relowner, rel.relhasoids, rel.relkind,
+ (CASE WHEN rel.relkind = 'p' THEN true ELSE false END) AS is_partitioned,
+ rel.relhassubclass, rel.reltuples::bigint, des.description, con.conname, con.conkey,
+ EXISTS(select 1 FROM pg_catalog.pg_trigger
+ JOIN pg_catalog.pg_proc pt ON pt.oid=tgfoid AND pt.proname='logtrigger'
+ JOIN pg_catalog.pg_proc pc ON pc.pronamespace=pt.pronamespace AND pc.proname='slonyversion'
+ WHERE tgrelid=rel.oid) AS isrepl,
+ (SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid=rel.oid AND tgisinternal = FALSE) AS triggercount,
+ (SELECT ARRAY(SELECT CASE WHEN (nspname NOT LIKE 'pg\_%') THEN
+ pg_catalog.quote_ident(nspname)||'.'||pg_catalog.quote_ident(c.relname)
+ ELSE pg_catalog.quote_ident(c.relname) END AS inherited_tables
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid ORDER BY inhseqno)) AS coll_inherits,
+ (SELECT count(*)
+ FROM pg_catalog.pg_inherits i
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhparent
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+ WHERE i.inhrelid = rel.oid) AS inherited_tables_cnt,
+ (CASE WHEN rel.relpersistence = 'u' THEN true ELSE false END) AS relpersistence,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'parallel_workers=([0-9]*)') AS parallel_workers,
+ (substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(rel.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ rel.reloptions AS reloptions, tst.reloptions AS toast_reloptions, rel.reloftype,
+ CASE WHEN typ.typname IS NOT NULL THEN (select pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace WHERE oid = {{scid}}::oid )||'.'||pg_catalog.quote_ident(typ.typname) ELSE typ.typname END AS typname,
+ typ.typrelid AS typoid, rel.relrowsecurity as rlspolicy, rel.relforcerowsecurity as forcerlspolicy,
+ (CASE WHEN rel.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=rel.oid AND sl1.objsubid=0) AS seclabels,
+ (CASE WHEN rel.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_table
+ -- Added for partition table
+ {% if tid %}, (CASE WHEN rel.relkind = 'p' THEN pg_catalog.pg_get_partkeydef({{ tid }}::oid) ELSE '' END) AS partition_scheme {% endif %}
+FROM pg_catalog.pg_class rel
+ LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=rel.reltablespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=rel.oid AND des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_constraint con ON con.conrelid=rel.oid AND con.contype='p'
+ LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = rel.reltoastrelid
+ LEFT JOIN pg_catalog.pg_type typ ON rel.reloftype=typ.oid
+WHERE rel.relkind IN ('r','s','t','p') AND rel.relnamespace = {{ scid }}::oid
+AND NOT rel.relispartition
+{% if tid %} AND rel.oid = {{ tid }}::oid {% endif %}
+ORDER BY rel.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/reset_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/reset_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4c71d9fdb73de6c524eaa13dbeb69a0000ecf30e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/reset_stats.sql
@@ -0,0 +1 @@
+SELECT pg_catalog.pg_stat_reset_single_table_counters({{tid}})
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e2b77c3838a7928766bd233d6e23cf97701c9aa8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/stats.sql
@@ -0,0 +1,53 @@
+SELECT
+ seq_scan AS {{ conn|qtIdent(_('Sequential scans')) }},
+ seq_tup_read AS {{ conn|qtIdent(_('Sequential tuples read')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ heap_blks_read AS {{ conn|qtIdent(_('Heap blocks read')) }},
+ heap_blks_hit AS {{ conn|qtIdent(_('Heap blocks hit')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ toast_blks_read AS {{ conn|qtIdent(_('Toast blocks read')) }},
+ toast_blks_hit AS {{ conn|qtIdent(_('Toast blocks hit')) }},
+ tidx_blks_read AS {{ conn|qtIdent(_('Toast index blocks read')) }},
+ tidx_blks_hit AS {{ conn|qtIdent(_('Toast index blocks hit')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ pg_catalog.pg_relation_size(stat.relid) AS {{ conn|qtIdent(_('Table size')) }},
+ CASE WHEN cl.reltoastrelid = 0 THEN NULL ELSE pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0))
+ END AS {{ conn|qtIdent(_('Toast table size')) }},
+ COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=stat.relid)::int8, 0)
+ AS {{ conn|qtIdent(_('Indexes size')) }}
+{% if is_pgstattuple %}
+{#== EXTENDED STATS ==#}
+ ,tuple_count AS {{ conn|qtIdent(_('Tuple count')) }},
+ tuple_len AS {{ conn|qtIdent(_('Tuple length')) }},
+ tuple_percent AS {{ conn|qtIdent(_('Tuple percent')) }},
+ dead_tuple_count AS {{ conn|qtIdent(_('Dead tuple count')) }},
+ dead_tuple_len AS {{ conn|qtIdent(_('Dead tuple length')) }},
+ dead_tuple_percent AS {{ conn|qtIdent(_('Dead tuple percent')) }},
+ free_space AS {{ conn|qtIdent(_('Free space')) }},
+ free_percent AS {{ conn|qtIdent(_('Free percent')) }}
+FROM
+ pgstattuple('{{schema_name}}.{{table_name}}'), pg_catalog.pg_stat_all_tables stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_tables stat
+{% endif %}
+JOIN
+ pg_catalog.pg_statio_all_tables statio ON stat.relid = statio.relid
+JOIN
+ pg_catalog.pg_class cl ON cl.oid=stat.relid
+WHERE
+ stat.relid = {{ tid }}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/truncate.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/truncate.sql
new file mode 100644
index 0000000000000000000000000000000000000000..975b14b88b8358eacfd5a4188a1c1d73ff46de93
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/truncate.sql
@@ -0,0 +1 @@
+TRUNCATE TABLE {{conn|qtIdent(data.schema, data.name)}}{% if identity %} RESTART IDENTITY{% endif %}{% if cascade %} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f1b4625a2acd90a3fac0bc92cee3485c4c4a94f9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/default/update.sql
@@ -0,0 +1,269 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{#####################################################}
+{## Rename table ##}
+{#####################################################}
+{% if data.name and data.name != o_data.name %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, o_data.name)}}
+ RENAME TO {{conn|qtIdent(data.name)}};
+
+{% endif %}
+{#####################################################}
+{## Change table schema ##}
+{#####################################################}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(o_data.schema, data.name)}}
+ SET SCHEMA {{conn|qtIdent(data.schema)}};
+
+{% endif %}
+{#####################################################}
+{## Change table owner ##}
+{#####################################################}
+{% if data.relowner and data.relowner != o_data.relowner %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ OWNER TO {{conn|qtIdent(data.relowner)}};
+
+{% endif %}
+{#####################################################}
+{## Update Inherits table definition ##}
+{#####################################################}
+{% if data.coll_inherits_added|length > 0 %}
+{% for val in data.coll_inherits_added %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{% if data.coll_inherits_removed|length > 0 %}
+{% for val in data.coll_inherits_removed %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO INHERIT {{val}};
+
+{% endfor %}
+{% endif %}
+{#####################################################}
+{## Change hasOID attribute of table ##}
+{#####################################################}
+{% if data.relhasoids is defined and data.relhasoids != o_data.relhasoids %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET {% if data.relhasoids %}WITH{% else %}WITHOUT{% endif %} OIDS;
+
+{% endif %}
+{#####################################################}
+{## Change tablespace ##}
+{#####################################################}
+{% if data.spcname and data.spcname != o_data.spcname %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET TABLESPACE {{conn|qtIdent(data.spcname)}};
+
+{% endif %}
+{#####################################################}
+{## change fillfactor settings ##}
+{#####################################################}
+{% if data.fillfactor and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ SET (FILLFACTOR={{data.fillfactor}});
+{% elif (data.fillfactor == '' or data.fillfactor == None) and data.fillfactor != o_data.fillfactor %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ RESET (FILLFACTOR);
+
+{% endif %}
+{###############################}
+{## Table AutoVacuum settings ##}
+{###############################}
+{% if data.vacuum_table is defined and data.vacuum_table.set_values|length > 0 %}
+{% set has_vacuum_set = true %}
+{% endif %}
+{% if data.vacuum_table is defined and data.vacuum_table.reset_values|length > 0 %}
+{% set has_vacuum_reset = true %}
+{% endif %}
+{% if o_data.autovacuum_custom and data.autovacuum_custom == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ autovacuum_enabled,
+ autovacuum_analyze_scale_factor,
+ autovacuum_analyze_threshold,
+ autovacuum_freeze_max_age,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_vacuum_threshold,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_table_age
+);
+{% else %}
+{% if (data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.autovacuum_enabled in ('t', 'f') and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_set %}
+{% for opt in data.vacuum_table.set_values %}{% if opt.name and opt.value is defined %}
+ {{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.autovacuum_enabled == 'x' and data.autovacuum_enabled != o_data.autovacuum_enabled) or has_vacuum_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.autovacuum_enabled =='x' and data.autovacuum_enabled != o_data.autovacuum_enabled %}
+ autovacuum_enabled{% if has_vacuum_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_reset %}
+{% for opt in data.vacuum_table.reset_values %}{% if opt.name %}
+ {{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+
+{#####################################################}
+{## Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.rlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ ENABLE ROW LEVEL SECURITY;
+{% elif data.rlspolicy is defined and data.rlspolicy != o_data.rlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ DISABLE ROW LEVEL SECURITY;
+
+{% endif %}
+
+{#####################################################}
+{## Force Enable Row Level Security Policy on table ##}
+{#####################################################}
+{% if data.forcerlspolicy %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ FORCE ROW LEVEL SECURITY;
+{% elif data.forcerlspolicy is defined and data.forcerlspolicy != o_data.forcerlspolicy%}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}}
+ NO FORCE ROW LEVEL SECURITY;
+{% endif %}
+
+{#####################################}
+{## Toast table AutoVacuum settings ##}
+{#####################################}
+{% if data.vacuum_toast is defined and data.vacuum_toast.set_values|length > 0 %}
+{% set has_vacuum_toast_set = true %}
+{% endif %}
+{% if data.vacuum_toast is defined and data.vacuum_toast.reset_values|length > 0 %}
+{% set has_vacuum_toast_reset = true %}
+{% endif %}
+{% if o_data.toast_autovacuum and data.toast_autovacuum == false %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+ toast.autovacuum_enabled,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_table_age,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_analyze_scale_factor
+);
+{% else %}
+{% if (data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_set %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} SET (
+{% if data.toast_autovacuum_enabled in ('t', 'f') and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if has_vacuum_toast_set %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_set %}
+{% for opt in data.vacuum_toast.set_values %}{% if opt.name and opt.value is defined %}
+ toast.{{opt.name}} = {{opt.value}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% if (data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled) or has_vacuum_toast_reset %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} RESET (
+{% if data.toast_autovacuum_enabled == 'x' and data.toast_autovacuum_enabled != o_data.toast_autovacuum_enabled %}
+ toast.autovacuum_enabled{% if has_vacuum_toast_reset %},
+{% endif %}
+{% endif %}
+{% if has_vacuum_toast_reset %}
+{% for opt in data.vacuum_toast.reset_values %}{% if opt.name %}
+ toast.{{opt.name}}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+);
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Change table comments ##}
+{#####################################################}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TABLE {{conn|qtIdent(data.schema, data.name)}}
+ IS {{data.description|qtLiteral(conn)}};
+
+{% endif %}
+{#####################################################}
+{## Update table Privileges ##}
+{#####################################################}
+{% if data.relacl %}
+{% if 'deleted' in data.relacl %}
+{% for priv in data.relacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.relacl %}
+{% for priv in data.relacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.relacl %}
+{% for priv in data.relacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#####################################################}
+{## Update table SecurityLabel ##}
+{#####################################################}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TABLE', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TABLE', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+
+{#####################################################}
+{## Change replica identity ##}
+{#####################################################}
+{% if data.replica_identity and data.replica_identity != o_data.replica_identity %}
+ALTER TABLE IF EXISTS {{conn|qtIdent(data.schema, data.name)}} REPLICA IDENTITY {{data.replica_identity }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/constraints.macro b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/constraints.macro
new file mode 100644
index 0000000000000000000000000000000000000000..7c3068fe98dfc433cf7f3be8b3289db85dda59be
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/constraints.macro
@@ -0,0 +1,112 @@
+{##########################}
+{# Macros for Constraints #}
+{##########################}
+{# CREATE MODE ONLY #}
+{##########################}
+{% macro PRIMARY_KEY(conn, data) -%}
+{% if data.columns|length > 0 %}
+
+ {% if data.name %}CONSTRAINT {{conn|qtIdent(data.name)}} {% endif %}PRIMARY KEY ({% for c in data.columns%}
+{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(c.column)}}{% endfor %}){% if data.include|length > 0 %}
+
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %}){% endif %}
+{% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}
+{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %} INITIALLY DEFERRED{% endif%}{% endif%}
+{% endif %}
+{%- endmacro %}
+{% macro UNIQUE(conn, unique_data) -%}
+{% for data in unique_data %}
+{% if data.columns|length > 0 %}{% if loop.index !=1 %},{% endif %}
+
+ {% if data.name %}CONSTRAINT {{conn|qtIdent(data.name)}} {% endif %}UNIQUE {% if data.indnullsnotdistinct %}NULLS NOT DISTINCT {% endif %}({% for c in data.columns%}
+{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(c.column)}}{% endfor %}){% if data.include|length > 0 %}
+
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %}){% endif %}
+{% if data.fillfactor %}
+
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}
+{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %} INITIALLY DEFERRED{% endif%}{% endif%}
+{% endif %}
+{% endfor %}
+{%- endmacro %}
+{% macro CHECK(conn, check_data) -%}
+{% for data in check_data %}{% if loop.index !=1 %},{% endif %}
+
+ {% if data.name %}CONSTRAINT {{ conn|qtIdent(data.name) }} {% endif%}CHECK ({{ data.consrc }}){% if data.convalidated %}
+ NOT VALID{% endif %}{% if data.connoinherit %} NO INHERIT{% endif %}
+{% endfor %}
+{%- endmacro %}
+{% macro FOREIGN_KEY(conn, foreign_key_data) -%}
+{% for data in foreign_key_data %}{% if loop.index != 1 %},{% endif %}
+
+ {% if data.name %}CONSTRAINT {{conn|qtIdent(data.name)}} {% endif %}FOREIGN KEY ({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
+ REFERENCES {{ conn|qtIdent(data.remote_schema, data.remote_table) }} ({% for columnobj in data.columns %}{% if loop.index != 1 %}
+, {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}) {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}
+
+ ON UPDATE{% if data.confupdtype == 'a' %}
+ NO ACTION{% elif data.confupdtype == 'r' %}
+ RESTRICT{% elif data.confupdtype == 'c' %}
+ CASCADE{% elif data.confupdtype == 'n' %}
+ SET NULL{% elif data.confupdtype == 'd' %}
+ SET DEFAULT{% endif %}
+
+ ON DELETE{% if data.confdeltype == 'a' %}
+ NO ACTION{% elif data.confdeltype == 'r' %}
+ RESTRICT{% elif data.confdeltype == 'c' %}
+ CASCADE{% elif data.confdeltype == 'n' %}
+ SET NULL{% elif data.confdeltype == 'd' %}
+ SET DEFAULT{% endif %}
+{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif%}
+{% if not data.convalidated %}
+
+ NOT VALID{% endif%}
+{% endfor %}
+{%- endmacro %}
+{% macro EXCLUDE(conn, exclude_data) -%}
+{% for data in exclude_data %}{% if loop.index != 1 %},{% endif %}
+
+ {% if data.name %}CONSTRAINT {{ conn|qtIdent(data.name) }} {% endif%}EXCLUDE {% if data.amname and data.amname != '' %}USING {{data.amname}}{% endif %} (
+ {% for col in data.columns %}{% if loop.index != 1 %},
+ {% endif %}{% if col.is_exp %}{{col.column}}{% else %}{{ conn|qtIdent(col.column)}}{% endif %}{% if col.oper_class and col.oper_class != '' %} {{col.oper_class}}{% endif%}{% if col.order is defined and col.is_sort_nulls_applicable %}{% if col.order %} ASC{% else %} DESC{% endif %} NULLS{% endif %} {% if col.nulls_order is defined and col.is_sort_nulls_applicable %}{% if col.nulls_order %}FIRST {% else %}LAST {% endif %}{% endif %}WITH {{col.operator}}{% endfor %})
+{% if data.include|length > 0 %}
+ INCLUDE({% for col in data.include %}{% if loop.index != 1 %}, {% endif %}{{conn|qtIdent(col)}}{% endfor %})
+{% endif %}{% if data.fillfactor %}
+ WITH (FILLFACTOR={{data.fillfactor}}){% endif %}{% if data.spcname and data.spcname != "pg_default" %}
+
+ USING INDEX TABLESPACE {{ conn|qtIdent(data.spcname) }}{% endif %}{% if data.indconstraint %}
+
+ WHERE ({{data.indconstraint}}){% endif%}{% if data.condeferrable %}
+
+ DEFERRABLE{% if data.condeferred %}
+ INITIALLY DEFERRED{% endif%}
+{% endif%}
+{% endfor %}
+{%- endmacro %}
+{##########################}
+{# COMMENTS ONLY #}
+{##########################}
+{% macro CONSTRAINT_COMMENTS(conn, schema, table, data) -%}
+{% for d in data %}
+{% if d.name and d.comment %}
+COMMENT ON CONSTRAINT {{ conn|qtIdent(d.name) }} ON {{ conn|qtIdent(schema, table) }}
+ IS {{ d.comment|qtLiteral(conn) }};
+{% endif %}
+{% endfor %}
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/db_catalogs.macro b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/db_catalogs.macro
new file mode 100644
index 0000000000000000000000000000000000000000..02b2718c571eda2d2eb5489bbffb07759a6d4ffd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/macros/db_catalogs.macro
@@ -0,0 +1,5 @@
+{% macro VALID_CATALOGS(server_type) -%}
+AND n.nspname NOT LIKE 'pg\_%' {% if server_type == 'ppas' %}
+AND n.nspname NOT IN ('information_schema', 'pgagent', 'sys') {% else %}
+AND n.nspname NOT IN ('information_schema') {% endif %}
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f3d7c207095a5d4e98b004ae6c0b4128c200255e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8b7a9ded01c612d9d70bdf3865a1d5ff79413b67
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/11_plus/update.sql
@@ -0,0 +1,61 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+{% if (data.tfunction is defined) %}
+ EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE FUNCTION {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fb799ca9ea66a85ffa5e8d48ba8f324419e693c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if not data.is_constraint_trigger %} OR REPLACE{% endif %}{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3b5d87b45d14dcb13b008cd07dc5c6538e4fef6b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/14_plus/update.sql
@@ -0,0 +1,61 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if not data.is_constraint_trigger %} OR REPLACE{% endif %}{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+{% if (data.tfunction is defined) %}
+ EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE FUNCTION {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/alter.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/alter.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dcfe217ed8d7e0f6a8d3c3a9eecaf613a08346cf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/alter.sql
@@ -0,0 +1,9 @@
+{## Alter index to use cluster type ##}
+{% if data.indisclustered %}
+ALTER TABLE {{conn|qtIdent(data.schema, data.table)}}
+ CLUSTER ON {{conn|qtIdent(data.name)}};
+{% endif %}
+{## Changes description ##}
+{% if data.description %}
+COMMENT ON INDEX {{conn|qtIdent(data.name)}}
+ IS {{data.description|qtLiteral(conn)}};{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b9b6b9af3e27133c51da3b2851eb00c055f2363
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is materialized view========#}
+{% if vid %}
+SELECT
+ CASE WHEN c.relkind = 'm' THEN False ELSE True END As m_view
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ vid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..74f54929e9b670f6c7886559f6395f372eb2b447
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/count.sql
@@ -0,0 +1,4 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_trigger t
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f3c877aec113cd5e2d707b12e93b31e00e3e748
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE PROCEDURE {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0a916a196e9153bbcdbbc3b7e8af03dacf05e072
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/delete.sql
@@ -0,0 +1 @@
+DROP TRIGGER IF EXISTS {{conn|qtIdent(data.name)}} ON {{conn|qtIdent(data.nspname, data.relname )}}{% if cascade %} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/enable_disable_trigger.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/enable_disable_trigger.sql
new file mode 100644
index 0000000000000000000000000000000000000000..174a37be49b20971b01c9fcab14ab8760a1fb918
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/enable_disable_trigger.sql
@@ -0,0 +1,3 @@
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(data.schema, data.table) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d9c7341147dc625a7a6e78e575ffbcc12dea7614
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_columns.sql
@@ -0,0 +1,6 @@
+SELECT att.attname as name
+FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attnum IN ({{ clist }})
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_enabled_triggers.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_enabled_triggers.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c24eda653d744b7d5041743e31743579aa2c53eb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_enabled_triggers.sql
@@ -0,0 +1 @@
+SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid={{tid}} AND tgisinternal = FALSE AND tgenabled = 'O'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_function_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_function_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8a7ae175560a8064253e455272db389c90b546db
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_function_oid.sql
@@ -0,0 +1,9 @@
+SELECT p.oid AS tfuncoid, p.proname AS tfunction,
+ p.pronamespace AS tfuncschoid, n.nspname AS tfuncschema, l.lanname
+FROM pg_catalog.pg_trigger t
+ LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
+ LEFT OUTER JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
+ LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND t.oid = {{trid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d37f4bfa558f520f1aa021226e2a384ec9cc1b2a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_oid.sql
@@ -0,0 +1,5 @@
+SELECT t.oid
+FROM pg_catalog.pg_trigger t
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgname = {{data.name|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_triggerfunctions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_triggerfunctions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6b8383b4e88406e4c13374b1c87999217bcd27d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/get_triggerfunctions.sql
@@ -0,0 +1,15 @@
+SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
+FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
+ WHERE p.pronamespace = n.oid
+ AND p.prolang = l.oid
+ -- PGOID_TYPE_TRIGGER = 2279
+ AND prorettype = 2279
+ -- If Show SystemObjects is not true
+ {% if not show_system_objects %}
+ AND (nspname NOT LIKE 'pg\_%' AND nspname NOT in ('information_schema'))
+ {% endif %}
+ -- Find function for specific OID
+ {% if tgfoid %}
+ AND p.oid = {{tgfoid}}::OID
+ {% endif %}
+ ORDER BY nspname ASC, proname ASC
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..183ff742c3ce2963fc60a75dfac31a56e7587d0c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/nodes.sql
@@ -0,0 +1,13 @@
+SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger, des.description
+FROM pg_catalog.pg_trigger t
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..48dbeffc14c3527dc70ce397dbb35749ade859dc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/properties.sql
@@ -0,0 +1,24 @@
+SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
+ nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
+ COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
+ pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) \$trigger')) AS whenclause,
+ -- We need to convert tgargs column bytea datatype to array datatype
+ (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
+{% if datlastsysoid %}
+ (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
+{% endif %}
+ (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
+ tgoldtable,
+ tgnewtable
+FROM pg_catalog.pg_trigger t
+ JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
+ JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
+ LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4cb6af00562657526319665707ebea1870423158
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/pg/default/update.sql
@@ -0,0 +1,61 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+{% if (data.tfunction is defined) %}
+ EXECUTE PROCEDURE {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE PROCEDURE {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f3d7c207095a5d4e98b004ae6c0b4128c200255e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e6b1d862448e37865acc85d2abb38be4b9783821
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/11_plus/update.sql
@@ -0,0 +1,70 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+
+{%if data.tfunction == 'Inline EDB-SPL' %}
+{% if (data.prosrc is not defined) %}
+{{ o_data.prosrc }};
+{% else %}
+{{ data.prosrc }};
+{% endif %}
+{% else %}
+{% if (data.tfunction is defined) %}
+ EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE FUNCTION {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b17aaf7cb02bf46a1c6b0eaea9cbc24f862b5b95
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/count.sql
@@ -0,0 +1,5 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_trigger t
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid = 0
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..700da637f64e7118bcfae757c37f28ca16c229aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/nodes.sql
@@ -0,0 +1,14 @@
+SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger, des.description
+FROM pg_catalog.pg_trigger t
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid = 0
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0631151ef1888558da4af91829b280a6d9b7bbf5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/12_plus/properties.sql
@@ -0,0 +1,25 @@
+SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
+ nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
+ COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
+ pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) \$trigger')) AS whenclause,
+ -- We need to convert tgargs column bytea datatype to array datatype
+ (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
+{% if datlastsysoid %}
+ (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
+{% endif %}
+ (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
+ tgoldtable,
+ tgnewtable
+FROM pg_catalog.pg_trigger t
+ JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
+ JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
+ LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgpackageoid = 0
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fb799ca9ea66a85ffa5e8d48ba8f324419e693c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if not data.is_constraint_trigger %} OR REPLACE{% endif %}{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0cfd77793995590900871fce6310c640e16d965a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/14_plus/update.sql
@@ -0,0 +1,70 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if not data.is_constraint_trigger %} OR REPLACE{% endif %}{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+
+{%if data.tfunction == 'Inline EDB-SPL' %}
+{% if (data.prosrc is not defined) %}
+{{ o_data.prosrc }};
+{% else %}
+{{ data.prosrc }};
+{% endif %}
+{% else %}
+{% if (data.tfunction is defined) %}
+ EXECUTE FUNCTION {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE FUNCTION {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/alter.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/alter.sql
new file mode 100644
index 0000000000000000000000000000000000000000..dcfe217ed8d7e0f6a8d3c3a9eecaf613a08346cf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/alter.sql
@@ -0,0 +1,9 @@
+{## Alter index to use cluster type ##}
+{% if data.indisclustered %}
+ALTER TABLE {{conn|qtIdent(data.schema, data.table)}}
+ CLUSTER ON {{conn|qtIdent(data.name)}};
+{% endif %}
+{## Changes description ##}
+{% if data.description %}
+COMMENT ON INDEX {{conn|qtIdent(data.name)}}
+ IS {{data.description|qtLiteral(conn)}};{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/backend_support.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/backend_support.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b9b6b9af3e27133c51da3b2851eb00c055f2363
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/backend_support.sql
@@ -0,0 +1,9 @@
+{#=============Checks if it is materialized view========#}
+{% if vid %}
+SELECT
+ CASE WHEN c.relkind = 'm' THEN False ELSE True END As m_view
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{ vid }}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..74f54929e9b670f6c7886559f6395f372eb2b447
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/count.sql
@@ -0,0 +1,4 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_trigger t
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f3c877aec113cd5e2d707b12e93b31e00e3e748
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/create.sql
@@ -0,0 +1,37 @@
+{### Set a flag which allows us to put OR between events ###}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {{data.fires}} {% if data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}
+{% if data.tgoldtable or data.tgnewtable %}
+ REFERENCING{% if data.tgnewtable %} NEW TABLE AS {{ conn|qtIdent(data.tgnewtable) }}{% endif %}{% if data.tgoldtable %} OLD TABLE AS {{ conn|qtIdent(data.tgoldtable) }}{% endif %}
+
+{% endif %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %}
+{% if data.whenclause %}
+
+ WHEN {% if not data.oid %}({% endif %}{{ data.whenclause }}{% if not data.oid %}){% endif %}{% endif %}
+
+ {% if data.prosrc is defined and
+ (data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL') %}{{ data.prosrc }}{% else %}EXECUTE PROCEDURE {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%}{% endif%};
+
+{% if data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(data.schema, data.table) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0a916a196e9153bbcdbbc3b7e8af03dacf05e072
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/delete.sql
@@ -0,0 +1 @@
+DROP TRIGGER IF EXISTS {{conn|qtIdent(data.name)}} ON {{conn|qtIdent(data.nspname, data.relname )}}{% if cascade %} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/enable_disable_trigger.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/enable_disable_trigger.sql
new file mode 100644
index 0000000000000000000000000000000000000000..174a37be49b20971b01c9fcab14ab8760a1fb918
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/enable_disable_trigger.sql
@@ -0,0 +1,3 @@
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(data.schema, data.table) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_columns.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_columns.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d9c7341147dc625a7a6e78e575ffbcc12dea7614
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_columns.sql
@@ -0,0 +1,6 @@
+SELECT att.attname as name
+FROM pg_catalog.pg_attribute att
+ WHERE att.attrelid = {{tid}}::oid
+ AND att.attnum IN ({{ clist }})
+ AND att.attisdropped IS FALSE
+ ORDER BY att.attnum
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_enabled_triggers.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_enabled_triggers.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c24eda653d744b7d5041743e31743579aa2c53eb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_enabled_triggers.sql
@@ -0,0 +1 @@
+SELECT count(*) FROM pg_catalog.pg_trigger WHERE tgrelid={{tid}} AND tgisinternal = FALSE AND tgenabled = 'O'
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_function_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_function_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8a7ae175560a8064253e455272db389c90b546db
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_function_oid.sql
@@ -0,0 +1,9 @@
+SELECT p.oid AS tfuncoid, p.proname AS tfunction,
+ p.pronamespace AS tfuncschoid, n.nspname AS tfuncschema, l.lanname
+FROM pg_catalog.pg_trigger t
+ LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
+ LEFT OUTER JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
+ LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND t.oid = {{trid}}::OID
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d37f4bfa558f520f1aa021226e2a384ec9cc1b2a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_oid.sql
@@ -0,0 +1,5 @@
+SELECT t.oid
+FROM pg_catalog.pg_trigger t
+ WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+ AND tgname = {{data.name|qtLiteral(conn)}};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_parent.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_parent.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0c46d743c50416d2600211941391a26eca39db30
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_parent.sql
@@ -0,0 +1,5 @@
+SELECT nsp.nspname AS schema ,rel.relname AS table
+FROM pg_catalog.pg_class rel
+ JOIN pg_catalog.pg_namespace nsp
+ ON rel.relnamespace = nsp.oid::oid
+ WHERE rel.oid = {{tid}}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_triggerfunctions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_triggerfunctions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6b8383b4e88406e4c13374b1c87999217bcd27d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/get_triggerfunctions.sql
@@ -0,0 +1,15 @@
+SELECT pg_catalog.quote_ident(nspname) || '.' || pg_catalog.quote_ident(proname) AS tfunctions
+FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_language l
+ WHERE p.pronamespace = n.oid
+ AND p.prolang = l.oid
+ -- PGOID_TYPE_TRIGGER = 2279
+ AND prorettype = 2279
+ -- If Show SystemObjects is not true
+ {% if not show_system_objects %}
+ AND (nspname NOT LIKE 'pg\_%' AND nspname NOT in ('information_schema'))
+ {% endif %}
+ -- Find function for specific OID
+ {% if tgfoid %}
+ AND p.oid = {{tgfoid}}::OID
+ {% endif %}
+ ORDER BY nspname ASC, proname ASC
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..183ff742c3ce2963fc60a75dfac31a56e7587d0c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/nodes.sql
@@ -0,0 +1,13 @@
+SELECT t.oid, t.tgname as name, t.tgenabled AS is_enable_trigger, des.description
+FROM pg_catalog.pg_trigger t
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..48dbeffc14c3527dc70ce397dbb35749ade859dc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/properties.sql
@@ -0,0 +1,24 @@
+SELECT t.oid,t.tgname AS name, t.xmin, t.tgenabled AS is_enable_trigger, t.*, relname, CASE WHEN relkind = 'r' THEN TRUE ELSE FALSE END AS parentistable,
+ nspname, des.description, l.lanname, p.prosrc, p.proname AS tfunction,
+ COALESCE(pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) EXECUTE (PROCEDURE|FUNCTION)'),
+ pg_catalog.substring(pg_catalog.pg_get_triggerdef(t.oid, true), 'WHEN (.*) \$trigger')) AS whenclause,
+ -- We need to convert tgargs column bytea datatype to array datatype
+ (pg_catalog.string_to_array(encode(tgargs, 'escape'), E'\\000')::text[])[1:tgnargs] AS custom_tgargs,
+{% if datlastsysoid %}
+ (CASE WHEN t.oid <= {{ datlastsysoid}}::oid THEN true ElSE false END) AS is_sys_trigger,
+{% endif %}
+ (CASE WHEN tgconstraint != 0::OID THEN true ElSE false END) AS is_constraint_trigger,
+ tgoldtable,
+ tgnewtable
+FROM pg_catalog.pg_trigger t
+ JOIN pg_catalog.pg_class cl ON cl.oid=tgrelid
+ JOIN pg_catalog.pg_namespace na ON na.oid=relnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_trigger'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_proc p ON p.oid=t.tgfoid
+ LEFT OUTER JOIN pg_catalog.pg_language l ON l.oid=p.prolang
+WHERE NOT tgisinternal
+ AND tgrelid = {{tid}}::OID
+{% if trid %}
+ AND t.oid = {{trid}}::OID
+{% endif %}
+ORDER BY tgname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6341cc0c667f1750dfd6f9730d79ff478e538375
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/triggers/sql/ppas/default/update.sql
@@ -0,0 +1,70 @@
+{% if data.name and o_data.name != data.name %}
+ALTER TRIGGER {{ conn|qtIdent(o_data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{% if ((data.prosrc is defined or data.is_row_trigger is defined or data.evnt_insert is defined or data.evnt_delete is defined or data.evnt_update is defined or data.fires is defined or data.is_constraint_trigger is defined or data.whenclause is defined) and (o_data.prosrc != data.prosrc or data.is_row_trigger != o_data.is_row_trigger or data.evnt_insert != o_data.evnt_insert or data.evnt_delete != o_data.evnt_delete or data.evnt_update != o_data.evnt_update or o_data.fires != data.fires or data.is_constraint_trigger != o_data.is_constraint_trigger or data.whenclause != o_data.whenclause)) %}
+{% set or_flag = False %}
+{% if data.lanname == 'edbspl' or data.tfunction == 'Inline EDB-SPL' %}
+CREATE OR REPLACE TRIGGER {{ conn|qtIdent(data.name) }}
+{% else %}
+CREATE{% if data.is_constraint_trigger %} CONSTRAINT{% endif %} TRIGGER {{ conn|qtIdent(data.name) }}
+{% endif %}
+ {% if data.fires is defined %}{{data.fires}} {% else %}{{o_data.fires}} {% endif %}{% if data.evnt_insert is not defined %}{% if o_data.evnt_insert %}INSERT{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_insert %}INSERT{% set or_flag = True %}{% endif %}{% endif %}{% if data.evnt_delete is not defined %}{% if o_data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_delete %}
+{% if or_flag %} OR {% endif %}DELETE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_truncate is not defined %}{% if o_data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}
+{% endif %}{% else %}{% if data.evnt_truncate %}
+{% if or_flag %} OR {% endif %}TRUNCATE{% set or_flag = True %}{%endif %}{% endif %}{% if data.evnt_update is not defined %}{% if o_data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if o_data.columns|length > 0 %}OF {% for c in o_data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}
+{% endif %}{% else %}{% if data.evnt_update %}
+{% if or_flag %} OR {% endif %}UPDATE {% if data.columns|length > 0 %}OF {% for c in data.columns %}{% if loop.index != 1 %}, {% endif %}{{ conn|qtIdent(c) }}{% endfor %}{% endif %}{% endif %}
+{% endif %}
+
+ ON {{ conn|qtIdent(data.schema, data.table) }}
+{% if data.tgdeferrable %}
+ DEFERRABLE{% if data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% elif o_data.tgdeferrable %}
+ DEFERRABLE{% if o_data.tginitdeferred %} INITIALLY DEFERRED{% endif %}
+
+{% endif %}{% if data.is_row_trigger is not defined %}
+ FOR EACH{% if o_data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% else %}
+ FOR EACH{% if data.is_row_trigger %} ROW{% else %} STATEMENT{% endif %} {% endif %}
+
+{% if data.whenclause %}
+ WHEN {{ data.whenclause }}
+{% elif o_data.whenclause %}
+ WHEN {{ o_data.whenclause }}
+{% endif %}
+
+{%if data.tfunction == 'Inline EDB-SPL' %}
+{% if (data.prosrc is not defined) %}
+{{ o_data.prosrc }};
+{% else %}
+{{ data.prosrc }};
+{% endif %}
+{% else %}
+{% if (data.tfunction is defined) %}
+ EXECUTE PROCEDURE {{ data.tfunction }}{% if data.tgargs %}({{ data.tgargs }}){% else %}(){% endif%};
+{% else %}
+ EXECUTE PROCEDURE {{ o_data.tfunction }}{% if o_data.tgargs %}({{ o_data.tgargs }}){% else %}(){% endif%};
+{% endif %}
+{% endif %}
+
+{% if data.description is not defined and o_data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{o_data.description|qtLiteral(conn)}};
+{% endif %}
+{% endif %}
+{% if data.description is defined and o_data.description != data.description %}
+COMMENT ON TRIGGER {{ conn|qtIdent(data.name) }} ON {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{% if data.is_enable_trigger is defined and o_data.is_enable_trigger != data.is_enable_trigger %}
+{% set enable_map = {'R':'ENABLE REPLICA', 'A':'ENABLE ALWAYS', 'O':'ENABLE', 'D':'DISABLE'} %}
+ALTER TABLE {{ conn|qtIdent(o_data.nspname, o_data.relname) }}
+ {{ enable_map[data.is_enable_trigger] }} TRIGGER {{ conn|qtIdent(data.name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..49dfde1cbf8cb6a0225e35ac85b6668449a16ab7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/__init__.py
@@ -0,0 +1,1102 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Trigger Node """
+
+import json
+from functools import wraps
+
+import pgadmin.browser.server_groups.servers.databases as database
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext
+from pgadmin.browser.collection import CollectionNodeModule
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ triggers import utils as trigger_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.directory_compare import directory_diff,\
+ parse_acl
+
+
+class TriggerModule(CollectionNodeModule):
+ """
+ class TriggerModule(CollectionNodeModule)
+
+ A module class for Trigger node derived from CollectionNodeModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Trigger and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for trigger, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'trigger'
+ _COLLECTION_LABEL = gettext("Triggers")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the TriggerModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ self.min_ver = None
+ self.max_ver = None
+ super().__init__(*args, **kwargs)
+
+ def backend_supported(self, manager, **kwargs):
+ """
+ Load this module if vid is view, we will not load it under
+ material view
+ """
+ if super().backend_supported(manager, **kwargs):
+ conn = manager.connection(did=kwargs['did'])
+
+ if 'vid' not in kwargs:
+ return True
+
+ template_path = 'triggers/sql/{0}/#{1}#'.format(
+ manager.server_type, manager.version)
+ SQL = render_template("/".join(
+ [template_path, 'backend_support.sql']), vid=kwargs['vid']
+ )
+
+ status, res = conn.execute_scalar(SQL)
+
+ # check if any errors
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Check vid is view not material view
+ # then true, othewise false
+ return res
+
+ def get_nodes(self, gid, sid, did, scid, **kwargs):
+ """
+ Generate the collection node
+ """
+ assert ('tid' in kwargs or 'vid' in kwargs or 'foid' in kwargs)
+ tid = kwargs.get('tid', kwargs.get('vid', kwargs.get('foid', None)))
+ if self.has_nodes(sid, did, scid=scid,
+ tid=tid,
+ base_template_path=TriggerView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(
+ tid
+ )
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for server, when any of the server-group node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return True
+
+ @property
+ def module_use_template_javascript(self):
+ """
+ Returns whether Jinja2 template is used for generating the javascript
+ module.
+ """
+ return False
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ "triggers/css/trigger.css",
+ node_type=self.node_type
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+
+blueprint = TriggerModule(__name__)
+
+
+class TriggerView(PGChildNodeView, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Trigger node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the TriggerView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Trigger nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Trigger node.
+
+ * node()
+ - This function will used to create child node within that
+ collection, Here it will create specific the Trigger node.
+
+ * properties(gid, sid, did, scid, tid, trid)
+ - This function will show the properties of the selected Trigger node
+
+ * create(gid, sid, did, scid, tid)
+ - This function will create the new Trigger object
+
+ * update(gid, sid, did, scid, tid, trid)
+ - This function will update the data for the selected Trigger node
+
+ * delete(self, gid, sid, scid, tid, trid):
+ - This function will drop the Trigger object
+
+ * enable(self, gid, sid, scid, tid, trid):
+ - This function will enable/disable Trigger object
+
+ * msql(gid, sid, did, scid, tid, trid)
+ - This function is used to return modified SQL for the selected
+ Trigger node
+
+ * sql(gid, sid, did, scid, tid, trid):
+ - This function will generate sql to show it in sql pane for the
+ selected Trigger node.
+
+ * dependency(gid, sid, did, scid, tid, trid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Trigger node.
+
+ * dependent(gid, sid, did, scid, tid, trid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Trigger node.
+
+ * get_trigger_functions(gid, sid, did, scid, tid, trid):
+ - This function will return list of trigger functions available
+ via AJAX response
+ """
+
+ node_type = blueprint.node_type
+ node_label = "Trigger"
+ BASE_TEMPLATE_PATH = 'triggers/sql/{0}/#{1}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'},
+ {'type': 'int', 'id': 'tid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'trid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_triggerfunctions': [{'get': 'get_trigger_functions'},
+ {'get': 'get_trigger_functions'}],
+ 'enable': [{'put': 'enable_disable_trigger'}]
+ })
+
+ # Schema Diff: Keys to ignore while comparing
+ keys_to_ignore = ['oid', 'xmin', 'nspname', 'tgrelid', 'tgfoid', 'oid-2']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ # we will set template path for sql scripts
+ self.table_template_path = compile_template_path(
+ 'tables/sql',
+ self.manager.version
+ )
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.server_type, self.manager.version)
+
+ self.trigger_function_template_path = \
+ 'trigger_functions/{0}/sql/#{1}#'.format(
+ self.manager.server_type, self.manager.version)
+
+ # Store server type
+ self.server_type = self.manager.server_type
+ # We need parent's name eg table name and schema name
+ # when we create new trigger in update we can fetch it using
+ # property sql
+ schema, table = trigger_utils.get_parent(self.conn, kwargs['tid'])
+ self.schema = schema
+ self.table = table
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def get_children_nodes(self, manager, **kwargs):
+ """
+ Function is used to get the child nodes.
+ :param manager:
+ :param kwargs:
+ :return:
+ """
+ nodes = []
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ trid = kwargs.get('trid')
+
+ try:
+ SQL = render_template(
+ "/".join([self.template_path, 'get_function_oid.sql']),
+ tid=tid, trid=trid
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(
+ gettext("Could not find the specified trigger function"))
+
+ trigger_function_schema_oid = rset['rows'][0]['tfuncschoid']
+
+ sql = render_template("/".join(
+ [self.trigger_function_template_path, self._NODE_SQL]),
+ scid=trigger_function_schema_oid,
+ fnid=rset['rows'][0]['tfuncoid']
+ )
+ status, res = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(res['rows']) == 0:
+ return gone(gettext(
+ "Could not find the specified trigger function"))
+
+ row = res['rows'][0]
+ func_name = row['name']
+ # If trigger function is from another schema then we should
+ # display the name as schema qulified name.
+ if scid != trigger_function_schema_oid:
+ func_name = \
+ rset['rows'][0]['tfuncschema'] + '.' + row['name']
+
+ trigger_func = current_app.blueprints['NODE-trigger_function']
+ nodes.append(trigger_func.generate_browser_node(
+ row['oid'], trigger_function_schema_oid,
+ gettext(func_name),
+ icon="icon-trigger_function", funcowner=row['funcowner'],
+ language=row['lanname'], inode=False)
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ return nodes
+
+ @check_precondition
+ def get_trigger_functions(self, gid, sid, did, scid, tid, trid=None):
+ """
+ This function will return list of trigger functions available
+ via AJAX response
+ """
+ res = [{'label': '', 'value': ''}]
+
+ # If server type is EDB-PPAS then we also need to add
+ # inline edb-spl along with options fetched by below sql
+
+ if self.server_type == 'ppas':
+ res.append({
+ 'label': 'Inline EDB-SPL',
+ 'value': 'Inline EDB-SPL'
+ })
+ try:
+ SQL = render_template(
+ "/".join([self.template_path, 'get_triggerfunctions.sql']),
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['tfunctions'],
+ 'value': row['tfunctions']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def list(self, gid, sid, did, scid, tid):
+ """
+ This function is used to list all the trigger nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available trigger nodes
+ """
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]), tid=tid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will used to create the child node within that
+ collection.
+ Here it will create specific the trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ Returns:
+ JSON of available trigger child nodes
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ tid=tid,
+ trid=trid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ tid,
+ rset['rows'][0]['name'],
+ icon="icon-trigger-bad" if
+ rset['rows'][0]['is_enable_trigger'] == 'D' else "icon-trigger"
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid, tid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of available trigger child nodes
+ """
+ res = []
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ tid,
+ row['name'],
+ icon="icon-trigger-bad" if row['is_enable_trigger'] == 'D'
+ else "icon-trigger",
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will show the properties of the selected trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ Returns:
+ JSON of selected trigger node
+ """
+ status, data = self._fetch_properties(tid, trid)
+ if not status:
+ return data
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ def _fetch_properties(self, tid, trid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param tid:
+ :param trid:
+ :return:
+ """
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+ data = trigger_utils.get_trigger_function_and_columns(
+ self.conn, data, tid, self.blueprint.show_system_objects)
+
+ data = trigger_definition(data)
+
+ return True, data
+
+ @check_precondition
+ def create(self, gid, sid, did, scid, tid):
+ """
+ This function will creates new the trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ for k, v in data.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except (ValueError, TypeError, KeyError):
+ data[k] = v
+
+ required_args = {
+ 'name': 'Name',
+ 'tfunction': 'Trigger function'
+ }
+
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(required_args[arg])
+ )
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+ if len(data['table']) == 0:
+ return gone(self.not_found_error_msg())
+
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # we need oid to add object in tree at browser
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ tid=tid, data=data, conn=self.conn)
+ status, trid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ trid,
+ tid,
+ data['name'],
+ icon="icon-trigger"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will updates the existing trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ trid = kwargs.get('trid', None)
+ only_sql = kwargs.get('only_sql', False)
+
+ if trid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [trid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for trid in data['ids']:
+ # We will first fetch the trigger name for current request
+ # so that we create template for dropping trigger
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ elif not res['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ data = dict(res['rows'][0])
+
+ SQL = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ conn=self.conn,
+ cascade=cascade
+ )
+ if only_sql:
+ return SQL
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Trigger is dropped")
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will updates the existing trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ try:
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ SQL, name = trigger_utils.get_sql(
+ self.conn, data=data, tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects)
+
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # We need oid to add object in browser tree and if user
+ # update the trigger then new OID is getting generated
+ # so we need to return new OID of trigger.
+ SQL = render_template(
+ "/".join([self.template_path, self._OID_SQL]),
+ tid=tid, data=data, conn=self.conn
+ )
+ status, new_trid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=new_trid)
+ # Fetch updated properties
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=new_trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ new_trid,
+ tid,
+ name,
+ icon="icon-%s-bad" % self.node_type if
+ data['is_enable_trigger'] == 'D' else
+ "icon-%s" % self.node_type,
+ description=data['description']
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid, trid=None):
+ """
+ This function will generates modified sql for trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID (When working with existing trigger)
+ """
+ data = dict()
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('description',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = self.schema
+ data['table'] = self.table
+
+ try:
+ sql, _ = trigger_utils.get_sql(
+ self.conn, data=data, tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects)
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will generates reverse engineered sql for trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+
+ SQL = trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=self.schema, table=self.table, tid=tid,
+ trid=trid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects)
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ SQL, _ = trigger_utils.get_sql(
+ self.conn, data=data, tid=tid, trid=oid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects,
+ is_schema_diff=True)
+
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ else:
+ if drop_sql:
+ SQL = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, tid=tid, trid=oid,
+ only_sql=True)
+ else:
+ schema = self.schema
+ if target_schema:
+ schema = target_schema
+
+ SQL = trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=self.table, tid=tid,
+ trid=oid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects,
+ template_path=None, with_header=False)
+
+ return SQL
+
+ @check_precondition
+ def enable_disable_trigger(self, gid, sid, did, scid, tid, trid):
+ """
+ This function will enable OR disable the current trigger object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ is_enable_trigger = data['is_enable_trigger']
+
+ try:
+
+ SQL = render_template("/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid, trid=trid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ o_data = dict(res['rows'][0])
+
+ # If enable is set to true means we need SQL to enable
+ # current trigger which is disabled already so we need to
+ # alter the 'is_enable_trigger' flag so that we can render
+ # correct SQL for operation
+ o_data['is_enable_trigger'] = is_enable_trigger
+
+ # Adding parent into data dict, will be using it while creating sql
+ o_data['schema'] = self.schema
+ o_data['table'] = self.table
+
+ SQL = render_template("/".join([self.template_path,
+ 'enable_disable_trigger.sql']),
+ data=o_data, conn=self.conn)
+ status, res = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template(
+ "/".join([
+ self.template_path, 'get_enabled_triggers.sql'
+ ]),
+ tid=tid
+ )
+
+ status, trigger_res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info="Trigger updated",
+ data={
+ 'id': trid,
+ 'tid': tid,
+ 'scid': scid,
+ 'has_enable_triggers': trigger_res
+ }
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid, trid):
+ """
+ This function get the dependents and return ajax response
+ for the trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, trid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid, trid):
+ """
+ This function get the dependencies and return ajax response
+ for the trigger node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ trid: Trigger ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, trid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, tid, oid=None):
+ """
+ This function will fetch the list of all the triggers for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :return:
+ """
+ res = dict()
+
+ if oid:
+ status, data = self._fetch_properties(tid, oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+ res = data
+ else:
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]), tid=tid,
+ schema_diff=True)
+ status, triggers = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(triggers)
+ return False
+
+ for row in triggers['rows']:
+ status, data = self._fetch_properties(tid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function returns the DDL/DML statements based on the
+ comparison status.
+
+ :param kwargs:
+ :return:
+ """
+
+ src_params = kwargs.get('source_params')
+ tgt_params = kwargs.get('target_params')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ target_schema = kwargs.get('target_schema')
+ comp_status = kwargs.get('comp_status')
+
+ diff = ''
+ if comp_status == 'source_only':
+ diff = self.get_sql_from_diff(gid=src_params['gid'],
+ sid=src_params['sid'],
+ did=src_params['did'],
+ scid=src_params['scid'],
+ tid=src_params['tid'],
+ oid=source['oid'],
+ target_schema=target_schema)
+ elif comp_status == 'target_only':
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ drop_sql=True)
+ elif comp_status == 'different':
+ diff_dict = directory_diff(
+ source, target,
+ ignore_keys=self.keys_to_ignore, difference={}
+ )
+ parse_acl(source, target, diff_dict)
+
+ diff = self.get_sql_from_diff(gid=tgt_params['gid'],
+ sid=tgt_params['sid'],
+ did=tgt_params['did'],
+ scid=tgt_params['scid'],
+ tid=tgt_params['tid'],
+ oid=target['oid'],
+ data=diff_dict)
+ return diff
+
+
+SchemaDiffRegistry(blueprint.node_type, TriggerView, 'table')
+TriggerView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/coll-trigger.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/coll-trigger.svg
new file mode 100644
index 0000000000000000000000000000000000000000..4c391e5553159e76f1105f79257f7532d8fd0216
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/coll-trigger.svg
@@ -0,0 +1 @@
+trigger
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger-bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger-bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..f3e50fd0322f590d677b0d372ddf94990ef21d78
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger-bad.svg
@@ -0,0 +1 @@
+trigger-bad
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger.svg
new file mode 100644
index 0000000000000000000000000000000000000000..be9c8ea70502e79fcb7a44abec495d1bd3ac0da2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/img/trigger.svg
@@ -0,0 +1 @@
+coll-trigger
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.js
new file mode 100644
index 0000000000000000000000000000000000000000..34df1df1ebf10d0c0da26be57744230bb08b3954
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.js
@@ -0,0 +1,202 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import { getNodeListByName, getNodeAjaxOptions } from '../../../../../../../../static/js/node_ajax';
+import TriggerSchema from './trigger.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.trigger', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, SchemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-trigger']) {
+ pgAdmin.Browser.Nodes['coll-trigger'] =
+ pgAdmin.Browser.Collection.extend({
+ node: 'trigger',
+ label: gettext('Triggers'),
+ type: 'coll-trigger',
+ columns: ['name', 'description'],
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['trigger']) {
+ pgAdmin.Browser.Nodes['trigger'] = pgBrowser.Node.extend({
+ parent_type: ['table', 'view', 'partition', 'foreign_table'],
+ collection_type: ['coll-table', 'coll-view','coll-foreign_table'],
+ type: 'trigger',
+ label: gettext('Trigger'),
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.sm + 'px',
+ sqlAlterHelp: 'sql-altertrigger.html',
+ sqlCreateHelp: 'sql-createtrigger.html',
+ dialogHelp: url_for('help.static', {'filename': 'trigger_dialog.html'}),
+ url_jump_after_node: 'schema',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_trigger_on_coll', node: 'coll-trigger', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_trigger', node: 'trigger', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_trigger_onTable', node: 'table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_trigger_onPartition', node: 'partition', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'enable_trigger', node: 'trigger', module: this,
+ applies: ['object', 'context'], callback: 'enable_trigger',
+ category: 'connect', priority: 3, label: gettext('Enable'),
+ enable : 'canCreate_with_trigger_enable',
+ },{
+ name: 'disable_trigger', node: 'trigger', module: this,
+ applies: ['object', 'context'], callback: 'disable_trigger',
+ category: 'drop', priority: 3, label: gettext('Disable'),
+ enable : 'canCreate_with_trigger_disable',
+ },{
+ name: 'create_trigger_onView', node: 'view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_trigger_onForeignTable', node: 'foreign_table', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 3, label: gettext('Trigger...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ }
+ ]);
+ },
+ callbacks: {
+ /* Enable trigger */
+ enable_trigger: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'enable' , d, true), {'is_enable_trigger' : 'O'})
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = 'icon-trigger';
+ data.has_enable_triggers = res.data.has_enable_triggers;
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ /* Disable trigger */
+ disable_trigger: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (!d)
+ return false;
+
+ let data = d;
+ getApiInstance().put(obj.generate_url(i, 'enable' , d, true), {'is_enable_trigger' : 'D'})
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.icon = 'icon-trigger-bad';
+ data.has_enable_triggers = res.data.has_enable_triggers;
+ t.addIcon(i, {icon: data.icon});
+ t.updateAndReselectNode(i, data);
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.refresh(i);
+ });
+ },
+ },
+ canDrop: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new TriggerSchema(
+ {
+ triggerFunction: ()=>getNodeAjaxOptions('get_triggerfunctions', this, treeNodeInfo, itemNodeData, {cacheLevel: 'trigger_function', jumpAfterNode: 'schema'}, (data) => {
+ return _.reject(data, function(option) {
+ return option.label == '';
+ });
+ }),
+ columns: ()=> getNodeListByName('column', treeNodeInfo, itemNodeData, { cacheLevel: 'column'}),
+ nodeInfo: treeNodeInfo
+ },
+ );
+ },
+ canCreate: SchemaChildTreeNode.isTreeItemOfChildOfSchema,
+ // Check to whether trigger is disable ?
+ canCreate_with_trigger_enable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-trigger-bad' &&
+ this.canCreate(itemData, item, data);
+ },
+ // Check to whether trigger is enable ?
+ canCreate_with_trigger_disable: function(itemData, item, data) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item);
+ if ('view' in treeData) {
+ return false;
+ }
+
+ return itemData.icon === 'icon-trigger' &&
+ this.canCreate(itemData, item, data);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['trigger'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..42db0b0a2963f6223da73c4d9b2ac5af201d6972
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/static/js/trigger.ui.js
@@ -0,0 +1,477 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { isEmptyString } from 'sources/validators';
+
+export class EventSchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ evnt_update: false,
+ evnt_insert: false,
+ evnt_delete: false,
+ evnt_truncate: false,
+ is_row_trigger: false,
+ is_constraint_trigger: false,
+ ...initValues,
+ });
+
+ this.fieldOptions = {
+ nodeInfo: null,
+ ...fieldOptions,
+ };
+
+ this.nodeInfo = this.fieldOptions.nodeInfo;
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ inSchemaWithModelCheck(state) {
+ // Check if we are under schema node & in 'create' mode
+ if(this.nodeInfo && 'schema' in this.nodeInfo) {
+ // We will disable control if it's in 'edit' mode
+ return !this.isNew(state);
+ }
+ return true;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'evnt_insert', label: gettext('INSERT'),
+ type: 'switch', mode: ['create','edit', 'properties'],
+ group: gettext('Events'),
+ readonly: (state) => {
+ let evn_insert = state.evnt_insert;
+ if (!_.isUndefined(evn_insert) && obj.nodeInfo && obj.nodeInfo.server.server_type == 'ppas' && obj.isNew(state))
+ return false;
+ return obj.inSchemaWithModelCheck(state);
+ },
+ },{
+ id: 'evnt_update', label: gettext('UPDATE'),
+ type: 'switch', mode: ['create','edit', 'properties'],
+ group: gettext('Events'),
+ readonly: (state) => {
+ let evn_update = state.evnt_update;
+ if (!_.isUndefined(evn_update) && obj.nodeInfo && obj.nodeInfo.server.server_type == 'ppas' && obj.isNew(state))
+ return false;
+ return obj.inSchemaWithModelCheck(state);
+ },
+ },{
+ id: 'evnt_delete', label: gettext('DELETE'),
+ type: 'switch', mode: ['create','edit', 'properties'],
+ group: gettext('Events'),
+ readonly: (state) => {
+ let evn_delete = state.evnt_delete;
+ if (!_.isUndefined(evn_delete) && obj.nodeInfo && obj.nodeInfo.server.server_type == 'ppas' && obj.isNew(state))
+ return false;
+ return obj.inSchemaWithModelCheck(state);
+ },
+ },{
+ id: 'evnt_truncate', label: gettext('TRUNCATE'),
+ type: 'switch', group: gettext('Events'), deps: ['is_row_trigger', 'is_constraint_trigger'],
+ readonly: (state) => {
+ let is_constraint_trigger = state.is_constraint_trigger,
+ is_row_trigger = state.is_row_trigger,
+ server_type = obj.nodeInfo ? obj.nodeInfo.server.server_type: null;
+ if (is_row_trigger){
+ state.evnt_truncate = false;
+ return true;
+ }
+
+ if (server_type === 'ppas' && !_.isUndefined(is_constraint_trigger) &&
+ !_.isUndefined(is_row_trigger) &&
+ is_constraint_trigger === false && obj.isNew(state))
+ return false;
+
+ return obj.inSchemaWithModelCheck(state);
+ },
+ }];
+ }
+
+ validate(state, setError) {
+
+ if (isEmptyString(state.service)) {
+ let errmsg = null;
+ /* events validation*/
+ if (state.tfunction && !state.evnt_truncate && !state.evnt_delete && !state.evnt_update && !state.evnt_insert) {
+ errmsg = gettext('Specify at least one event.');
+ setError('evnt_insert', errmsg);
+ return true;
+ } else {
+ setError('evnt_insert', null);
+ }
+ }
+ }
+
+}
+
+
+export default class TriggerSchema extends BaseUISchema {
+ constructor(fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ is_row_trigger: true,
+ fires: 'BEFORE',
+ ...initValues
+ });
+
+ this.fieldOptions = {
+ triggerFunction: [],
+ //columns: [],
+ ...fieldOptions,
+ };
+ this.nodeInfo = this.fieldOptions.nodeInfo;
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ inSchemaWithModelCheck(state) {
+ // Check if we are under schema node & in 'create' mode
+ if('schema' in this.nodeInfo) {
+ // We will disable control if it's in 'edit' mode
+ return !this.isNew(state);
+ }
+ return true;
+ }
+
+ disableTransition(state) {
+ if (!this.isNew())
+ return true;
+ let flag = false,
+ evnt = null,
+ name = state.name,
+ evnt_count = 0;
+
+ // Disable transition tables for view trigger and PG version < 100000
+ if(_.indexOf(Object.keys(this.nodeInfo), 'table') == -1 ||
+ this.nodeInfo.server.version < 100000) return true;
+
+ if (name == 'tgoldtable') evnt = 'evnt_delete';
+ else if (name == 'tgnewtable') evnt = 'evnt_insert';
+
+ if(state.evnt_insert) evnt_count++;
+ if(state.evnt_update) evnt_count++;
+ if(state.evnt_delete) evnt_count++;
+
+
+ // Disable transition tables if
+ // - It is a constraint trigger
+ // - Fires other than AFTER
+ // - More than one events enabled
+ // - Update event with the column list
+
+ // Disable Old transition table if both UPDATE and DELETE events are disabled
+ // Disable New transition table if both UPDATE and INSERT events are disabled
+ if(!state.is_constraint_trigger && state.fires == 'AFTER' &&
+ (state.evnt_update || state[evnt]) && evnt_count == 1) {
+ flag = (state.evnt_update && (_.size(state.columns) >= 1 && state.columns[0] != ''));
+ }
+
+ return flag;
+ }
+
+ isDisable(state) {
+ return !state.is_constraint_trigger;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', disabled: obj.inCatalog(), noEmpty: true
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'int', mode: ['properties'],
+ },{
+ id: 'is_enable_trigger', label: gettext('Trigger enabled?'),
+ mode: ['edit', 'properties'], group: gettext('Definition'),
+ type: 'select',
+ disabled: () => {
+ return 'catalog' in obj.nodeInfo || 'view' in obj.nodeInfo;
+ },
+ options: [
+ {label: gettext('Enable'), value: 'O'},
+ {label: gettext('Enable Replica'), value: 'R'},
+ {label: gettext('Enable Always'), value: 'A'},
+ {label: gettext('Disable'), value: 'D'},
+ ],
+ controlProps: { allowClear: false },
+ },{
+ id: 'is_row_trigger', label: gettext('Row trigger?'),
+ type: 'switch', group: gettext('Definition'),
+ mode: ['create','edit', 'properties'],
+ deps: ['is_constraint_trigger'],
+ readonly: (state) => {
+ // Disabled if table is a partitioned table.
+ if (!obj.isNew())
+ return true;
+
+ if (( _.has(obj.nodeInfo, 'table') && _.has(obj.nodeInfo.table, 'is_partitioned') &&
+ obj.nodeInfo.table.is_partitioned) && obj.nodeInfo?.server.version < 110000)
+ {
+ state.is_row_trigger = false;
+ return true;
+ }
+
+ // If constraint trigger is set to True then row trigger will
+ // automatically set to True and becomes disable
+ let is_constraint_trigger = state.is_constraint_trigger;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ if(!_.isUndefined(is_constraint_trigger) &&
+ is_constraint_trigger === true) {
+ // change it's model value
+ state.is_row_trigger = true;
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ // Check if it is row trigger then enabled it.
+ let is_row_trigger = state.is_row_trigger;
+ return !(!_.isUndefined(is_row_trigger) && obj.nodeInfo.server.server_type == 'ppas');
+ }
+ },
+ },{
+ id: 'is_constraint_trigger', label: gettext('Constraint trigger?'),
+ type: 'switch',
+ mode: ['create','edit', 'properties'],
+ group: gettext('Definition'),
+ deps: ['tfunction'],
+ readonly: (state) => {
+ // Disabled if table is a partitioned table.
+ let tfunction = state.tfunction;
+ if (( _.has(obj.nodeInfo, 'table') && _.has(obj.nodeInfo.table, 'is_partitioned') &&
+ obj.nodeInfo.table.is_partitioned) || ( _.has(obj.nodeInfo, 'view')) ||
+ (obj.nodeInfo.server.server_type === 'ppas' && !_.isUndefined(tfunction) &&
+ tfunction === 'Inline EDB-SPL')) {
+ state.is_constraint_trigger = false;
+ return true;
+ }
+ return obj.inSchemaWithModelCheck(state);
+ },
+ disabled: () => {
+ return 'view' in obj.nodeInfo;
+ }
+ },{
+ id: 'tgdeferrable', label: gettext('Deferrable?'),
+ type: 'switch', group: gettext('Definition'),
+ mode: ['create','edit', 'properties'],
+ deps: ['is_constraint_trigger'],
+ readonly: (state) => {
+ // If constraint trigger is set to True then only enable it
+ let is_constraint_trigger = state.is_constraint_trigger;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ if(!_.isUndefined(is_constraint_trigger) &&
+ is_constraint_trigger === true) {
+ return false;
+ } else {
+ // If value is already set then reset it to false
+ if(state.tgdeferrable) {
+ state.tgdeferrable = false;
+ }
+ return true;
+ }
+ } else {
+ // readonly it
+ return true;
+ }
+ },
+ disabled: (state) => {
+ return obj.isDisable(state);
+ }
+ },{
+ id: 'tginitdeferred', label: gettext('Deferred?'),
+ type: 'switch', group: gettext('Definition'),
+ mode: ['create','edit', 'properties'],
+ deps: ['tgdeferrable', 'is_constraint_trigger'],
+ readonly: (state) => {
+ // If Deferrable is set to True then only enable it
+ let tgdeferrable = state.tgdeferrable;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ if(!_.isUndefined(tgdeferrable) && tgdeferrable) {
+ return false;
+ } else {
+ // If value is already set then reset it to false
+ if(obj.tginitdeferred) {
+ state.tginitdeferred = false;
+ }
+ // If constraint trigger is set then do not disable
+ return !state.is_constraint_trigger;
+ }
+ } else {
+ // readonly it
+ return true;
+ }
+ },
+ disabled: (state) => {
+ return obj.isDisable(state);
+ }
+ },{
+ id: 'tfunction', label: gettext('Trigger function'),
+ type: 'select', readonly: obj.inSchemaWithModelCheck,
+ mode: ['create','edit', 'properties'], group: gettext('Definition'),
+ control: 'node-ajax-options', url: 'get_triggerfunctions', url_jump_after_node: 'schema',
+ options: obj.fieldOptions.triggerFunction,
+ cache_node: 'trigger_function',
+ },{
+ id: 'tgargs', label: gettext('Arguments'), cell: 'text',
+ group: gettext('Definition'),
+ type: 'text',mode: ['create','edit', 'properties'], deps: ['tfunction'],
+ readonly: (state) => {
+ // We will disable it when EDB PPAS and trigger function is
+ // set to Inline EDB-SPL
+ let tfunction = state.tfunction,
+ server_type = obj.nodeInfo.server.server_type;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ if(server_type === 'ppas' &&
+ !_.isUndefined(tfunction) &&
+ tfunction === 'Inline EDB-SPL') {
+ // Disable and clear its value
+ state.tgargs = undefined;
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ // Disable it
+ return true;
+ }
+ },
+ },{
+ id: 'fires', label: gettext('Fires'), deps: ['is_constraint_trigger'],
+ mode: ['create','edit', 'properties'], group: gettext('Events'),
+ options: () => {
+ let table_options = [
+ {label: 'BEFORE', value: 'BEFORE'},
+ {label: 'AFTER', value: 'AFTER'}],
+ view_options = [
+ {label: 'BEFORE', value: 'BEFORE'},
+ {label: 'AFTER', value: 'AFTER'},
+ {label: 'INSTEAD OF', value: 'INSTEAD OF'}];
+ // If we are under table then show table specific options
+ if(_.indexOf(Object.keys(obj.nodeInfo), 'table') != -1) {
+ return table_options;
+ } else {
+ return view_options;
+ }
+ },
+ type: 'select', controlProps: { allowClear: false },
+ readonly: (state) => {
+ if (!obj.isNew())
+ return true;
+ // If contraint trigger is set to True then only enable it
+ let is_constraint_trigger = state.is_constraint_trigger;
+ if(!obj.inSchemaWithModelCheck(state)) {
+ if(!_.isUndefined(is_constraint_trigger) &&
+ is_constraint_trigger === true) {
+ state.fires = 'AFTER';
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ // Check if it is row trigger then enabled it.
+ let fires_ = state.fires;
+ return !(!_.isUndefined(fires_) && obj.nodeInfo.server.server_type == 'ppas');
+ }
+ },
+ },{
+ type: 'nested-fieldset', mode: ['create','edit', 'properties'],
+ label: gettext('Events'), group: gettext('Events'),
+ schema: new EventSchema({nodeInfo: obj.nodeInfo}),
+ },{
+ id: 'whenclause', label: gettext('When'),
+ type: 'sql',
+ readonly: obj.inSchemaWithModelCheck,
+ mode: ['create', 'edit', 'properties'], visible: true,
+ group: gettext('Events'),
+ },{
+ id: 'columns', label: gettext('Columns'),
+ type: 'select', controlProps: { multiple: true },
+ deps: ['evnt_update'], group: gettext('Events'),
+ options: obj.fieldOptions.columns,
+ readonly: (state) => {
+ if(obj.nodeInfo && 'catalog' in obj.nodeInfo) {
+ return true;
+ }
+ //Disable in edit mode
+ if (!obj.isNew()) {
+ return true;
+ }
+ // Enable column only if update event is set true
+ let isUpdate = state.evnt_update;
+ return !(!_.isUndefined(isUpdate) && isUpdate);
+ },
+ },{
+ id: 'tgoldtable', label: gettext('Old table'),
+ type: 'text', group: gettext('Transition'),
+ cell: 'text', mode: ['create', 'edit', 'properties'],
+ deps: ['fires', 'is_constraint_trigger', 'evnt_insert', 'evnt_update', 'evnt_delete', 'columns'],
+ disabled: obj.disableTransition,
+ },{
+ id: 'tgnewtable', label: gettext('New table'),
+ type: 'text', group: gettext('Transition'),
+ cell: 'string', mode: ['create', 'edit', 'properties'],
+ deps: ['fires', 'is_constraint_trigger', 'evnt_insert', 'evnt_update', 'evnt_delete', 'columns'],
+ disabled: obj.disableTransition,
+ },{
+ id: 'prosrc', label: gettext('Code'), group: gettext('Code'),
+ type: 'sql', mode: ['create', 'edit'], deps: ['tfunction'],
+ isFullTab: true,
+ visible: true,
+ disabled: (state) => {
+ // We will enable it only when EDB PPAS and trigger function is
+ // set to Inline EDB-SPL
+ let tfunction = state.tfunction,
+ server_type = obj.nodeInfo.server.server_type;
+
+ return (server_type !== 'ppas' ||
+ _.isUndefined(tfunction) ||
+ tfunction !== 'Inline EDB-SPL');
+ },
+ depChange: (state) => {
+ if (state.tfunction == null) {
+ return { prosrc: '' };
+ }
+ }
+ },{
+ id: 'is_sys_trigger', label: gettext('System trigger?'), cell: 'text',
+ type: 'switch', disabled: obj.inSchemaWithModelCheck, mode: ['properties'],
+ },{
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ disabled: obj.inCatalog(),
+ }];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+
+ if (isEmptyString(state.service)) {
+
+ /* trigger function validation*/
+ if (isEmptyString(state.tfunction)) {
+ errmsg = gettext('Trigger function cannot be empty.');
+ setError('tfunction', errmsg);
+ return true;
+ } else {
+ setError('tfunction', null);
+ }
+ }
+ }
+}
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/templates/triggers/css/trigger.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/templates/triggers/css/trigger.css
new file mode 100644
index 0000000000000000000000000000000000000000..1b91c040efde3e8ce0c0f1483e19100a3bffe6ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/templates/triggers/css/trigger.css
@@ -0,0 +1,23 @@
+.icon-coll-trigger {
+ background-image: url('{{ url_for('NODE-trigger.static', filename='img/coll-trigger.svg' )}}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-trigger {
+ background-image: url('{{ url_for('NODE-trigger.static', filename='img/trigger.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
+
+.icon-trigger-bad {
+ background-image: url('{{ url_for('NODE-trigger.static', filename='img/trigger-bad.svg') }}') !important;
+ background-size: 20px !important;
+ border-radius: 10px
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb41dcdd2e8df8265372d48114a9f6331d7650f0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/utils.py
@@ -0,0 +1,316 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Triggers. """
+
+from flask import render_template
+from flask_babel import gettext
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.utils.exception import ObjectGone, ExecuteError
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+from config import PG_DEFAULT_DRIVER
+from pgadmin.utils.driver import get_driver
+from functools import wraps
+
+
+def get_template_path(f):
+ """
+ This function will behave as a decorator which will prepare
+ the template path based on database server version.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold the connection object
+ conn_obj = args[0]
+ if 'template_path' not in kwargs or kwargs['template_path'] is None:
+ kwargs['template_path'] = 'triggers/sql/{0}/#{1}#'.format(
+ conn_obj.manager.server_type, conn_obj.manager.version)
+
+ return f(*args, **kwargs)
+ return wrap
+
+
+@get_template_path
+def get_parent(conn, tid, template_path=None):
+ """
+ This function will return the parent of the given table.
+ :param conn: Connection Object
+ :param tid: Table oid
+ :param template_path: Optional template path
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_parent.sql']), tid=tid)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ raise ExecuteError(rset)
+
+ schema = ''
+ table = ''
+ if 'rows' in rset and len(rset['rows']) > 0:
+ schema = rset['rows'][0]['schema']
+ table = rset['rows'][0]['table']
+
+ return schema, table
+
+
+@get_template_path
+def get_column_details(conn, tid, clist, template_path=None):
+ """
+ This functional will fetch list of column for trigger.
+ :param conn:
+ :param tid:
+ :param clist:
+ :param template_path:
+ :return:
+ """
+
+ SQL = render_template("/".join([template_path,
+ 'get_columns.sql']),
+ tid=tid, clist=clist)
+ status, rset = conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ columns = []
+ for row in rset['rows']:
+ columns.append(row['name'])
+
+ return columns
+
+
+@get_template_path
+def get_trigger_function_and_columns(conn, data, tid,
+ show_system_objects, template_path=None):
+ """
+ This function will return trigger function with schema name.
+ :param conn: Connection Object
+ :param data: Data
+ :param tid: Table ID
+ :param show_system_objects: show system object
+ :param template_path: Optional Template Path
+ :return:
+ """
+ # If language is 'edbspl' then trigger function should be
+ # 'Inline EDB-SPL' else we will find the trigger function
+ # with schema name.
+ SQL = render_template("/".join(
+ [template_path, 'get_triggerfunctions.sql']),
+ tgfoid=data['tgfoid'],
+ show_system_objects=show_system_objects
+ )
+
+ status, result = conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=result)
+
+ # Update the trigger function which we have fetched with
+ # schema name
+ if 'rows' in result and len(result['rows']) > 0 and \
+ 'tfunctions' in result['rows'][0]:
+ data['tfunction'] = result['rows'][0]['tfunctions']
+
+ if len(data['custom_tgargs']) > 0:
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ # We know that trigger has more than 1 argument, let's join them
+ # and convert it to string
+ formatted_args = [driver.qtLiteral(arg, conn)
+ for arg in data['custom_tgargs']]
+ formatted_args = ', '.join(formatted_args)
+
+ data['tgargs'] = formatted_args
+ else:
+ data['tgargs'] = None
+
+ if len(data['tgattr']) >= 1:
+ columns = ', '.join(data['tgattr'].split(' '))
+ data['columns'] = get_column_details(conn, tid, columns)
+
+ return data
+
+
+@get_template_path
+def get_sql(conn, **kwargs):
+ """
+ This function will generate sql from model data.
+
+ :param conn: Connection Object
+ :param kwargs
+ :return:
+ """
+ data = kwargs.get('data')
+ tid = kwargs.get('tid')
+ trid = kwargs.get('trid')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ show_system_objects = kwargs.get('show_system_objects')
+ is_schema_diff = kwargs.get('is_schema_diff', False)
+ template_path = kwargs.get('template_path', None)
+
+ name = data['name'] if 'name' in data else None
+ if trid is not None:
+ sql = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, trid=trid,
+ datlastsysoid=datlastsysoid)
+
+ status, res = conn.execute_dict(sql)
+ if not status:
+ raise ExecuteError(res)
+ elif len(res['rows']) == 0:
+ raise ObjectGone(
+ gettext('Could not find the trigger in the table.'))
+
+ old_data = dict(res['rows'][0])
+ # If name is not present in data then
+ # we will fetch it from old data, we also need schema & table name
+ if 'name' not in data:
+ name = data['name'] = old_data['name']
+
+ drop_sql = _check_schema_diff_sql(is_schema_diff, data, old_data,
+ template_path, conn)
+
+ old_data = get_trigger_function_and_columns(
+ conn, old_data, tid, show_system_objects)
+
+ old_data = trigger_definition(old_data)
+
+ if 'lanname' in old_data and old_data['lanname'] == 'edbspl':
+ data['lanname'] = old_data['lanname']
+ if ('tfunction' in old_data and
+ old_data['tfunction'] == 'Inline EDB-SPL'):
+ data['tfunction'] = old_data['tfunction']
+
+ sql = render_template(
+ "/".join([template_path, 'update.sql']),
+ data=data, o_data=old_data, conn=conn
+ )
+
+ if is_schema_diff:
+ sql = drop_sql + '\n' + sql
+ else:
+ required_args = {
+ 'name': 'Name',
+ 'tfunction': 'Trigger function'
+ }
+
+ for arg in required_args:
+ if arg not in data:
+ return gettext('-- definition incomplete')
+
+ # If the request for new object which do not have did
+ sql = render_template("/".join([template_path, 'create.sql']),
+ data=data, conn=conn)
+ return sql, name
+
+
+def _check_schema_diff_sql(is_schema_diff, data, old_data, template_path,
+ conn):
+ """
+ Check for schema diff and perform required actions.
+ is_schema_diff: flag for check req for schema diff.
+ data: Data.
+ old_data: properties sql data.
+ template_path: template path for get correct template location.
+ conn: Connection.
+ return: return deleted sql statement if any.
+ """
+ drop_sql = ''
+ if is_schema_diff:
+ if 'table' not in data:
+ data['table'] = old_data['relname']
+ if 'schema' not in data:
+ data['schema'] = old_data['nspname']
+
+ # If any of the below key is present in data then we need to drop
+ # trigger and re-create it.
+ key_array = ['prosrc', 'is_row_trigger', 'evnt_insert',
+ 'evnt_delete', 'evnt_update', 'fires', 'tgdeferrable',
+ 'whenclause', 'tfunction', 'tgargs', 'columns',
+ 'is_constraint_trigger', 'tginitdeferred']
+
+ is_drop_trigger = False
+ for key in key_array:
+ if key in data:
+ is_drop_trigger = True
+ break
+
+ if is_drop_trigger:
+ tmp_data = dict()
+ tmp_data['name'] = data['name']
+ tmp_data['nspname'] = old_data['nspname']
+ tmp_data['relname'] = old_data['relname']
+ drop_sql = render_template("/".join([template_path,
+ 'delete.sql']),
+ data=tmp_data, conn=conn)
+ return drop_sql
+
+
+@get_template_path
+def get_reverse_engineered_sql(conn, **kwargs):
+ """
+ This function will return reverse engineered sql for specified trigger.
+
+ :param conn: Connection Object
+ :param kwargs:
+ :return:
+ """
+ schema = kwargs.get('schema')
+ table = kwargs.get('table')
+ tid = kwargs.get('tid')
+ trid = kwargs.get('trid')
+ datlastsysoid = kwargs.get('datlastsysoid')
+ show_system_objects = kwargs.get('show_system_objects')
+ template_path = kwargs.get('template_path', None)
+ with_header = kwargs.get('with_header', True)
+
+ SQL = render_template("/".join([template_path, 'properties.sql']),
+ tid=tid, trid=trid,
+ datlastsysoid=datlastsysoid)
+
+ status, res = conn.execute_dict(SQL)
+ if not status:
+ raise ExecuteError(res)
+
+ if len(res['rows']) == 0:
+ raise ObjectGone(gettext('Could not find the trigger in the table.'))
+
+ data = dict(res['rows'][0])
+
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = schema
+ data['table'] = table
+
+ data = \
+ get_trigger_function_and_columns(conn, data, tid, show_system_objects)
+
+ data = trigger_definition(data)
+
+ SQL, _ = get_sql(conn, data=data, tid=tid, trid=None,
+ datlastsysoid=datlastsysoid,
+ show_system_objects=show_system_objects)
+
+ if with_header:
+ sql_header = "-- Trigger: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([template_path, 'delete.sql']),
+ data=data, conn=conn)
+
+ SQL = sql_header + '\n\n' + SQL.strip('\n')
+ else:
+ SQL = SQL.strip('\n')
+
+ # If trigger is disabled then add sql code for the same
+ if data['is_enable_trigger'] != 'O':
+ SQL += '\n\n'
+ SQL += render_template("/".join([template_path,
+ 'enable_disable_trigger.sql']),
+ data=data, conn=conn)
+ return SQL
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..718e6403a6efa100498046875cdfb6cde0f21b1f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/utils.py
@@ -0,0 +1,2233 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for Table and Partitioned Table. """
+
+import re
+import copy
+from functools import wraps
+import json
+from flask import render_template, jsonify, request
+from flask_babel import gettext
+
+from pgadmin.browser.server_groups.servers.databases.schemas\
+ .tables.base_partition_table import BasePartitionTable
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ gone, make_response as ajax_response
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import DataTypeReader, parse_rule_definition
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.compile_template_name import compile_template_path
+from pgadmin.utils.driver import get_driver
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ columns import utils as column_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.foreign_key import utils as fkey_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.check_constraint import utils as check_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.exclusion_constraint import utils as exclusion_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ constraints.index_constraint import utils as idxcons_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ triggers import utils as trigger_utils
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ compound_triggers import utils as compound_trigger_utils
+from pgadmin.browser.server_groups.servers.databases.schemas. \
+ tables.row_security_policies import \
+ utils as row_security_policies_utils
+from pgadmin.utils.preferences import Preferences
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import VacuumSettings
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.dashboard import locks
+
+
+class BaseTableView(PGChildNodeView, BasePartitionTable, VacuumSettings):
+ """
+ This class is base class for tables and partitioned tables.
+
+ Methods:
+ -------
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * _formatter(data, tid)
+ - It will return formatted output of query result
+ as per client model format
+
+ * get_table_dependents(self, tid):
+ - This function get the dependents and return ajax response
+ for the table node.
+
+ * get_table_dependencies(self, tid):
+ - This function get the dependencies and return ajax response
+ for the table node.
+
+ * get_table_statistics(self, tid):
+ - Returns the statistics for a particular table if tid is specified,
+ otherwise it will return statistics for all the tables in that
+ schema.
+ * get_reverse_engineered_sql(self, did, scid, tid, main_sql, data):
+ - This function will creates reverse engineered sql for
+ the table object.
+
+ * reset_statistics(self, scid, tid):
+ - This function will reset statistics of table.
+ """
+
+ node_label = "Table"
+ pattern = '\n{2,}'
+ double_newline = '\n\n'
+ BASE_TEMPLATE_PATH = 'tables/sql/#{0}#'
+
+ @staticmethod
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ driver = get_driver(PG_DEFAULT_DRIVER)
+
+ self.manager = driver.connection_manager(kwargs['sid'])
+ if "conn_id" in kwargs:
+ self.conn = self.manager.connection(
+ did=kwargs['did'], conn_id=kwargs['conn_id'])
+ else:
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.qtIdent = driver.qtIdent
+ self.qtTypeIdent = driver.qtTypeIdent
+
+ ver = self.manager.version
+ server_type = self.manager.server_type
+ # Set the template path for the SQL scripts
+ self.table_template_path = compile_template_path('tables/sql', ver)
+ self.data_type_template_path = compile_template_path(
+ 'datatype/sql', ver)
+ self.partition_template_path = \
+ 'partitions/sql/{0}/#{0}#{1}#'.format(server_type, ver)
+
+ # Template for Column ,check constraint and exclusion
+ # constraint node
+ self.column_template_path = 'columns/sql/#{0}#'.format(ver)
+
+ # Template for index node
+ self.index_template_path = compile_template_path(
+ 'indexes/sql', ver)
+
+ # Template for index node
+ self.row_security_policies_template_path = \
+ 'row_security_policies/sql/#{0}#'.format(ver)
+
+ # Template for trigger node
+ self.trigger_template_path = \
+ 'triggers/sql/{0}/#{1}#'.format(server_type, ver)
+
+ # Template for compound trigger node
+ self.compound_trigger_template_path = \
+ 'compound_triggers/sql/{0}/#{1}#'.format(server_type, ver)
+
+ # Template for rules node
+ self.rules_template_path = 'rules/sql'
+
+ # Supported ACL for table
+ self.acl = ['a', 'r', 'w', 'd', 'D', 'x', 't']
+
+ # Supported ACL for columns
+ self.column_acl = ['a', 'r', 'w', 'x']
+
+ # Submodule list for schema diff
+ self.tables_sub_modules = ['index', 'rule', 'trigger']
+ if server_type == 'ppas' and ver >= 120000:
+ self.tables_sub_modules.append('compound_trigger')
+ if ver >= 90500:
+ self.tables_sub_modules.append('row_security_policy')
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ def _formatter(self, did, scid, tid, data, with_serial_cols=False):
+ """
+ Args:
+ data: dict of query result
+ scid: schema oid
+ tid: table oid
+
+ Returns:
+ It will return formatted output of query result
+ as per client model format
+ """
+ # Need to format security labels according to client js collection
+ if 'seclabels' in data and data['seclabels'] is not None:
+ seclabels = []
+ for seclbls in data['seclabels']:
+ k, v = seclbls.split('=')
+ seclabels.append({'provider': k, 'label': v})
+
+ data['seclabels'] = seclabels
+
+ # We need to parse & convert ACL coming from database to json format
+ sql = render_template("/".join([self.table_template_path,
+ self._ACL_SQL]),
+ tid=tid, scid=scid)
+ status, acl = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ BaseTableView._set_privileges_for_properties(data, acl)
+
+ # We will add Auto vacuum defaults with out result for grid
+ data['vacuum_table'] = copy.deepcopy(
+ self.parse_vacuum_data(self.conn, data, 'table'))
+ data['vacuum_toast'] = copy.deepcopy(
+ self.parse_vacuum_data(self.conn, data, 'toast'))
+
+ # Fetch columns for the table logic
+ #
+ # 1) Check if of_type and inherited tables are present?
+ # 2) If yes then Fetch all the columns for of_type and inherited tables
+ # 3) Add columns in columns collection
+ # 4) Find all the columns for tables and filter out columns which are
+ # not inherited from any table & format them one by one
+
+ other_columns = []
+ table_or_type = ''
+ # Get of_type table columns and add it into columns dict
+ if data['typoid']:
+ sql = render_template("/".join([self.table_template_path,
+ 'get_columns_for_table.sql']),
+ tid=data['typoid'], conn=self.conn)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ other_columns = res['rows']
+ table_or_type = 'type'
+ # Get inherited table(s) columns and add it into columns dict
+ elif data['coll_inherits'] and len(data['coll_inherits']) > 0:
+ is_error, errmsg = self._get_inherited_tables(scid, data,
+ other_columns)
+ if is_error:
+ return internal_server_error(errormsg=errmsg)
+
+ table_or_type = 'table'
+
+ # We will fetch all the columns for the table using
+ # columns properties.sql, so we need to set template path
+ data = column_utils.get_formatted_columns(self.conn, tid,
+ data, other_columns,
+ table_or_type,
+ with_serial=with_serial_cols)
+
+ self._add_constrints_to_output(data, did, tid)
+
+ return data
+
+ def _get_inherited_tables(self, scid, data, other_columns):
+ # Return all tables which can be inherited & do not show
+ # system columns
+ sql = render_template("/".join([self.table_template_path,
+ 'get_inherits.sql']),
+ show_system_objects=False,
+ scid=scid
+ )
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return True, rset
+
+ for row in rset['rows']:
+ if row['inherits'] in data['coll_inherits']:
+ # Fetch columns using inherited table OID
+ sql = render_template("/".join(
+ [self.table_template_path,
+ 'get_columns_for_table.sql']),
+ tid=row['oid'], conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return True, res
+ other_columns.extend(res['rows'][:])
+
+ return False, ''
+
+ @staticmethod
+ def _set_privileges_for_properties(data, acl):
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ if row['deftype'] in data:
+ data[row['deftype']].append(priv)
+ else:
+ data[row['deftype']] = [priv]
+
+ def _add_constrints_to_output(self, data, did, tid):
+ # Here we will add constraint in our output
+ index_constraints = {
+ 'p': 'primary_key', 'u': 'unique_constraint'
+ }
+ for ctype in index_constraints.keys():
+ data[index_constraints[ctype]] = []
+ status, constraints = \
+ idxcons_utils.get_index_constraints(self.conn, did, tid, ctype)
+ if status:
+ for cons in constraints:
+ if not self.\
+ _is_partition_and_constraint_inherited(cons, data):
+ data.setdefault(
+ index_constraints[ctype], []).append(cons)
+
+ # Add Foreign Keys
+ status, foreign_keys = fkey_utils.get_foreign_keys(self.conn, tid)
+ if status:
+ for fk in foreign_keys:
+ if not self._is_partition_and_constraint_inherited(fk, data):
+ data.setdefault('foreign_key', []).append(fk)
+
+ # Add Check Constraints
+ status, check_constraints = \
+ check_utils.get_check_constraints(self.conn, tid)
+ if status:
+ for cc in check_constraints:
+ if not self._is_partition_and_constraint_inherited(cc, data):
+ data.setdefault('check_constraint', []).append(cc)
+
+ # Add Exclusion Constraint
+ status, exclusion_constraints = \
+ exclusion_utils.get_exclusion_constraints(self.conn, did, tid)
+ if status:
+ for ex in exclusion_constraints:
+ data.setdefault('exclude_constraint', []).append(ex)
+
+ @staticmethod
+ def _is_partition_and_constraint_inherited(constraint, data):
+
+ """
+ This function will check whether a constraint is local or
+ inherited only for partition table
+ :param constraint: given constraint
+ :param data: partition table data
+ :return: True or False based on condition
+ """
+ # check whether the table is partition or not, then check conislocal
+ if 'relispartition' in data and data['relispartition'] is True and \
+ 'conislocal' in constraint and \
+ constraint['conislocal'] is False:
+ return True
+ return False
+
+ def get_table_dependents(self, tid):
+ """
+ This function get the dependents and return ajax response
+ for the table node.
+
+ Args:
+ tid: Table ID
+ """
+ # Specific condition for column which we need to append
+ where = "WHERE dep.refobjid={0}::OID".format(tid)
+
+ dependents_result = self.get_dependents(
+ self.conn, tid
+ )
+
+ # Specific sql to run againt column to fetch dependents
+ sql = render_template("/".join([self.table_template_path,
+ 'depend.sql']), where=where)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in res['rows']:
+ ref_name = row['refname']
+ if ref_name is None:
+ continue
+
+ dep_type = ''
+ dep_str = row['deptype']
+ if dep_str == 'a':
+ dep_type = 'auto'
+ elif dep_str == 'n':
+ dep_type = 'normal'
+ elif dep_str == 'i':
+ dep_type = 'internal'
+
+ dependents_result.append({'type': 'sequence', 'name': ref_name,
+ 'field': dep_type})
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ def get_table_dependencies(self, tid):
+ """
+ This function get the dependencies and return ajax response
+ for the table node.
+
+ Args:
+ tid: Table ID
+
+ """
+ dependencies_result = self.get_dependencies(
+ self.conn, tid
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ def get_fk_ref_tables(self, tid):
+ """
+ This function get the depending tables of the current table.
+ The tables depending on tid table using FK relation.
+ Args:
+ tid: Table ID
+ """
+ sql = render_template("/".join([self.table_template_path,
+ 'fk_ref_tables.sql']), oid=tid)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return status, res
+
+ return status, res['rows']
+
+ def get_table_statistics(self, scid, tid):
+ """
+ Statistics
+
+ Args:
+ scid: Schema Id
+ tid: Table Id
+
+ Returns the statistics for a particular table if tid is specified,
+ otherwise it will return statistics for all the tables in that
+ schema.
+ """
+
+ # Fetch schema name
+ status, schema_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_schema.sql']),
+ conn=self.conn, scid=scid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ if tid is None:
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.table_template_path,
+ 'coll_table_stats.sql']), conn=self.conn,
+ schema_name=schema_name
+ )
+ )
+ else:
+ # For Individual table stats
+
+ # Check if pgstattuple extension is already created?
+ # if created then only add extended stats
+ status, is_pgstattuple = self.conn.execute_scalar("""
+ SELECT (count(extname) > 0) AS is_pgstattuple
+ FROM pg_catalog.pg_extension
+ WHERE extname='pgstattuple'
+ """)
+ if not status:
+ return internal_server_error(errormsg=is_pgstattuple)
+
+ # Fetch Table name
+ status, table_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_table.sql']),
+ conn=self.conn, scid=scid, tid=tid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=table_name)
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.table_template_path, 'stats.sql']),
+ conn=self.conn, schema_name=schema_name,
+ table_name=table_name,
+ is_pgstattuple=is_pgstattuple, tid=tid
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def get_types_condition_sql(self, show_system_objects):
+ condition = render_template(
+ "/".join([
+ self.table_template_path, 'get_types_where_condition.sql'
+ ]),
+ show_system_objects=show_system_objects
+ )
+
+ return condition
+
+ def fetch_tables(self, sid, did, scid, tid=None, with_serial_cols=False):
+ """
+ This function will fetch the list of all the tables
+ and will be used by schema diff.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :param tid: Table Id
+ :param with_serial_cols: Boolean
+ :return: Table dataset
+ """
+
+ if tid:
+ status, data = self._fetch_table_properties(did, scid, tid)
+
+ if not status:
+ return False, data
+
+ data = BaseTableView.properties(
+ self, 0, sid, did, scid, tid, res=data,
+ with_serial_cols=with_serial_cols,
+ return_ajax_response=False,
+ )
+
+ return True, data
+
+ else:
+ res = dict()
+ sql = render_template("/".join([self.table_template_path,
+ self._NODES_SQL]), scid=scid,
+ schema_diff=True)
+ status, tables = self.conn.execute_2darray(sql)
+ if not status:
+ return False, tables
+
+ for row in tables['rows']:
+ status, data = \
+ self._fetch_table_properties(did, scid, row['oid'])
+
+ if status:
+ data = BaseTableView.properties(
+ self, 0, sid, did, scid, row['oid'], res=data,
+ with_serial_cols=with_serial_cols,
+ return_ajax_response=False
+ )
+
+ # Get sub module data of a specified table for object
+ # comparison
+ BaseTableView._get_sub_module_data_for_compare(
+ self, sid, did, scid, data, row)
+ res[row['name']] = data
+
+ return True, res
+
+ def _get_sub_module_data_for_compare(self, sid, did, scid, data, row):
+ # Get sub module data of a specified table for object
+ # comparison
+ for module in self.tables_sub_modules:
+ module_view = SchemaDiffRegistry.get_node_view(module)
+ if module_view.blueprint.server_type is None or \
+ self.manager.server_type in \
+ module_view.blueprint.server_type:
+ sub_data = module_view.fetch_objects_to_compare(
+ sid=sid, did=did, scid=scid, tid=row['oid'],
+ oid=None)
+ data[module] = sub_data
+
+ @staticmethod
+ def _check_rlspolicy_support(res):
+ """
+ This function is used to check whether 'rlspolicy' in response
+ as it supported for version 9.5 and above
+ :param res:
+ :return:
+ """
+ if 'rlspolicy' in res['rows'][0]:
+ # Set the value of rls policy
+ if res['rows'][0]['rlspolicy'] == "true":
+ res['rows'][0]['rlspolicy'] = True
+
+ # Set the value of force rls policy for table owner
+ if res['rows'][0]['forcerlspolicy'] == "true":
+ res['rows'][0]['forcerlspolicy'] = True
+
+ def _fetch_table_properties(self, did, scid, tid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param did:
+ :param scid:
+ :param tid:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.table_template_path, self._PROPERTIES_SQL]),
+ did=did, scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ conn=self.conn
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ elif len(res['rows']) == 0:
+ return False, gone(
+ gettext(self.not_found_error_msg()))
+
+ # Update autovacuum properties
+ self.update_autovacuum_properties(res['rows'][0])
+
+ # We will check the threshold set by user before executing
+ # the query because that can cause performance issues
+ # with large result set
+ pref = Preferences.module('browser')
+ table_row_count_pref = pref.preference('table_row_count_threshold')
+ table_row_count_threshold = table_row_count_pref.get()
+ estimated_row_count = int(res['rows'][0].get('reltuples', 0))
+
+ # Check whether 'rlspolicy' in response as it supported for
+ # version 9.5 and above
+ BaseTableView._check_rlspolicy_support(res)
+
+ # If estimated_row_count is zero or -1 then set the row count to 0
+ if not estimated_row_count or estimated_row_count < 0:
+ res['rows'][0]['rows_cnt'] = 0
+ # If estimated rows are greater than threshold then
+ elif estimated_row_count > table_row_count_threshold:
+ res['rows'][0]['rows_cnt'] = str(table_row_count_threshold) + '+'
+ # If estimated rows is lower than threshold then calculate the count
+ elif 0 < estimated_row_count <= table_row_count_threshold:
+ sql = render_template(
+ "/".join(
+ [self.table_template_path, 'get_table_row_count.sql']
+ ), data=res['rows'][0]
+ )
+
+ status, count = self.conn.execute_scalar(sql)
+
+ if not status:
+ return False, internal_server_error(errormsg=count)
+
+ res['rows'][0]['rows_cnt'] = count
+
+ # Fetch privileges
+ sql = render_template("/".join([self.table_template_path,
+ self._ACL_SQL]),
+ tid=tid, scid=scid)
+ status, tblaclres = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Get Formatted Privileges
+ res['rows'][0].update(self._format_tbacl_from_db(tblaclres['rows']))
+
+ return True, res
+
+ def _format_tbacl_from_db(self, tbacl):
+ """
+ Returns privileges.
+ Args:
+ tbacl: Privileges Dict
+ """
+ privileges = []
+ for row in tbacl:
+ priv = parse_priv_from_db(row)
+ privileges.append(priv)
+
+ return {"acl": privileges}
+
+ def _format_column_list(self, data):
+ # Now we have all lis of columns which we need
+ # to include in our create definition, Let's format them
+ if 'columns' in data:
+ for c in data['columns']:
+ if 'attacl' in c:
+ c['attacl'] = parse_priv_to_db(
+ c['attacl'], self.column_acl
+ )
+
+ # check type for '[]' in it
+ if 'cltype' in c:
+ c['cltype'], c['hasSqrBracket'] = \
+ column_utils.type_formatter(c['cltype'])
+
+ def _get_resql_for_table(self, did, scid, tid, data, json_resp, main_sql,
+ add_not_exists_clause=False):
+ """
+ #####################################
+ # Reverse engineered sql for TABLE
+ #####################################
+ """
+ data = self._formatter(did, scid, tid, data)
+
+ # Format column list
+ self._format_column_list(data)
+
+ if json_resp:
+ sql_header = "-- Table: {0}.{1}\n\n-- ".format(
+ data['schema'], data['name'])
+
+ sql_header += render_template("/".join([self.table_template_path,
+ self._DELETE_SQL]),
+ data=data, conn=self.conn)
+
+ sql_header = sql_header.strip('\n')
+ sql_header += '\n'
+
+ # Add into main sql
+ main_sql.append(sql_header)
+
+ # Parse privilege data
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)
+
+ if 'acl' in data:
+ data.update({'revoke_all': []})
+ for acl in data['acl']:
+ if len(acl['privileges']) > 0 and len(acl['privileges']) < 7:
+ data['revoke_all'].append(acl['grantee'])
+
+ # if table is partitions then
+ if 'relispartition' in data and data['relispartition']:
+ table_sql = \
+ render_template("/".join([self.partition_template_path,
+ self._CREATE_SQL]), data=data,
+ conn=self.conn,
+ add_not_exists_clause=add_not_exists_clause)
+ else:
+ table_sql = \
+ render_template("/".join([self.table_template_path,
+ self._CREATE_SQL]), data=data,
+ conn=self.conn, is_sql=True,
+ add_not_exists_clause=add_not_exists_clause)
+
+ # Add into main sql
+ table_sql = re.sub(self.pattern, self.double_newline, table_sql)
+ main_sql.append(table_sql.strip('\n'))
+
+ def _get_resql_for_index(self, did, tid, main_sql, json_resp, schema,
+ table, add_not_exists_clause=False):
+ """
+ ######################################
+ # Reverse engineered sql for INDEX
+ ######################################
+ """
+
+ sql = render_template("/".join([self.index_template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # Dynamically load index utils to avoid circular dependency.
+ from pgadmin.browser.server_groups.servers.databases.schemas. \
+ tables.indexes import utils as index_utils
+ for row in rset['rows']:
+ # Do not include inherited indexes as those are automatically
+ # created by postgres. If index is inherited, exclude it
+ # from main sql
+ if 'is_inherited' in row and row['is_inherited'] is True:
+ continue
+
+ index_sql = index_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=table, did=did, tid=tid,
+ idx=row['oid'], datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ template_path=None, with_header=json_resp,
+ add_not_exists_clause=add_not_exists_clause
+ )
+ index_sql = "\n" + index_sql
+
+ # Add into main sql
+ index_sql = re.sub(self.pattern, self.double_newline, index_sql)
+
+ main_sql.append(index_sql.strip('\n'))
+
+ def _get_resql_for_row_security_policy(self, scid, tid, json_resp,
+ main_sql, schema, table):
+ """
+ ########################################################
+ # Reverse engineered sql for ROW SECURITY POLICY
+ ########################################################
+ """
+ if self.manager.version >= 90500:
+ sql = \
+ render_template(
+ "/".join([self.row_security_policies_template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ policy_sql = row_security_policies_utils. \
+ get_reverse_engineered_sql(
+ self.conn, schema=schema, table=table, scid=scid,
+ plid=row['oid'], policy_table_id=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ template_path=None, with_header=json_resp)
+ policy_sql = "\n" + policy_sql
+
+ # Add into main sql
+ policy_sql = re.sub(self.pattern, self.double_newline,
+ policy_sql)
+
+ main_sql.append(policy_sql.strip('\n'))
+
+ def _get_resql_for_triggers(self, tid, json_resp, main_sql, schema,
+ table):
+ """
+ ########################################
+ # Reverse engineered sql for TRIGGERS
+ ########################################
+ """
+ sql = render_template("/".join([self.trigger_template_path,
+ self._NODES_SQL]), tid=tid)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ trigger_sql = trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=table, tid=tid,
+ trid=row['oid'], datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects,
+ template_path=None, with_header=json_resp)
+ trigger_sql = "\n" + trigger_sql
+
+ # Add into main sql
+ trigger_sql = re.sub(self.pattern, self.double_newline,
+ trigger_sql)
+ main_sql.append(trigger_sql)
+
+ def _get_resql_for_compound_triggers(self, tid, main_sql, schema, table):
+ """
+ #################################################
+ # Reverse engineered sql for COMPOUND TRIGGERS
+ #################################################
+ """
+
+ if self.manager.server_type == 'ppas' \
+ and self.manager.version >= 120000:
+ sql = render_template("/".join(
+ [self.compound_trigger_template_path, self._NODES_SQL]),
+ tid=tid)
+
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ compound_trigger_sql = \
+ compound_trigger_utils.get_reverse_engineered_sql(
+ self.conn, schema=schema, table=table, tid=tid,
+ trid=row['oid'],
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ compound_trigger_sql = "\n" + compound_trigger_sql
+
+ # Add into main sql
+ compound_trigger_sql = \
+ re.sub(self.pattern, self.double_newline,
+ compound_trigger_sql)
+ main_sql.append(compound_trigger_sql)
+
+ def _get_resql_for_rules(self, tid, main_sql, table, json_resp):
+ """
+ #####################################
+ # Reverse engineered sql for RULES
+ #####################################
+ """
+
+ sql = render_template("/".join(
+ [self.rules_template_path, self._NODES_SQL]), tid=tid)
+
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ rules_sql = '\n'
+ sql = render_template("/".join(
+ [self.rules_template_path, self._PROPERTIES_SQL]
+ ), rid=row['oid'], datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ display_comments = True
+ if not json_resp:
+ display_comments = False
+ res_data = parse_rule_definition(res)
+ # Update the correct table name for rules
+ if 'view' in res_data:
+ res_data['view'] = table
+
+ rules_sql += render_template("/".join(
+ [self.rules_template_path, self._CREATE_SQL]),
+ data=res_data, display_comments=display_comments,
+ add_replace_clause=True
+ )
+
+ # Add into main sql
+ rules_sql = re.sub(self.pattern, self.double_newline, rules_sql)
+ main_sql.append(rules_sql)
+
+ def _get_resql_for_partitions(self, data, rset, json_resp,
+ diff_partition_sql, main_sql, did):
+ """
+ ##########################################
+ # Reverse engineered sql for PARTITIONS
+ ##########################################
+ """
+
+ sql_header = ''
+ partition_sql_arr = []
+ if len(rset['rows']):
+ if json_resp:
+ sql_header = "\n-- Partitions SQL"
+ partition_sql = ''
+ for row in rset['rows']:
+ part_data = dict()
+ part_data['partitioned_table_name'] = data['name']
+ part_data['parent_schema'] = data['schema']
+ part_data['spcname'] = row['spcname']
+ if not json_resp:
+ part_data['schema'] = data['schema']
+ else:
+ part_data['schema'] = row['schema_name']
+ part_data['relispartition'] = True
+ part_data['name'] = row['name']
+ part_data['partition_value'] = row['partition_value']
+ part_data['is_partitioned'] = row['is_partitioned']
+ part_data['partition_scheme'] = row['partition_scheme']
+ part_data['description'] = row['description']
+ part_data['relowner'] = row['relowner']
+ part_data['default_amname'] = data.get('default_amname')
+ part_data['amname'] = row.get('amname')
+
+ self.update_autovacuum_properties(row)
+
+ part_data['fillfactor'] = row['fillfactor']
+ part_data['autovacuum_custom'] = row['autovacuum_custom']
+ part_data['autovacuum_enabled'] = row['autovacuum_enabled']
+ part_data['autovacuum_vacuum_threshold'] = \
+ row['autovacuum_vacuum_threshold']
+ part_data['autovacuum_vacuum_scale_factor'] = \
+ row['autovacuum_vacuum_scale_factor']
+ part_data['autovacuum_analyze_threshold'] = \
+ row['autovacuum_analyze_threshold']
+ part_data['autovacuum_analyze_scale_factor'] = \
+ row['autovacuum_analyze_scale_factor']
+ part_data['autovacuum_vacuum_cost_delay'] = \
+ row['autovacuum_vacuum_cost_delay']
+ part_data['autovacuum_vacuum_cost_limit'] = \
+ row['autovacuum_vacuum_cost_limit']
+ part_data['autovacuum_freeze_min_age'] = \
+ row['autovacuum_freeze_min_age']
+ part_data['autovacuum_freeze_max_age'] = \
+ row['autovacuum_freeze_max_age']
+ part_data['autovacuum_freeze_table_age'] = \
+ row['autovacuum_freeze_table_age']
+ part_data['toast_autovacuum'] = row['toast_autovacuum']
+ part_data['toast_autovacuum_enabled'] = \
+ row['toast_autovacuum_enabled']
+ part_data['toast_autovacuum_vacuum_threshold'] = \
+ row['toast_autovacuum_vacuum_threshold']
+ part_data['toast_autovacuum_vacuum_scale_factor'] = \
+ row['toast_autovacuum_vacuum_scale_factor']
+ part_data['toast_autovacuum_analyze_threshold'] = \
+ row['toast_autovacuum_analyze_threshold']
+ part_data['toast_autovacuum_analyze_scale_factor'] = \
+ row['toast_autovacuum_analyze_scale_factor']
+ part_data['toast_autovacuum_vacuum_cost_delay'] = \
+ row['toast_autovacuum_vacuum_cost_delay']
+ part_data['toast_autovacuum_vacuum_cost_limit'] = \
+ row['toast_autovacuum_vacuum_cost_limit']
+ part_data['toast_autovacuum_freeze_min_age'] = \
+ row['toast_autovacuum_freeze_min_age']
+ part_data['toast_autovacuum_freeze_max_age'] = \
+ row['toast_autovacuum_freeze_max_age']
+ part_data['toast_autovacuum_freeze_table_age'] = \
+ row['toast_autovacuum_freeze_table_age']
+
+ # We will add Auto vacuum defaults with out result for grid
+ part_data['vacuum_table'] = \
+ copy.deepcopy(self.parse_vacuum_data(
+ self.conn, row, 'table'))
+ part_data['vacuum_toast'] = \
+ copy.deepcopy(self.parse_vacuum_data(
+ self.conn, row, 'toast'))
+
+ scid = row['schema_id']
+ schema = part_data['schema']
+ table = part_data['name']
+
+ # Get all the supported constraints for partition table
+ self._add_constrints_to_output(part_data, did, row['oid'])
+
+ partition_sql = render_template("/".join(
+ [self.partition_template_path, self._CREATE_SQL]),
+ data=part_data, conn=self.conn) + '\n'
+
+ partition_sql = re.sub(self.pattern, self.double_newline,
+ partition_sql).strip('\n')
+
+ partition_main_sql = partition_sql.strip('\n')
+
+ # Add into partition sql to partition array
+ partition_sql_arr.append(partition_main_sql)
+
+ # Get Reverse engineered sql for index
+ self._get_resql_for_index(did, row['oid'], partition_sql_arr,
+ json_resp, schema, table)
+
+ # Get Reverse engineered sql for ROW SECURITY POLICY
+ self._get_resql_for_row_security_policy(scid, row['oid'],
+ json_resp,
+ partition_sql_arr,
+ schema, table)
+
+ # Get Reverse engineered sql for Triggers
+ self._get_resql_for_triggers(row['oid'], json_resp,
+ partition_sql_arr, schema, table)
+
+ # Get Reverse engineered sql for Compound Triggers
+ self._get_resql_for_compound_triggers(row['oid'],
+ partition_sql_arr,
+ schema, table)
+
+ # Get Reverse engineered sql for Rules
+ self._get_resql_for_rules(row['oid'], partition_sql_arr, table,
+ json_resp)
+
+ if not diff_partition_sql:
+ main_sql.append(sql_header + '\n')
+ main_sql += partition_sql_arr
+
+ def get_reverse_engineered_sql(self, **kwargs):
+ """
+ This function will creates reverse engineered sql for
+ the table object
+
+ Args:
+ kwargs
+ """
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ tid = kwargs.get('tid')
+ main_sql = kwargs.get('main_sql')
+ data = kwargs.get('data')
+ json_resp = kwargs.get('json_resp', True)
+ diff_partition_sql = kwargs.get('diff_partition_sql', False)
+ if_exists_flag = kwargs.get('add_not_exists_clause', False)
+
+ # Table & Schema declaration so that we can use them in child nodes
+ schema = data['schema']
+ table = data['name']
+ is_partitioned = 'is_partitioned' in data and data['is_partitioned']
+
+ # Get Reverse engineered sql for Table
+ self._get_resql_for_table(did, scid, tid, data, json_resp, main_sql,
+ add_not_exists_clause=if_exists_flag)
+ # Get Reverse engineered sql for Table
+ self._get_resql_for_index(did, tid, main_sql, json_resp, schema,
+ table, add_not_exists_clause=if_exists_flag)
+
+ # Get Reverse engineered sql for ROW SECURITY POLICY
+ self._get_resql_for_row_security_policy(scid, tid, json_resp,
+ main_sql, schema, table)
+
+ # Get Reverse engineered sql for Triggers
+ self._get_resql_for_triggers(tid, json_resp, main_sql, schema, table)
+
+ # Get Reverse engineered sql for Compound Triggers
+ self._get_resql_for_compound_triggers(tid, main_sql, schema, table)
+
+ # Get Reverse engineered sql for Rules
+ self._get_resql_for_rules(tid, main_sql, table, json_resp)
+
+ # Get Reverse engineered sql for Partitions
+ partition_main_sql = ""
+ if is_partitioned:
+ sql = render_template("/".join([self.partition_template_path,
+ self._NODES_SQL]),
+ scid=scid, tid=tid, did=did)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ self._get_resql_for_partitions(data, rset, json_resp,
+ diff_partition_sql, main_sql, did)
+
+ sql = '\n'.join(main_sql)
+
+ if not json_resp:
+ return sql, partition_main_sql
+ return ajax_response(response=sql.strip('\n'))
+
+ def reset_statistics(self, scid, tid):
+ """
+ This function will reset statistics of table
+
+ Args:
+ scid: Schema ID
+ tid: Table ID
+ """
+ # checking the table existence using the function of the same class
+ _, table_name = self.get_schema_and_table_name(tid)
+
+ if table_name is None:
+ return gone(gettext(self.not_found_error_msg()))
+
+ # table exist
+ try:
+ sql = render_template("/".join([self.table_template_path,
+ 'reset_stats.sql']),
+ tid=tid)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Table statistics have been reset"),
+ data={
+ 'id': tid,
+ 'scid': scid
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def get_partition_scheme(self, data):
+ partition_scheme = None
+ part_type = 'sub_partition_type' if 'sub_partition_type' in data \
+ else 'partition_type'
+ part_keys = 'sub_partition_keys' if 'sub_partition_keys' in data \
+ else 'partition_keys'
+
+ if part_type in data and data[part_type] == 'range':
+ partition_scheme = 'RANGE ('
+ elif part_type in data and data[part_type] == 'list':
+ partition_scheme = 'LIST ('
+ elif part_type in data and data[part_type] == 'hash':
+ partition_scheme = 'HASH ('
+
+ for row in data.get(part_keys, []):
+ if row['key_type'] == 'column':
+ partition_scheme += self.qtIdent(
+ self.conn, row['pt_column'])
+ if 'collationame' in row and row['collationame']:
+ partition_scheme += ' COLLATE %s' % row['collationame']
+
+ if 'op_class' in row:
+ partition_scheme += ' %s' % row['op_class']
+
+ partition_scheme += ', '
+
+ elif row['key_type'] == 'expression':
+ partition_scheme += row['expression'] + ', '
+
+ # Remove extra space and comma
+ if len(data.get(part_keys, [])) > 0:
+ partition_scheme = partition_scheme[:-2]
+ partition_scheme += ')'
+
+ return partition_scheme
+
+ @staticmethod
+ def validate_constrains(key, data):
+ """
+ This function is used to validate the constraints.
+ :param key:
+ :param data:
+ :return:
+ """
+ if key == 'primary_key' or key == 'unique_constraint':
+ if 'columns' in data and len(data['columns']) > 0:
+ return True
+ else:
+ return False
+ elif key == 'foreign_key':
+ return BaseTableView._check_foreign_key(data)
+ elif key == 'check_constraint':
+ return BaseTableView._check_constraint(data)
+
+ return True
+
+ @staticmethod
+ def _check_foreign_key(data):
+ if 'oid' not in data:
+ for arg in ['columns']:
+ if arg not in data or \
+ (isinstance(data[arg], list) and
+ len(data[arg]) < 1):
+ return False
+
+ if 'autoindex' in data and \
+ data['autoindex'] and \
+ ('coveringindex' not in data or
+ data['coveringindex'] == ''):
+ return False
+
+ return True
+
+ @staticmethod
+ def _check_constraint(data):
+ for arg in ['consrc']:
+ if arg not in data or data[arg] == '':
+ return False
+ return True
+
+ @staticmethod
+ def check_and_convert_name_to_string(data):
+ """
+ This function will check and covert table to string incase
+ it is numeric
+
+ Args:
+ data: data dict
+
+ Returns:
+ Updated data dict
+ """
+ if isinstance(data['name'], (int, float)):
+ data['name'] = str(data['name'])
+
+ return data
+
+ def _get_privileges_from_client(self, data):
+ # We will convert privileges coming from client required
+ if 'relacl' in data:
+ for mode in ['added', 'changed', 'deleted']:
+ if mode in data['relacl']:
+ data['relacl'][mode] = parse_priv_to_db(
+ data['relacl'][mode], self.acl
+ )
+
+ @staticmethod
+ def _filter_new_tables(data, old_data):
+ # Filter out new tables from list, we will send complete list
+ # and not newly added tables in the list from client
+ # so we will filter new tables here
+ if 'coll_inherits' in data:
+ p_len = len(old_data['coll_inherits'])
+ c_len = len(data['coll_inherits'])
+ # If table(s) added
+ if c_len > p_len:
+ data['coll_inherits_added'] = list(
+ set(data['coll_inherits']) -
+ set(old_data['coll_inherits'])
+ )
+ # If table(s)removed
+ elif c_len < p_len:
+ data['coll_inherits_removed'] = list(
+ set(old_data['coll_inherits']) -
+ set(data['coll_inherits'])
+ )
+ # Safe side verification,In case it happens..
+ # If user removes and adds same number of table
+ # eg removed one table and added one new table
+ elif c_len == p_len:
+ data['coll_inherits_added'] = list(
+ set(data['coll_inherits']) -
+ set(old_data['coll_inherits'])
+ )
+ data['coll_inherits_removed'] = list(
+ set(old_data['coll_inherits']) -
+ set(data['coll_inherits'])
+ )
+
+ def _check_for_column_delete(self, columns, data, column_sql):
+ # If column(s) is/are deleted
+ if 'deleted' in columns:
+ for c in columns['deleted']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+ # Sql for drop column
+ if c.get('inheritedfrom', None) is None:
+ column_sql += render_template("/".join(
+ [self.column_template_path, self._DELETE_SQL]),
+ data=c, conn=self.conn).strip('\n') + \
+ self.double_newline
+ return column_sql
+
+ def _check_for_column_update(self, columns, data, column_sql, tid):
+ # Here we will be needing previous properties of column
+ # so that we can compare & update it
+ if 'changed' in columns:
+ for c in columns['changed']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ properties_sql = render_template(
+ "/".join([self.column_template_path,
+ self._PROPERTIES_SQL]),
+ tid=tid,
+ clid=c['attnum'] if 'attnum' in c else None,
+ show_sys_objects=self.blueprint.show_system_objects
+ )
+
+ status, res = self.conn.execute_dict(properties_sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+ old_col_data = res['rows'][0]
+
+ old_col_data['cltype'], \
+ old_col_data['hasSqrBracket'] = \
+ column_utils.type_formatter(old_col_data['cltype'])
+ old_col_data = \
+ column_utils.convert_length_precision_to_string(
+ old_col_data)
+ old_col_data = column_utils.fetch_length_precision(
+ old_col_data)
+
+ old_col_data['cltype'] = \
+ DataTypeReader.parse_type_name(
+ old_col_data['cltype'])
+
+ # Sql for alter column
+ if c.get('inheritedfrom', None) is None and \
+ c.get('inheritedfromtable', None) is None:
+ column_sql += render_template("/".join(
+ [self.column_template_path, self._UPDATE_SQL]),
+ data=c, o_data=old_col_data, conn=self.conn
+ ).strip('\n') + self.double_newline
+ return column_sql
+
+ def _check_for_column_add(self, columns, data, column_sql):
+ # If column(s) is/are added
+ if 'added' in columns:
+ for c in columns['added']:
+ c['schema'] = data['schema']
+ c['table'] = data['name']
+
+ c = column_utils.convert_length_precision_to_string(c)
+
+ if c.get('inheritedfrom', None) is None and \
+ c.get('inheritedfromtable', None) is None:
+ column_sql += render_template("/".join(
+ [self.column_template_path, self._CREATE_SQL]),
+ data=c, conn=self.conn).strip('\n') + \
+ self.double_newline
+ return column_sql
+
+ def _check_for_partitions_in_sql(self, data, old_data, sql):
+ # Check for partitions
+ if 'partitions' in data:
+ partitions = data['partitions']
+ partitions_sql = '\n'
+
+ # If partition(s) is/are deleted
+ if 'deleted' in partitions:
+ for row in partitions['deleted']:
+ temp_data = dict()
+ schema_name, table_name = \
+ self.get_schema_and_table_name(row['oid'])
+
+ temp_data['parent_schema'] = data['schema']
+ temp_data['partitioned_table_name'] = data['name']
+ temp_data['schema'] = schema_name
+ temp_data['name'] = table_name
+
+ # Sql for detach partition
+ partitions_sql += render_template(
+ "/".join(
+ [
+ self.partition_template_path,
+ 'detach.sql'
+ ]
+ ),
+ data=temp_data,
+ conn=self.conn).strip('\n') + self.double_newline
+
+ # If partition(s) is/are added
+ if 'added' in partitions and 'partition_scheme' in old_data \
+ and old_data['partition_scheme'] != '':
+ temp_data = dict()
+ temp_data['schema'] = data['schema']
+ temp_data['name'] = data['name']
+ # get the partition type
+ temp_data['partition_type'] = \
+ old_data['partition_scheme'].split()[0].lower()
+ temp_data['partitions'] = partitions['added']
+
+ partitions_sql += \
+ self.get_partitions_sql(temp_data).strip('\n') + \
+ self.double_newline
+
+ # Combine all the SQL together
+ sql += '\n' + partitions_sql.strip('\n')
+ return sql
+
+ def _check_for_constraints(self, index_constraint_sql, data, did,
+ tid, sql):
+ # If we have index constraint sql then ad it in main sql
+ if index_constraint_sql is not None:
+ sql += '\n' + index_constraint_sql
+
+ # Check if foreign key(s) is/are added/changed/deleted
+ foreign_key_sql = fkey_utils.get_foreign_key_sql(
+ self.conn, tid, data)
+ # If we have foreign key sql then ad it in main sql
+ if foreign_key_sql is not None:
+ sql += '\n' + foreign_key_sql
+
+ # Check if check constraint(s) is/are added/changed/deleted
+ check_constraint_sql = check_utils.get_check_constraint_sql(
+ self.conn, tid, data)
+ # If we have check constraint sql then ad it in main sql
+ if check_constraint_sql is not None:
+ sql += '\n' + check_constraint_sql
+
+ # Check if exclusion constraint(s) is/are added/changed/deleted
+ exclusion_constraint_sql = \
+ exclusion_utils.get_exclusion_constraint_sql(
+ self.conn, did, tid, data)
+ # If we have check constraint sql then ad it in main sql
+ if exclusion_constraint_sql is not None:
+ sql += '\n' + exclusion_constraint_sql
+ return sql
+
+ def _check_fk_constraint(self, data):
+ if 'foreign_key' in data:
+ for c in data['foreign_key']:
+ schema, table = fkey_utils.get_parent(
+ self.conn, c['columns'][0]['references'])
+ c['remote_schema'] = schema
+ c['remote_table'] = table
+
+ def _check_for_partitioned(self, data):
+ partitions_sql = ''
+ if 'is_partitioned' in data and data['is_partitioned']:
+ data['relkind'] = 'p'
+ # create partition scheme
+ data['partition_scheme'] = self.get_partition_scheme(data)
+ partitions_sql = self.get_partitions_sql(data)
+ return partitions_sql
+
+ def _validate_constraint_data(self, data):
+ # validate constraint data.
+ for key in ['primary_key', 'unique_constraint',
+ 'foreign_key', 'check_constraint',
+ 'exclude_constraint']:
+ if key in data and len(data[key]) > 0:
+ for constraint in data[key]:
+ if not self.validate_constrains(key, constraint):
+ return gettext(
+ '-- definition incomplete for {0}'.format(key)
+ )
+
+ @staticmethod
+ def _check_for_create_sql(data):
+ required_args = [
+ 'name'
+ ]
+ for arg in required_args:
+ if arg not in data:
+ return True, '-- definition incomplete'
+ return False, ''
+
+ def _convert_privilege_to_server_format(self, data):
+ # We will convert privileges coming from client required
+ # in server side format
+ if 'relacl' in data:
+ data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)
+
+ def get_sql(self, did, scid, tid, data, res, add_not_exists_clause=False,
+ with_drop=False):
+ """
+ This function will generate create/update sql from model data
+ coming from client
+ """
+ if tid is not None:
+ old_data = res['rows'][0]
+ old_data = self._formatter(did, scid, tid, old_data)
+
+ self._get_privileges_from_client(data)
+
+ # If name is not present in request data
+ if 'name' not in data:
+ data['name'] = old_data['name']
+
+ data = BaseTableView.check_and_convert_name_to_string(data)
+
+ # If name if not present
+ if 'schema' not in data:
+ data['schema'] = old_data['schema']
+
+ self._filter_new_tables(data, old_data)
+
+ # Update the vacuum table settings.
+ self.update_vacuum_settings('vacuum_table', old_data, data)
+ # Update the vacuum toast table settings.
+ self.update_vacuum_settings('vacuum_toast', old_data, data)
+
+ sql = render_template(
+ "/".join([self.table_template_path, self._UPDATE_SQL]),
+ o_data=old_data, data=data, conn=self.conn
+ )
+ # Removes training new lines
+ sql = sql.strip('\n') + self.double_newline
+
+ # Parse/Format columns & create sql
+ if 'columns' in data:
+ # Parse the data coming from client
+ data = column_utils.parse_format_columns(data, mode='edit')
+
+ columns = data['columns']
+ column_sql = '\n'
+
+ # If column(s) is/are deleted
+ column_sql = self._check_for_column_delete(columns, data,
+ column_sql)
+
+ # If column(s) is/are changed
+ column_sql = self._check_for_column_update(columns, data,
+ column_sql, tid)
+
+ # If column(s) is/are added
+ column_sql = self._check_for_column_add(columns, data,
+ column_sql)
+
+ # Combine all the SQL together
+ sql += column_sql.strip('\n')
+
+ # Check for partitions
+ sql = self._check_for_partitions_in_sql(data, old_data, sql)
+
+ data['columns_to_be_dropped'] = []
+ if 'columns' in data and 'deleted' in data['columns']:
+ data['columns_to_be_dropped'] = list(map(
+ lambda d: d['name'], data['columns']['deleted']))
+
+ # Check if index constraints are added/changed/deleted
+ index_constraint_sql = \
+ idxcons_utils.get_index_constraint_sql(
+ self.conn, did, tid, data)
+
+ sql = self._check_for_constraints(index_constraint_sql, data, did,
+ tid, sql)
+ else:
+ error, _ = BaseTableView._check_for_create_sql(data)
+ if error:
+ return gettext('-- definition incomplete'), data['name']
+
+ # validate constraint data.
+ self._validate_constraint_data(data)
+ # We will convert privileges coming from client required
+ # in server side format
+ self._convert_privilege_to_server_format(data)
+
+ # Parse & format columns
+ data = column_utils.parse_format_columns(data)
+ data = BaseTableView.check_and_convert_name_to_string(data)
+
+ self._check_fk_constraint(data)
+
+ partitions_sql = self._check_for_partitioned(data)
+
+ # Update the vacuum table settings.
+ self.update_vacuum_settings('vacuum_table', data)
+ # Update the vacuum toast table settings.
+ self.update_vacuum_settings('vacuum_toast', data)
+
+ sql = ''
+ if with_drop:
+ sql = self.get_delete_sql(data) + '\n\n'
+
+ sql += render_template("/".join([self.table_template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn,
+ add_not_exists_clause=add_not_exists_clause)
+
+ # Append SQL for partitions
+ sql += '\n' + partitions_sql
+
+ sql = re.sub(self.pattern, self.double_newline, sql)
+ sql = sql.strip('\n')
+
+ return sql, data['name'] if 'name' in data else old_data['name']
+
+ def update(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will update an existing table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ data: Data to update
+ res: Table properties
+ parent_id: parent table id if current table is partition of parent
+ table else none
+ """
+ data = kwargs.get('data')
+ res = kwargs.get('res')
+ parent_id = kwargs.get('parent_id', None)
+
+ # checking the table existence using the function of the same class
+ _, table_name = self.get_schema_and_table_name(tid)
+
+ if table_name is None:
+ return gone(gettext(self.not_found_error_msg()))
+
+ # table exists
+ try:
+ sql, name = self.get_sql(did, scid, tid, data, res)
+
+ sql = sql.strip('\n').strip(' ')
+ status, rest = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=rest)
+
+ sql = render_template("/".join([self.table_template_path,
+ self._GET_SCHEMA_OID_SQL]), tid=tid,
+ conn=self.conn)
+ status, rest = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rest)
+
+ if not parent_id:
+ parent_id = scid
+
+ # Check for partitions
+ partitions_oid = dict()
+ is_partitioned = self._check_for_partitions(data, partitions_oid,
+ res, scid)
+
+ # If partitioned_table_name in result set then get partition
+ # icon css class else table icon.
+ if 'partitioned_table_name' in res['rows'][0]:
+ res['rows'][0]['is_sub_partitioned'] = is_partitioned
+ icon = self.get_partition_icon_css_class(res['rows'][0])
+ else:
+ icon = self.get_icon_css_class(res['rows'][0])
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ parent_id,
+ name,
+ icon=icon,
+ is_partitioned=is_partitioned,
+ parent_schema_id=scid,
+ schema_id=rest['rows'][0]['scid'],
+ schema_name=rest['rows'][0]['nspname'],
+ affected_partitions=partitions_oid,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _check_for_partitions(self, data, partitions_oid, res, scid):
+ if 'partitions' in data:
+ # Fetch oid of schema for all detached partitions
+ if 'deleted' in data['partitions']:
+ detached = []
+ for row in data['partitions']['deleted']:
+ status, pscid = self.conn.execute_scalar(
+ render_template(
+ "/".join([
+ self.table_template_path,
+ self._GET_SCHEMA_OID_SQL
+ ]),
+ tid=row['oid'],
+ conn=self.conn
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=pscid)
+
+ detached.append(
+ {'oid': row['oid'], 'schema_id': pscid}
+ )
+ partitions_oid['detached'] = detached
+
+ self._fetch_oid_schema_iod(data, scid, partitions_oid)
+
+ if 'is_partitioned' in res['rows'][0]:
+ is_partitioned = res['rows'][0]['is_partitioned']
+ else:
+ is_partitioned = False
+
+ return is_partitioned
+
+ def _fetch_oid_schema_iod(self, data, scid, partitions_oid):
+ # Fetch oid and schema oid for all created/attached partitions
+ if 'added' in data['partitions']:
+ created = []
+ attached = []
+ for row in data['partitions']['added']:
+ if row['is_attach']:
+ status, pscid = self.conn.execute_scalar(
+ render_template(
+ "/".join([
+ self.table_template_path,
+ self._GET_SCHEMA_OID_SQL
+ ]),
+ tid=row['partition_name'],
+ conn=self.conn
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=pscid)
+
+ attached.append({
+ 'oid': row['partition_name'],
+ 'schema_id': pscid
+ })
+
+ else:
+ tmp_data = dict()
+ tmp_data['name'] = row['partition_name']
+ sql = render_template(
+ "/".join([
+ self.table_template_path, self._OID_SQL
+ ]),
+ scid=scid, data=tmp_data, conn=self.conn
+ )
+
+ status, ptid = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=ptid)
+
+ created.append({
+ 'oid': ptid,
+ 'schema_id': scid
+ })
+
+ partitions_oid['created'] = created
+ partitions_oid['attached'] = attached
+
+ def properties(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will show the properties of the selected table node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Table ID
+
+ Returns:
+ JSON of selected table node
+ """
+ res = kwargs.get('res')
+ return_ajax_response = kwargs.get('return_ajax_response', True)
+ with_serial_cols = kwargs.get('with_serial_cols', False)
+
+ data = res['rows'][0]
+
+ data['vacuum_settings_str'] = ''
+
+ if data['reloptions'] is not None:
+ data['vacuum_settings_str'] += '\n'.join(data['reloptions'])
+
+ if data['toast_reloptions'] is not None:
+ data['vacuum_settings_str'] += '\n' \
+ if data['vacuum_settings_str'] != '' else ''
+ data['vacuum_settings_str'] += '\n'.\
+ join(map(lambda o: 'toast.' + o, data['toast_reloptions']))
+
+ data['vacuum_settings_str'] = data[
+ 'vacuum_settings_str'
+ ].replace('=', ' = ')
+
+ data = self._formatter(did, scid, tid, data,
+ with_serial_cols=with_serial_cols)
+
+ # Fetch partition of this table if it is partitioned table.
+ if 'is_partitioned' in data and data['is_partitioned']:
+ # get the partition type
+ data['partition_type'] = \
+ data['partition_scheme'].split()[0].lower()
+
+ partitions = []
+ sql = render_template("/".join([self.partition_template_path,
+ self._NODES_SQL]),
+ scid=scid, tid=tid, did=did)
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ partition_name = row['name']
+ # if schema name is different then display schema
+ # qualified name on UI.
+ if data['schema'] != row['schema_name']:
+ partition_name = row['schema_name'] + '.' + row['name']
+
+ BaseTableView._partition_type_check(data, row, partitions,
+ partition_name)
+
+ data['partitions'] = partitions
+
+ if not return_ajax_response:
+ return data
+
+ return ajax_response(
+ response=data,
+ status=200
+ )
+
+ @staticmethod
+ def _partition_type_check(data, row, partitions, partition_name):
+ if data['partition_type'] == 'range':
+ if row['partition_value'] == 'DEFAULT':
+ is_default = True
+ range_from = None
+ range_to = None
+ else:
+ range_part = row['partition_value'].split(
+ 'FOR VALUES FROM (')[1].split(') TO')
+ range_from = range_part[0]
+ range_to = range_part[1][2:-1]
+ is_default = False
+
+ partitions.append({
+ 'oid': row['oid'],
+ 'partition_name': partition_name,
+ 'values_from': range_from,
+ 'values_to': range_to,
+ 'is_default': is_default,
+ 'is_sub_partitioned': row['is_sub_partitioned'],
+ 'sub_partition_scheme': row['sub_partition_scheme'],
+ 'amname': row.get('amname', '')
+ })
+ elif data['partition_type'] == 'list':
+ if row['partition_value'] == 'DEFAULT':
+ is_default = True
+ range_in = None
+ else:
+ range_part = row['partition_value'].split(
+ 'FOR VALUES IN (')[1]
+ range_in = range_part[:-1]
+ is_default = False
+
+ partitions.append({
+ 'oid': row['oid'],
+ 'partition_name': partition_name,
+ 'values_in': range_in,
+ 'is_default': is_default,
+ 'is_sub_partitioned': row['is_sub_partitioned'],
+ 'sub_partition_scheme': row['sub_partition_scheme'],
+ 'amname': row.get('amname', '')
+ })
+ else:
+ range_part = row['partition_value'].split(
+ 'FOR VALUES WITH (')[1].split(",")
+ range_modulus = range_part[0].strip().strip(
+ "modulus").strip()
+ range_remainder = range_part[1].strip(). \
+ strip(" remainder").strip(")").strip()
+
+ partitions.append({
+ 'oid': row['oid'],
+ 'partition_name': partition_name,
+ 'values_modulus': range_modulus,
+ 'values_remainder': range_remainder,
+ 'is_sub_partitioned': row['is_sub_partitioned'],
+ 'sub_partition_scheme': row['sub_partition_scheme'],
+ 'amname': row.get('amname', '')
+ })
+
+ def get_partitions_sql(self, partitions, schema_diff=False):
+ """
+ This function will iterate all the partitions and create SQL.
+
+ :param partitions: List of partitions
+ :param schema_diff: If true then create sql accordingly.
+ """
+ sql = ''
+
+ for row in partitions['partitions']:
+ part_data = dict()
+ part_data['partitioned_table_name'] = partitions['name']
+ part_data['parent_schema'] = partitions['schema']
+ part_data['amname'] = row.get('amname')
+
+ if 'is_attach' in row and row['is_attach']:
+ schema_name, table_name = \
+ self.get_schema_and_table_name(row['partition_name'])
+
+ part_data['schema'] = schema_name
+ part_data['name'] = table_name
+ else:
+ part_data['schema'] = partitions['schema']
+ part_data['relispartition'] = True
+ part_data['name'] = row['partition_name']
+
+ if 'is_default' in row and row['is_default'] and (
+ partitions['partition_type'] == 'range' or
+ partitions['partition_type'] == 'list'):
+ part_data['partition_value'] = 'DEFAULT'
+ elif partitions['partition_type'] == 'range':
+ range_from = row['values_from'].split(',')
+ range_to = row['values_to'].split(',')
+
+ from_str = ', '.join("{0}".format(item) for
+ item in range_from)
+ to_str = ', '.join("{0}".format(item) for
+ item in range_to)
+
+ part_data['partition_value'] = 'FOR VALUES FROM (' +\
+ from_str + ') TO (' +\
+ to_str + ')'
+
+ elif partitions['partition_type'] == 'list':
+ range_in = row['values_in'].split(',')
+ in_str = ', '.join("{0}".format(item) for item in range_in)
+ part_data['partition_value'] = 'FOR VALUES IN (' + in_str\
+ + ')'
+
+ else:
+ range_modulus = row['values_modulus'].split(',')
+ range_remainder = row['values_remainder'].split(',')
+
+ modulus_str = ', '.join("{0}".format(item) for item in
+ range_modulus)
+ remainder_str = ', '.join("{0}".format(item) for item in
+ range_remainder)
+
+ part_data['partition_value'] = 'FOR VALUES WITH (MODULUS '\
+ + modulus_str \
+ + ', REMAINDER ' +\
+ remainder_str + ')'
+
+ partition_sql = self._check_for_partitioned_table(row, part_data,
+ schema_diff)
+
+ sql += partition_sql
+
+ return sql
+
+ def _check_for_partitioned_table(self, row, part_data, schema_diff):
+ # Check if partition is again declare as partitioned table.
+ if 'is_sub_partitioned' in row and row['is_sub_partitioned']:
+ part_data['partition_scheme'] = row['sub_partition_scheme'] \
+ if 'sub_partition_scheme' in row else \
+ self.get_partition_scheme(row)
+
+ part_data['is_partitioned'] = True
+
+ if 'is_attach' in row and row['is_attach']:
+ partition_sql = render_template(
+ "/".join([self.partition_template_path, 'attach.sql']),
+ data=part_data, conn=self.conn
+ )
+ else:
+ # For schema diff we create temporary partitions to copy the
+ # data from original table to temporary table.
+ if schema_diff:
+ part_data['name'] = row['temp_partition_name']
+
+ partition_sql = render_template(
+ "/".join([self.partition_template_path, self._CREATE_SQL]),
+ data=part_data, conn=self.conn
+ )
+
+ return partition_sql
+
+ def truncate(self, gid, sid, did, scid, tid, res):
+ """
+ This function will truncate the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+ # Below will decide if it's simple drop or drop with cascade call
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ # Convert str 'true' to boolean type
+ is_cascade = data.get('cascade') or False
+ is_identity = data.get('identity') or False
+
+ data = res['rows'][0]
+
+ lock_on_table = self.get_table_locks(did, data)
+ if lock_on_table != '':
+ return lock_on_table
+
+ sql = render_template("/".join([self.table_template_path,
+ 'truncate.sql']),
+ data=data, cascade=is_cascade,
+ identity=is_identity)
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Table truncated"),
+ data={
+ 'id': tid,
+ 'scid': scid
+ }
+ )
+
+ def get_delete_sql(self, data):
+ # Below will decide if it's simple drop or drop with cascade call
+ cascade = self._check_cascade_operation()
+
+ return render_template(
+ "/".join([self.table_template_path, self._DELETE_SQL]),
+ data=data, cascade=cascade,
+ conn=self.conn
+ )
+
+ def delete(self, gid, sid, did, scid, tid, res):
+ """
+ This function will delete the table object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Table ID
+ """
+
+ sql = self.get_delete_sql(res['rows'][0])
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return status, res
+
+ return True, {
+ 'id': tid,
+ 'scid': scid
+ }
+
+ def get_table_locks(self, did, data):
+ """
+ This function returns the lock details if there is any on table
+ :param did:
+ :param data:
+ :return:
+ """
+ sql = render_template(
+ "/".join([self.table_template_path, 'locks.sql']), did=did
+ )
+ _, lock_table_result = self.conn.execute_dict(sql)
+
+ for row in lock_table_result['rows']:
+ if row['relation'] and \
+ row['relation'].strip('\"') == data['name']:
+
+ sql = render_template(
+ "/".join([self.table_template_path,
+ 'get_application_name.sql']), pid=row['pid']
+ )
+ _, res = self.conn.execute_dict(sql)
+
+ application_name = res['rows'][0]['application_name']
+
+ return make_json_response(
+ success=2,
+ info=gettext(
+ "The table is currently locked and the "
+ "operation cannot be completed. "
+ "Please try again later. "
+ "\r\nBlocking Process ID : {0} "
+ "Application Name : {1}").format(row['pid'],
+ application_name)
+ )
+ return ''
+
+ def get_schema_and_table_name(self, tid):
+ """
+ This function will fetch the schema qualified name of the
+ given table id.
+
+ :param tid: Table Id.
+ """
+ # Get schema oid
+ status, scid = self.conn.execute_scalar(
+ render_template("/".join([self.table_template_path,
+ self._GET_SCHEMA_OID_SQL]),
+ tid=tid,
+ conn=self.conn))
+ if not status:
+ return internal_server_error(errormsg=scid)
+ if scid is None:
+ return None, None
+
+ # Fetch schema name
+ status, schema_name = self.conn.execute_scalar(
+ render_template("/".join([self.table_template_path,
+ 'get_schema.sql']), conn=self.conn,
+ scid=scid)
+ )
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ # Fetch Table name
+ status, table_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.table_template_path, 'get_table.sql']),
+ conn=self.conn, scid=scid, tid=tid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=table_name)
+
+ return schema_name, table_name
+
+ def update_vacuum_settings(self, vacuum_key, old_data, data=None):
+ """
+ This function iterate the vacuum and vacuum toast table and create
+ two new dictionaries. One for set parameter and another for reset.
+
+ :param vacuum_key: Key to be checked.
+ :param old_data: Old data
+ :param data: New data
+ :return:
+ """
+
+ # When creating a table old_data is the actual data
+ if data is None:
+ if vacuum_key in old_data:
+ for opt in old_data[vacuum_key]:
+ if 'add_vacuum_settings_in_sql' not in old_data:
+ old_data['add_vacuum_settings_in_sql'] = False
+
+ if ('value' in opt and opt['value'] is None) or \
+ ('value' in opt and opt['value'] == ''):
+ opt.pop('value')
+
+ if 'value' in opt and 'add_vacuum_settings_in_sql' in \
+ old_data and not \
+ old_data['add_vacuum_settings_in_sql']:
+ old_data['add_vacuum_settings_in_sql'] = True
+
+ # Iterate vacuum table
+ elif vacuum_key in data and 'changed' in data[vacuum_key] \
+ and vacuum_key in old_data:
+ set_values = []
+ reset_values = []
+ self._iterate_vacuume_table(data, old_data, set_values,
+ reset_values, vacuum_key)
+
+ def _iterate_vacuume_table(self, data, old_data, set_values, reset_values,
+ vacuum_key):
+ for data_row in data[vacuum_key]['changed']:
+ for old_data_row in old_data[vacuum_key]:
+ if data_row['name'] == old_data_row['name'] and \
+ 'value' in data_row:
+ if data_row['value'] is not None and \
+ data_row['value'] != '':
+ set_values.append(data_row)
+ elif 'value' in old_data_row:
+ reset_values.append(data_row)
+
+ if len(set_values) > 0:
+ data[vacuum_key]['set_values'] = set_values
+
+ if len(reset_values) > 0:
+ data[vacuum_key]['reset_values'] = reset_values
+
+ def update_autovacuum_properties(self, res):
+ """
+ This function sets the appropriate value for autovacuum_enabled and
+ autovacuum_custom for table & toast table both.
+ :param res:
+ :return:
+ """
+ # Set value based on
+ # x: No set, t: true, f: false
+ if res is not None:
+ res['autovacuum_enabled'] = 'x' \
+ if res['autovacuum_enabled'] is None else \
+ {True: 't', False: 'f'}[res['autovacuum_enabled']]
+ res['toast_autovacuum_enabled'] = 'x' \
+ if res['toast_autovacuum_enabled'] is None else \
+ {True: 't', False: 'f'}[
+ res['toast_autovacuum_enabled']]
+ # Enable custom autovaccum only if one of the options is set
+ # or autovacuum is set
+ res['autovacuum_custom'] = any([
+ res['autovacuum_vacuum_threshold'],
+ res['autovacuum_vacuum_scale_factor'],
+ res['autovacuum_analyze_threshold'],
+ res['autovacuum_analyze_scale_factor'],
+ res['autovacuum_vacuum_cost_delay'],
+ res['autovacuum_vacuum_cost_limit'],
+ res['autovacuum_freeze_min_age'],
+ res['autovacuum_freeze_max_age'],
+ res['autovacuum_freeze_table_age']]) or \
+ res['autovacuum_enabled'] in ('t', 'f')
+
+ res['toast_autovacuum'] = any([
+ res['toast_autovacuum_vacuum_threshold'],
+ res['toast_autovacuum_vacuum_scale_factor'],
+ res['toast_autovacuum_analyze_threshold'],
+ res['toast_autovacuum_analyze_scale_factor'],
+ res['toast_autovacuum_vacuum_cost_delay'],
+ res['toast_autovacuum_vacuum_cost_limit'],
+ res['toast_autovacuum_freeze_min_age'],
+ res['toast_autovacuum_freeze_max_age'],
+ res['toast_autovacuum_freeze_table_age']]) or \
+ res['toast_autovacuum_enabled'] in ('t', 'f')
+
+ def get_access_methods(self):
+ """
+ This function returns the access methods for table
+ """
+
+ res = []
+ sql = render_template("/".join([self.table_template_path,
+ 'get_access_methods.sql']))
+
+ status, rest = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rest)
+
+ for row in rest['rows']:
+ res.append(
+ {'label': row['amname'], 'value': row['amname']}
+ )
+
+ return res
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c41e3137359af0c9a757459250eba2346d538652
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/acl.sql
@@ -0,0 +1,23 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7cd2aaa4e0a0849d25000baf0e3b9c5002fbdcf9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/create.sql
@@ -0,0 +1,17 @@
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% if data %}
+CREATE SCHEMA {{ conn|qtIdent(data.name) }}
+{% if data.namespaceowner %}
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{% if data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f15d3c177ad2db239169df7aac99836179d888bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.1_plus/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c41e3137359af0c9a757459250eba2346d538652
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/acl.sql
@@ -0,0 +1,23 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f15d3c177ad2db239169df7aac99836179d888bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/9.2_plus/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..1253e87dcdd7bbab46af65d65c3eaac7e15c5ef9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/allowed_privs.json
@@ -0,0 +1,30 @@
+{# List of allowed privileges for PostgreSQL 9.2 or later #}
+{#
+ Format for allowed privileges is:
+ "acl_col": {
+ "type": "name",
+ "acl": [...]
+ }
+#}
+{
+ "nspacl": {
+ "type": "DATABASE",
+ "acl": ["c", "C", "T"]
+ },
+ "deftblacl": {
+ "type": "TABLE",
+ "acl": ["r", "a", "w", "d", "D", "x", "t"]
+ },
+ "defseqacl": {
+ "type": "SEQUENCE",
+ "acl": ["U", "r", "w"]
+ },
+ "deffuncacl": {
+ "type": "FUNCTION",
+ "acl": ["X"]
+ },
+ "deftypeacl": {
+ "type": "TYPE",
+ "acl": ["U"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89136c7df8f17224482e1ba6108ed2a89e480b22
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/acl.sql
@@ -0,0 +1,24 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d55e2aac0f8275e9c0bdca919604de1746678907
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/create.sql
@@ -0,0 +1,17 @@
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% if data %}
+CREATE SCHEMA{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.name) }}
+{% if data.namespaceowner %}
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{% if data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f15d3c177ad2db239169df7aac99836179d888bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e9edaec48c5358e0f509d4290b3c0efbc776e6b6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/nodes.sql
@@ -0,0 +1,19 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.oid,
+{{ CATALOGS.LABELS('nsp', _) }},
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') as can_create,
+ pg_catalog.has_schema_privilege(nsp.oid, 'USAGE') as has_usage,
+ des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% endif %}
+ (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ORDER BY 2;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..897e762547e2d6ce4eb9598c63bd102623e68345
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/properties.sql
@@ -0,0 +1,25 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ 2 AS nsptyp,
+ nsp.nspname AS name,
+ nsp.oid,
+ pg_catalog.array_to_string(nsp.nspacl::text[], ', ') as acl,
+ r.rolname AS namespaceowner, description,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') AS can_create,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'r' AND defaclnamespace = nsp.oid) AS tblacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'S' AND defaclnamespace = nsp.oid) AS seqacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'f' AND defaclnamespace = nsp.oid) AS funcacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'T' AND defaclnamespace = nsp.oid) AS typeacl
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+ LEFT JOIN pg_catalog.pg_roles r ON (r.oid = nsp.nspowner)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% endif %}
+ (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ORDER BY 1, nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..510adf5ddd989acf78eb72f120120e3674a22ae5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/default/sql/update.sql
@@ -0,0 +1,30 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% if data %}
+{# ==== To update catalog comments ==== #}
+{% if data.description and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{# ==== To update catalog securitylabel ==== #}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', o_data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/macros/catalogs.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/macros/catalogs.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4650efcf622e476792b2a0b3e3727b70af060109
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/pg/macros/catalogs.sql
@@ -0,0 +1,43 @@
+{% macro LIST(tbl) -%}
+ ({{ tbl }}.nspname = 'pg_catalog' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pg_class' AND
+ relnamespace = {{ tbl }}.oid LIMIT 1)) OR
+ ({{ tbl }}.nspname = 'pgagent' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'pga_job' AND
+ relnamespace = {{ tbl }}.oid LIMIT 1)) OR
+ ({{ tbl }}.nspname = 'information_schema' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class WHERE relname = 'tables' AND
+ relnamespace = {{ tbl }}.oid LIMIT 1))
+{%- endmacro %}
+{% macro IS_CATALOG_SCHEMA(schema_col_name) -%}
+ {{ schema_col_name }} IN ('pg_catalog', 'pgagent', 'information_schema')
+{%- endmacro %}
+{% macro LABELS(tbl, _) -%}
+ CASE {{ tbl }}.nspname
+ WHEN 'pg_catalog' THEN '{{ _( 'PostgreSQL Catalog' ) }} (pg_catalog)'
+ WHEN 'pgagent' THEN '{{ _( 'pgAgent Job Scheduler' ) }} (pgagent)'
+ WHEN 'information_schema' THEN '{{ _( 'ANSI' ) }} (information_schema)'
+ ELSE {{ tbl }}.nspname
+ END AS name
+{%- endmacro %}
+{% macro LABELS_SCHEMACOL(schema_col_name, _) -%}
+ CASE {{ schema_col_name }}
+ WHEN 'pg_catalog' THEN '{{ _( 'PostgreSQL Catalog' ) }} (pg_catalog)'
+ WHEN 'pgagent' THEN '{{ _( 'pgAgent Job Scheduler' ) }} (pgagent)'
+ WHEN 'information_schema' THEN '{{ _( 'ANSI' ) }} (information_schema)'
+ ELSE {{ schema_col_name }}
+ END
+{%- endmacro %}
+{% macro DB_SUPPORT(tbl) -%}
+ CASE
+ WHEN {{ tbl }}.nspname = ANY('{information_schema}')
+ THEN false
+ ELSE true END
+{%- endmacro %}
+{% macro DB_SUPPORT_SCHEMACOL(schema_col_name) -%}
+ CASE
+ WHEN {{ schema_col_name }} = ANY('{information_schema}')
+ THEN false
+ ELSE true END
+{%- endmacro %}
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c41e3137359af0c9a757459250eba2346d538652
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/acl.sql
@@ -0,0 +1,23 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1fd2f207ef2593c4683c076ba95429916059797e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..510adf5ddd989acf78eb72f120120e3674a22ae5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.1_plus/sql/update.sql
@@ -0,0 +1,30 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% if data %}
+{# ==== To update catalog comments ==== #}
+{% if data.description and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{# ==== To update catalog securitylabel ==== #}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', o_data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c41e3137359af0c9a757459250eba2346d538652
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/acl.sql
@@ -0,0 +1,23 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..811955ad98a781e83b2714dffbc91e3c8a4e94ed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/create.sql
@@ -0,0 +1,17 @@
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% if data %}
+CREATE SCHEMA {{ conn|qtIdent(data.name) }}
+{% if data.namespaceowner %}
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{% if data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1fd2f207ef2593c4683c076ba95429916059797e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..510adf5ddd989acf78eb72f120120e3674a22ae5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/9.2_plus/sql/update.sql
@@ -0,0 +1,30 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% if data %}
+{# ==== To update catalog comments ==== #}
+{% if data.description and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{# ==== To update catalog securitylabel ==== #}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', o_data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..0d0b305e2fc6773058fb0ed321bc8c86ef9d8088
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/allowed_privs.json
@@ -0,0 +1,30 @@
+{# List of allowed privileges for PPAS 9.2 or later #}
+{#
+ Format for allowed privileges is:
+ "acl_col": {
+ "type": "name",
+ "acl": [...]
+ }
+#}
+{
+ "nspacl": {
+ "type": "DATABASE",
+ "acl": ["c", "C", "T"]
+ },
+ "deftblacl": {
+ "type": "TABLE",
+ "acl": ["r", "a", "w", "d", "D", "x", "t"]
+ },
+ "defseqacl": {
+ "type": "SEQUENCE",
+ "acl": ["U", "r", "w"]
+ },
+ "deffuncacl": {
+ "type": "FUNCTION",
+ "acl": ["X"]
+ },
+ "deftypeacl": {
+ "type": "TYPE",
+ "acl": ["U"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89136c7df8f17224482e1ba6108ed2a89e480b22
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/acl.sql
@@ -0,0 +1,24 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..811955ad98a781e83b2714dffbc91e3c8a4e94ed
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/create.sql
@@ -0,0 +1,17 @@
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% if data %}
+CREATE SCHEMA {{ conn|qtIdent(data.name) }}
+{% if data.namespaceowner %}
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{% if data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1fd2f207ef2593c4683c076ba95429916059797e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..82a532d04a9f75866b1cd4654cd80c62ebba5453
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/nodes.sql
@@ -0,0 +1,20 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.oid,
+{{ CATALOGS.LABELS('nsp', _) }},
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') as can_create,
+ pg_catalog.has_schema_privilege(nsp.oid, 'USAGE') as has_usage,
+ des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% endif %}
+ nsp.nspparent = 0 AND
+ (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ORDER BY 2;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2e1af5b062f161435ddc170f2e8a77d2e0f424d2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/properties.sql
@@ -0,0 +1,27 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ 2 AS nsptyp,
+ nsp.nspname AS name,
+ nsp.oid,
+ pg_catalog.array_to_string(nsp.nspacl::text[], ', ') as acl,
+ r.rolname AS namespaceowner, description,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') AS can_create,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'r' AND defaclnamespace = nsp.oid) AS tblacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'S' AND defaclnamespace = nsp.oid) AS seqacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'f' AND defaclnamespace = nsp.oid) AS funcacl,
+ (SELECT pg_catalog.array_to_string(defaclacl::text[], ', ') FROM pg_catalog.pg_default_acl WHERE defaclobjtype = 'T' AND defaclnamespace = nsp.oid) AS typeacl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=nsp.oid) AS seclabels
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+ LEFT JOIN pg_catalog.pg_roles r ON (r.oid = nsp.nspowner)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% endif %}
+ nsp.nspparent = 0 AND
+ (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ORDER BY 1, nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..510adf5ddd989acf78eb72f120120e3674a22ae5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/default/sql/update.sql
@@ -0,0 +1,30 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% if data %}
+{# ==== To update catalog comments ==== #}
+{% if data.description and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{# ==== To update catalog securitylabel ==== #}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', o_data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', o_data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/macros/catalogs.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/macros/catalogs.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b3568a2fb4834b97f54a36bc9dac8b17f5b06d8a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/catalog/ppas/macros/catalogs.sql
@@ -0,0 +1,48 @@
+{% macro LIST(tbl) -%}
+ ({{ tbl }}.nspname = 'pg_catalog' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class
+ WHERE relname = 'pg_class' AND relnamespace = {{ tbl }}.oid LIMIT 1)) OR
+ ({{ tbl }}.nspname = 'pgagent' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class
+ WHERE relname = 'pga_job' AND relnamespace = {{ tbl }}.oid LIMIT 1)) OR
+ ({{ tbl }}.nspname = 'information_schema' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_class
+ WHERE relname = 'tables' AND relnamespace = {{ tbl }}.oid LIMIT 1)) OR
+ ({{ tbl }}.nspname = 'sys') OR
+ ({{ tbl }}.nspname = 'dbms_job_procedure' AND EXISTS
+ (SELECT 1 FROM pg_catalog.pg_proc
+ WHERE pronamespace = {{ tbl }}.oid and proname = 'run_job' LIMIT 1))
+{%- endmacro %}
+{% macro IS_CATALOG_SCHEMA(schema_col_name) -%}
+ {{ schema_col_name }} IN ('pg_catalog', 'pgagent', 'information_schema', 'sys', 'dbms_job_procedure')
+{%- endmacro %}
+{% macro LABELS(tbl, _) -%}
+ CASE {{ tbl }}.nspname
+ WHEN 'pg_catalog' THEN '{{ _( 'PostgreSQL Catalog' ) }} (pg_catalog)'
+ WHEN 'pgagent' THEN '{{ _( 'pgAgent Job Scheduler' ) }} (pgagent)'
+ WHEN 'information_schema' THEN '{{ _( 'ANSI' ) }} (information_schema)'
+ WHEN 'sys' THEN 'Redwood (sys)'
+ ELSE {{ tbl }}.nspname
+ END AS name
+{%- endmacro %}
+{% macro LABELS_SCHEMACOL(schema_col_name, _) -%}
+ CASE {{ schema_col_name }}
+ WHEN 'pg_catalog' THEN '{{ _( 'PostgreSQL Catalog' ) }} (pg_catalog)'
+ WHEN 'pgagent' THEN '{{ _( 'pgAgent Job Scheduler' ) }} (pgagent)'
+ WHEN 'information_schema' THEN '{{ _( 'ANSI' ) }} (information_schema)'
+ WHEN 'sys' THEN 'Redwood (sys)'
+ ELSE {{ schema_col_name }}
+ END
+{%- endmacro %}
+{% macro DB_SUPPORT(tbl, schema_col_name) -%}
+ CASE
+ WHEN {{ tbl }}.nspname = ANY('{information_schema,sys}')
+ THEN false
+ ELSE true END
+{%- endmacro %}
+{% macro DB_SUPPORT_SCHEMACOL(schema_col_name) -%}
+ CASE
+ WHEN {{ schema_col_name }} = ANY('{information_schema,sys}')
+ THEN false
+ ELSE true END
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/datatype/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/datatype/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0bd2311c184c092827d3574a1fe3c85b6c3613b5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/datatype/sql/default/get_types.sql
@@ -0,0 +1,25 @@
+SELECT
+ *
+FROM
+ (SELECT
+ pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END as elemoid,
+ typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup,
+ CASE WHEN t.typcollation != 0 THEN TRUE ELSE FALSE END AS is_collatable
+ FROM
+ pg_catalog.pg_type t
+ JOIN
+ pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ WHERE
+ (NOT (typname = 'unknown' AND nspname = 'pg_catalog'))
+ AND
+ {{ condition }}
+{% if add_serials %}
+{# Here we will add serials types manually #}
+ UNION SELECT 'smallserial', 0, 2, 'b', 0, 'pg_catalog', false, false
+ UNION SELECT 'bigserial', 0, 8, 'b', 0, 'pg_catalog', false, false
+ UNION SELECT 'serial', 0, 4, 'b', 0, 'pg_catalog', false, false
+{% endif %}
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/privilege.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/privilege.macros
new file mode 100644
index 0000000000000000000000000000000000000000..3a55908f02ace410ca3b3a0f7299689b1eed809e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/privilege.macros
@@ -0,0 +1,14 @@
+{##############################################}
+{# Macros for Privileges (functions module) #}
+{##############################################}
+{% macro SET(conn, type, role, param, privs, with_grant_privs, schema, func_args) -%}
+{% if privs %}
+GRANT {{ privs|join(', ') }} ON {{ type }} {{ conn|qtIdent(schema, param) }}({{func_args}}) TO {{role }};
+{% endif %}
+{% if with_grant_privs %}
+GRANT {{ with_grant_privs|join(', ') }} ON {{ type }} {{ conn|qtIdent(schema, param) }}({{func_args}}) TO {{ role }} WITH GRANT OPTION;
+{% endif %}
+{%- endmacro %}
+{% macro UNSETALL(conn, type, role, param, schema, func_args) -%}
+REVOKE ALL ON {{ type }} {{ conn|qtIdent(schema, param) }}({{func_args}}) FROM {{role }};
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/security.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/security.macros
new file mode 100644
index 0000000000000000000000000000000000000000..bd90b8af699c1095b979ea3f7969cced53bb40c2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/security.macros
@@ -0,0 +1,9 @@
+{#################################################}
+{# Macros for Security Labels (functions module) #}
+{#################################################}
+{% macro SET(conn, type, name, provider, label, schema, func_args) -%}
+SECURITY LABEL{% if provider and provider != '' %} FOR {{ conn|qtIdent(provider) }}{% endif %} ON {{ type }} {{ conn|qtIdent(schema, name) }}({{func_args}}) IS {{ label|qtLiteral(conn) }};
+{%- endmacro %}
+{% macro UNSET(conn, type, name, provider, schema, func_args) -%}
+SECURITY LABEL FOR {{ provider }} ON {{ type }} {{ conn|qtIdent(schema, name) }}({{func_args}}) IS NULL;
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/variable.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/variable.macros
new file mode 100644
index 0000000000000000000000000000000000000000..30ddbc90267d79ab7c6cf757b8cd60ebdc72b7a9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/functions/variable.macros
@@ -0,0 +1,25 @@
+{################################################}
+{# Macros for Variables (functions module) #}
+{################################################}
+{% macro SET(conn, object_type, object_name, options, schema, func_args) -%}
+
+{% for opt in options %}
+ALTER {{object_type}} {{ conn|qtIdent(schema, object_name) }}{% if func_args is defined %}({{func_args}})
+{% else %}
+
+{% endif %}
+ SET {{ conn|qtIdent(opt.name) }}={{ opt.value }};
+
+{% endfor %}
+{%- endmacro %}
+{% macro UNSET(conn, object_type, object_name, options, schema, func_args) -%}
+
+{% for opt in options %}
+ALTER {{object_type}} {{ conn|qtIdent(schema, object_name) }}{% if func_args is defined %}({{func_args}})
+{% else %}
+
+{% endif %}
+ RESET {{ conn|qtIdent(opt.name) }};
+
+{% endfor %}
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/privilege.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/privilege.macros
new file mode 100644
index 0000000000000000000000000000000000000000..5211b00ded7d9cc726f74386cf9250c9213df7cb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/privilege.macros
@@ -0,0 +1,18 @@
+{##########################################}
+{# Macros for schema and its child nodes #}
+{##########################################}
+{% macro SET(conn, type, role, param, privs, with_grant_privs, schema) -%}
+{% if privs %}
+GRANT {{ privs|join(', ') }} ON {{ type }} {{ conn|qtIdent(schema, param) }} TO {{ role }};
+{% endif %}
+{% if with_grant_privs %}
+{% if privs %}
+{# This empty if is to add new line in between #}
+
+{% endif %}
+GRANT {{ with_grant_privs|join(', ') }} ON {{ type }} {{ conn|qtIdent(schema, param) }} TO {{ role }} WITH GRANT OPTION;
+{% endif %}
+{%- endmacro %}
+{% macro UNSETALL(conn, type, role, param, schema) -%}
+REVOKE ALL ON {{ type }} {{ conn|qtIdent(schema, param) }} FROM {{ role }};
+{%- endmacro %}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/security.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/security.macros
new file mode 100644
index 0000000000000000000000000000000000000000..cc7e9803dfffbd6ccdd74b676c4726f83c0da779
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/macros/schemas/security.macros
@@ -0,0 +1,9 @@
+{##########################################}
+{# Macros for schema and its child nodes #}
+{##########################################}
+{% macro SET(conn, type, name, provider, label, schema) -%}
+SECURITY LABEL{% if provider and provider != '' %} FOR {{ conn|qtIdent(provider) }}{% endif %} ON {{ type }} {{ conn|qtIdent(schema, name) }} IS {{ label|qtLiteral(conn) }};
+{%- endmacro %}
+{% macro UNSET(conn, type, name, provider, schema) -%}
+SECURITY LABEL FOR {{ provider }} ON {{ type }} {{ conn|qtIdent(schema, name) }} IS NULL;
+{%- endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..0c1784a5bd50fe12ef8182957d70c09328a7c216
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/allowed_privs.json
@@ -0,0 +1,30 @@
+{# List of allowed privileges for PostgreSQL 9.2 or later #}
+{#
+ Format for allowed privileges is:
+ "acl_col": {
+ "type": "name",
+ "acl": [...]
+ }
+#}
+{
+ "nspacl": {
+ "type": "SCHEMA",
+ "acl": ["C", "U"]
+ },
+ "deftblacl": {
+ "type": "TABLE",
+ "acl": ["r", "a", "w", "d", "D", "x", "t"]
+ },
+ "defseqacl": {
+ "type": "SEQUENCE",
+ "acl": ["U", "r", "w"]
+ },
+ "deffuncacl": {
+ "type": "FUNCTION",
+ "acl": ["X"]
+ },
+ "deftypeacl": {
+ "type": "TYPE",
+ "acl": ["U"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89136c7df8f17224482e1ba6108ed2a89e480b22
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/acl.sql
@@ -0,0 +1,24 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7b33a512f0d09ef49c652fc11720cc440ea4e0ba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/count.sql
@@ -0,0 +1,11 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ {% if not showsysobj %}
+ nspname NOT LIKE E'pg\\_%' AND
+ {% endif %}
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d5a65a16651b92251bfdf228fb2ed7945f8a68ce
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/create.sql
@@ -0,0 +1,40 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/default_privilege.macros' as DEFAULT_PRIVILEGE %}
+{% if data.name %}
+CREATE SCHEMA{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.name) }}{% if data.namespaceowner %}
+
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }}{% endif %}{% endif %};
+{# Alter the comment/description #}
+{% if data.description %}
+
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{# ACL for the schema #}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{# Default privileges on tables #}
+{% for defacl, type in [
+ ('deftblacl', 'TABLES'), ('defseqacl', 'SEQUENCES'),
+ ('deffuncacl', 'FUNCTIONS'), ('deftypeacl', 'TYPES')]
+%}
+{% if data[defacl] %}{% set acl = data[defacl] %}
+{% for priv in acl %}
+
+{{ DEFAULT_PRIVILEGE.SET(
+ conn, 'SCHEMA', data.name, type, priv.grantee,
+ priv.without_grant, priv.with_grant, priv.grantor
+ ) }}{% endfor %}
+{% endif %}
+{% endfor %}
+{# Security Labels on schema #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% for r in data.seclabels %}
+
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/defacl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/defacl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb7a1dffe95f92dcd42cffea92614f8afae697f9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/defacl.sql
@@ -0,0 +1,40 @@
+SELECT
+ CASE (a.deftype)
+ WHEN 'r' THEN 'deftblacl'
+ WHEN 'S' THEN 'defseqacl'
+ WHEN 'f' THEN 'deffuncacl'
+ WHEN 'T' THEN 'deftypeacl'
+ ELSE 'UNKNOWN - ' || a.deftype::text
+ END AS deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(a.privilege_type) as privileges, pg_catalog.array_agg(a.is_grantable) as grantable
+FROM
+ (SELECT
+ (acl).grantee as grantee, (acl).grantor AS grantor, (acl).is_grantable AS is_grantable,
+ CASE (acl).privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (acl).privilege_type
+ END AS privilege_type,
+ defaclobjtype as deftype
+ FROM
+ (SELECT defaclobjtype, pg_catalog.aclexplode(defaclacl) as acl
+ FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_default_acl dacl ON (dacl.defaclnamespace = nsp.oid)
+ WHERE
+ nsp.oid={{scid}}::oid
+ ) d) a
+ LEFT JOIN pg_catalog.pg_roles g ON (a.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (a.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname, a.deftype
+ORDER BY a.deftype;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..75e9a8b4da65cbd5812c0aad6119eb09386a6770
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/delete.sql
@@ -0,0 +1 @@
+DROP SCHEMA IF EXISTS {{ conn|qtIdent(name) }} {% if cascade %}CASCADE{%endif%};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f15d3c177ad2db239169df7aac99836179d888bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2c31a53d465f620bc18b9b5cf3b54df8c93de017
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/nodes.sql
@@ -0,0 +1,29 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.oid,
+ nsp.nspname as name,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') as can_create,
+ pg_catalog.has_schema_privilege(nsp.oid, 'USAGE') as has_usage,
+ des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% else %}
+ {% if not show_sysobj %}
+ nspname NOT LIKE E'pg\\_%' AND
+ {% endif %}
+ {% endif %}
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
+
+ {% if schema_restrictions %}
+ AND
+ nsp.nspname in ({{schema_restrictions}})
+ {% endif %}
+
+ORDER BY nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4c75713c3c83ab55a046b7a37dbcc5ee14d344ac
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/oid.sql
@@ -0,0 +1 @@
+SELECT nsp.oid FROM pg_catalog.pg_namespace nsp WHERE nsp.nspname = {{ schema|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..eacc48fa90233d76ad386c1c1e899b2d180e8839
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/properties.sql
@@ -0,0 +1,57 @@
+{% import 'catalog/pg/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ CASE
+ WHEN (nspname LIKE E'pg\\_temp\\_%') THEN 1
+ WHEN (nspname LIKE E'pg\\_%') THEN 0
+ ELSE 3 END AS nsptyp,
+ nsp.nspname AS name,
+ nsp.oid,
+ pg_catalog.array_to_string(nsp.nspacl::text[], ', ') as acl,
+ r.rolname AS namespaceowner, description,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') AS can_create,
+ {### Default ACL for Tables ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'r' AND defaclnamespace = nsp.oid
+ ), ', ')) AS tblacl,
+ {### Default ACL for Sequnces ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'S' AND defaclnamespace = nsp.oid
+ ), ', ')) AS seqacl,
+ {### Default ACL for Functions ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'f' AND defaclnamespace = nsp.oid
+ ), ', ')) AS funcacl,
+ {### Default ACL for Type ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'T' AND defaclnamespace = nsp.oid
+ ), ', ')) AS typeacl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=nsp.oid) AS seclabels
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+ LEFT JOIN pg_catalog.pg_roles r ON (r.oid = nsp.nspowner)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% else %}
+ {% if not show_sysobj %}
+ nspname NOT LIKE E'pg\\_%' AND
+ {% endif %}
+ {% endif %}
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ {% if schema_restrictions %}
+ AND
+ nsp.nspname in ({{schema_restrictions}})
+ {% endif %}
+ORDER BY 1, nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ad2a5593c27d38963d12221428f88c976c804297
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/pg/default/sql/update.sql
@@ -0,0 +1,91 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/default_privilege.macros' as DEFAULT_PRIVILEGE %}
+{# Rename the schema #}
+{% if data.name and data.name != o_data.name %}
+ALTER SCHEMA {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# Change the owner #}
+{% if data.namespaceowner and data.namespaceowner != o_data.namespaceowner %}
+ALTER SCHEMA {{ conn|qtIdent(data.name) }}
+ OWNER TO {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{# Update the comments/description #}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{# Change the privileges #}
+{% if data.nspacl %}
+{% if 'deleted' in data.nspacl %}
+{% for priv in data.nspacl.deleted %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.grantee, data.name) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.nspacl %}
+{% for priv in data.nspacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.old_grantee, data.name) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.grantee, data.name) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.nspacl %}
+{% for priv in data.nspacl.added %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# Change the default privileges #}
+{% for defacl, type in [
+ ('deftblacl', 'TABLES'), ('defseqacl', 'SEQUENCES'),
+ ('deffuncacl', 'FUNCTIONS'), ('deftypeacl', 'TYPES')]
+%}
+{% if data[defacl] %}{% set acl = data[defacl] %}
+{% if 'deleted' in acl %}
+{% for priv in acl.deleted %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, type, priv.grantee, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in acl %}
+{% for priv in acl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, type, priv.old_grantee, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, type, priv.grantee, priv.grantor) }}
+{% endif %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, type, priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in acl %}
+{% for priv in acl.added %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, type, priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endfor %}
+{# Change the security labels #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..b014f5798539b2c500fcd4a7ea909ddaeee5b8a6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/allowed_privs.json
@@ -0,0 +1,30 @@
+{# List of allowed privileges for PPAS 9.2 or later #}
+{#
+ Format for allowed privileges is:
+ "acl_col": {
+ "type": "name",
+ "acl": [...]
+ }
+#}
+{
+ "nspacl": {
+ "type": "SCHEMA",
+ "acl": ["C", "U"]
+ },
+ "deftblacl": {
+ "type": "TABLE",
+ "acl": ["r", "a", "w", "d", "D", "x", "t"]
+ },
+ "defseqacl": {
+ "type": "SEQUENCE",
+ "acl": ["U", "r", "w"]
+ },
+ "deffuncacl": {
+ "type": "FUNCTION",
+ "acl": ["X"]
+ },
+ "deftypeacl": {
+ "type": "TYPE",
+ "acl": ["U"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..89136c7df8f17224482e1ba6108ed2a89e480b22
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/acl.sql
@@ -0,0 +1,24 @@
+{# Fetch privileges for schema #}
+SELECT
+ 'nspacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') AS grantee,
+ g.rolname AS grantor, pg_catalog.array_agg(b.privilege_type) AS privileges,
+ pg_catalog.array_agg(b.is_grantable) AS grantable
+FROM
+ (SELECT
+ (d).grantee AS grantee, (d).grantor AS grantor,
+ (d).is_grantable AS is_grantable,
+ CASE (d).privilege_type
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (d).privilege_type
+ END AS privilege_type
+ FROM
+ (SELECT pg_catalog.aclexplode(nsp.nspacl) as d
+ FROM pg_catalog.pg_namespace nsp
+ WHERE nsp.oid = {{ scid|qtLiteral(conn) }}::OID
+ ) a
+ ) b
+ LEFT JOIN pg_catalog.pg_roles g ON (b.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (b.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..95334d1997ce60c0ecde5cfa11af485ef8338389
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/count.sql
@@ -0,0 +1,20 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT COUNT(*)
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.nspparent = 0 AND
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% else %}
+ {% if not show_sysobj %}
+ nspname NOT LIKE 'pg!_%' escape '!' AND
+ {% endif %}
+ {% endif %}
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ {% if schema_restrictions %}
+ AND
+ nsp.nspname in ({{schema_restrictions}})
+ {% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d5a65a16651b92251bfdf228fb2ed7945f8a68ce
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/create.sql
@@ -0,0 +1,40 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/default_privilege.macros' as DEFAULT_PRIVILEGE %}
+{% if data.name %}
+CREATE SCHEMA{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.name) }}{% if data.namespaceowner %}
+
+ AUTHORIZATION {{ conn|qtIdent(data.namespaceowner) }}{% endif %}{% endif %};
+{# Alter the comment/description #}
+{% if data.description %}
+
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+{% endif %}
+{# ACL for the schema #}
+{% if data.nspacl %}
+{% for priv in data.nspacl %}
+
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}{% endfor %}
+{% endif %}
+{# Default privileges on tables #}
+{% for defacl, type in [
+ ('deftblacl', 'TABLES'), ('defseqacl', 'SEQUENCES'),
+ ('deffuncacl', 'FUNCTIONS'), ('deftypeacl', 'TYPES')]
+%}
+{% if data[defacl] %}{% set acl = data[defacl] %}
+{% for priv in acl %}
+
+{{ DEFAULT_PRIVILEGE.SET(
+ conn, 'SCHEMA', data.name, type, priv.grantee,
+ priv.without_grant, priv.with_grant, priv.grantor
+ ) }}{% endfor %}
+{% endif %}
+{% endfor %}
+{# Security Labels on schema #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% for r in data.seclabels %}
+
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/defacl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/defacl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..18448b9ad7cb608d83943cf0d4c07f0bf024175e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/defacl.sql
@@ -0,0 +1,43 @@
+SELECT
+ CASE (a.deftype)
+ WHEN 'r' THEN 'deftblacl'
+ WHEN 'S' THEN 'defseqacl'
+ WHEN 'f' THEN 'deffuncacl'
+ WHEN 'T' THEN 'deftypeacl'
+ ELSE 'UNKNOWN - ' || a.deftype::text
+ END AS deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(a.privilege_type order by a.privilege_type) as privileges,
+ pg_catalog.array_agg(a.is_grantable) as grantable
+FROM
+ (SELECT
+ (acl).grantee as grantee, (acl).grantor AS grantor, (acl).is_grantable AS is_grantable,
+ CASE (acl).privilege_type
+ WHEN 'CONNECT' THEN 'c'
+ WHEN 'CREATE' THEN 'C'
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'EXECUTE' THEN 'X'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TEMPORARY' THEN 'T'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'TRUNCATE' THEN 'D'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN - ' || (acl).privilege_type
+ END AS privilege_type,
+ defaclobjtype as deftype
+ FROM
+ (SELECT defaclobjtype, pg_catalog.aclexplode(defaclacl) as acl
+ FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_default_acl dacl ON (dacl.defaclnamespace = nsp.oid)
+ WHERE
+ nsp.oid={{scid}}::oid
+ ) d) a
+ LEFT JOIN pg_catalog.pg_roles g ON (a.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (a.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname, a.deftype
+ORDER BY a.deftype;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..75e9a8b4da65cbd5812c0aad6119eb09386a6770
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/delete.sql
@@ -0,0 +1 @@
+DROP SCHEMA IF EXISTS {{ conn|qtIdent(name) }} {% if cascade %}CASCADE{%endif%};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/get_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/get_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5f5612c02e1ee2f4d58a1a2e621bfe60f5ac15f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/get_name.sql
@@ -0,0 +1 @@
+SELECT nsp.nspname FROM pg_catalog.pg_namespace nsp WHERE nsp.oid = {{ scid|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/is_catalog.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/is_catalog.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1fd2f207ef2593c4683c076ba95429916059797e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/is_catalog.sql
@@ -0,0 +1,9 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.nspname as schema_name,
+ {{ CATALOGS.LIST('nsp') }} AS is_catalog,
+ {{ CATALOGS.DB_SUPPORT('nsp') }} AS db_support
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ nsp.oid = {{ scid|qtLiteral(conn) }}::OID;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3e1f656a21208433b74fe194dc932541745592b8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/nodes.sql
@@ -0,0 +1,28 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ nsp.oid,
+ nsp.nspname as name,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') as can_create,
+ pg_catalog.has_schema_privilege(nsp.oid, 'USAGE') as has_usage,
+ des.description
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+WHERE
+ nsp.nspparent = 0 AND
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% else %}
+ {% if not show_sysobj %}
+ nspname NOT LIKE 'pg!_%' escape '!' AND
+ {% endif %}
+ {% endif %}
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ {% if schema_restrictions %}
+ AND
+ nsp.nspname in ({{schema_restrictions}})
+ {% endif %}
+ORDER BY nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4c75713c3c83ab55a046b7a37dbcc5ee14d344ac
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/oid.sql
@@ -0,0 +1 @@
+SELECT nsp.oid FROM pg_catalog.pg_namespace nsp WHERE nsp.nspname = {{ schema|qtLiteral(conn) }};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6e8e5e9ef92b7cde6d11490683d53eac54966d9c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/properties.sql
@@ -0,0 +1,58 @@
+{% import 'catalog/ppas/macros/catalogs.sql' as CATALOGS %}
+SELECT
+ CASE
+ WHEN (nspname LIKE E'pg\\_temp\\_%') THEN 1
+ WHEN (nspname LIKE E'pg\\_%') THEN 0
+ ELSE 3 END AS nsptyp,
+ nsp.nspname AS name,
+ nsp.oid,
+ pg_catalog.array_to_string(nsp.nspacl::text[], ', ') as acl,
+ r.rolname AS namespaceowner, description,
+ pg_catalog.has_schema_privilege(nsp.oid, 'CREATE') AS can_create,
+ {### Default ACL for Tables ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'r' AND defaclnamespace = nsp.oid
+ ), ', ')) AS tblacl,
+ {### Default ACL for Sequnces ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'S' AND defaclnamespace = nsp.oid
+ ), ', ')) AS seqacl,
+ {### Default ACL for Functions ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'f' AND defaclnamespace = nsp.oid
+ ), ', ')) AS funcacl,
+ {### Default ACL for Type ###}
+ (SELECT pg_catalog.array_to_string(ARRAY(
+ SELECT pg_catalog.array_to_string(defaclacl::text[], ', ')
+ FROM pg_catalog.pg_default_acl
+ WHERE defaclobjtype = 'T' AND defaclnamespace = nsp.oid
+ ), ', ')) AS typeacl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=nsp.oid) AS seclabels
+FROM
+ pg_catalog.pg_namespace nsp
+ LEFT OUTER JOIN pg_catalog.pg_description des ON
+ (des.objoid=nsp.oid AND des.classoid='pg_namespace'::regclass)
+ LEFT JOIN pg_catalog.pg_roles r ON (r.oid = nsp.nspowner)
+WHERE
+ {% if scid %}
+ nsp.oid={{scid}}::oid AND
+ {% else %}
+ {% if not show_sysobj %}
+ nspname NOT LIKE E'pg\\_%' AND
+ {% endif %}
+ {% endif %}
+ nsp.nspparent = 0 AND
+ NOT (
+{{ CATALOGS.LIST('nsp') }}
+ )
+ {% if schema_restrictions %}
+ AND
+ nsp.nspname in ({{schema_restrictions}})
+ {% endif %}
+ORDER BY 1, nspname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..82991a8a220ff128035ba1ed79db57aeeeee2c26
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/schemas/ppas/default/sql/update.sql
@@ -0,0 +1,153 @@
+{% import 'macros/security.macros' as SECLABEL %}
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/default_privilege.macros' as DEFAULT_PRIVILEGE %}
+{% if data %}
+{### To update SCHEMA name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER SCHEMA {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{### To update SCHEMA owner ###}
+{% if data.namespaceowner and data.namespaceowner != o_data.namespaceowner %}
+ALTER SCHEMA {{ conn|qtIdent(data.name) }}
+ OWNER TO {{ conn|qtIdent(data.namespaceowner) }};
+
+{% endif %}
+{### To update SCHEMA comments ###}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON SCHEMA {{ conn|qtIdent(data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{### Change the security labels ###}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.DROP(conn, 'SCHEMA', data.name, r.provider) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.APPLY(conn, 'SCHEMA', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### Change the privileges ###}
+{% if data.nspacl %}
+{% if 'deleted' in data.nspacl %}
+{% for priv in data.nspacl.deleted %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.grantee, data.name) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.nspacl %}
+{% for priv in data.nspacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.old_grantee, data.name) }}
+{% else %}
+{{ PRIVILEGE.RESETALL(conn, 'SCHEMA', priv.grantee, data.name) }}
+{% endif %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.nspacl %}
+{% for priv in data.nspacl.added %}
+{{ PRIVILEGE.APPLY(conn, 'SCHEMA', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### To change default privileges for tables ###}
+{% if data.deftblacl %}
+{% if 'deleted' in data.deftblacl %}
+{% for priv in data.deftblacl.deleted %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, 'TABLES', priv.grantee, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.deftblacl %}
+{% for priv in data.deftblacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, 'TABLES', priv.old_grantee, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn, 'SCHEMA', data.name, 'TABLES', priv.grantee, priv.grantor) }}
+{% endif %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'TABLES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.deftblacl %}
+{% for priv in data.deftblacl.added %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'TABLES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### To change default privileges for sequences ###}
+{% if data.defseqacl %}
+{% if 'deleted' in data.defseqacl %}
+{% for priv in data.defseqacl.deleted %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'SEQUENCES', priv.grantee, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.defseqacl %}
+{% for priv in data.defseqacl.changed %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'SEQUENCES', priv.grantee, priv.grantor) }}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'SEQUENCES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.defseqacl %}
+{% for priv in data.defseqacl.added %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'SEQUENCES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### To change default privileges for functions ###}
+{% if data.deffuncacl %}
+{% if 'deleted' in data.deffuncacl %}
+{% for priv in data.deffuncacl.deleted %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'FUNCTIONS', priv.grantee, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.deffuncacl %}
+{% for priv in data.deffuncacl.changed %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'FUNCTIONS', priv.grantee, priv.grantor) }}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'FUNCTIONS', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.deffuncacl %}
+{% for priv in data.deffuncacl.added %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'FUNCTIONS', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### To change default privileges for types ###}
+{% if data.deftypeacl %}
+{% if 'deleted' in data.deftypeacl %}
+{% for priv in data.deftypeacl.deleted %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'TYPES', priv.grantee, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.deftypeacl %}
+{% for priv in data.deftypeacl.changed %}
+{{ DEFAULT_PRIVILEGE.UNSET(conn,'SCHEMA', data.name, 'TYPES', priv.grantee, priv.grantor) }}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'TYPES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.deftypeacl %}
+{% for priv in data.deftypeacl.added %}
+{{ DEFAULT_PRIVILEGE.SET(conn,'SCHEMA', data.name, 'TYPES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{### End main if data ###}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/sql/vacuum_defaults.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/sql/vacuum_defaults.sql
new file mode 100644
index 0000000000000000000000000000000000000000..67e768abce5352bd04f42cfe14ce5ccb8e8db10d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/sql/vacuum_defaults.sql
@@ -0,0 +1,2 @@
+{# ============= Fetch list of default values for autovacuum parameters =============== #}
+SELECT name, setting::numeric AS setting FROM pg_catalog.pg_settings WHERE name IN({{ columns }}) ORDER BY name
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/vacuum_fields.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/vacuum_fields.json
new file mode 100644
index 0000000000000000000000000000000000000000..28607050aaf7b7e672bd5cace67d34ab557fbf76
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/templates/vacuum_settings/vacuum_fields.json
@@ -0,0 +1,39 @@
+{# ===== Define name, label and column type of vacuum settings ===== #}
+{# Usage:
+
+ 'Type":
+ {
+ "key": ["label", "column_type"
+ }
+
+ Where
+ - "Type" either table/toast
+ - "key" refers to the name of columns we fetch in properties.sql
+ - "label" It is the name of properties to display in grid.
+ - "column_type" Type of column, we have to provide the grid what type of value to rendered
+#}
+{# ===== Define name, label and column type of vacuum settings ===== #}
+{
+ "table":
+ {
+ "autovacuum_vacuum_threshold": ["autovacuum_vacuum_threshold", "VACUUM base threshold", "integer"],
+ "autovacuum_analyze_threshold": ["autovacuum_analyze_threshold", "ANALYZE base threshold", "integer"],
+ "autovacuum_vacuum_scale_factor": ["autovacuum_vacuum_scale_factor", "VACUUM scale factor", "number"],
+ "autovacuum_analyze_scale_factor": ["autovacuum_analyze_scale_factor", "ANALYZE scale factor", "number"],
+ "autovacuum_vacuum_cost_delay": ["autovacuum_vacuum_cost_delay", "VACUUM cost delay", "integer"],
+ "autovacuum_vacuum_cost_limit": ["autovacuum_vacuum_cost_limit", "VACUUM cost limit", "integer"],
+ "autovacuum_freeze_max_age": ["autovacuum_freeze_max_age", "FREEZE maximum age", "integer"],
+ "vacuum_freeze_min_age": ["autovacuum_freeze_min_age", "FREEZE minimum age", "integer"],
+ "vacuum_freeze_table_age": ["autovacuum_freeze_table_age", "FREEZE table age", "integer"]
+ },
+ "toast":
+ {
+ "autovacuum_vacuum_threshold": ["autovacuum_vacuum_threshold", "VACUUM base threshold", "integer"],
+ "autovacuum_vacuum_scale_factor": ["autovacuum_vacuum_scale_factor", "VACUUM scale factor", "number"],
+ "autovacuum_vacuum_cost_delay": ["autovacuum_vacuum_cost_delay", "VACUUM cost delay", "integer"],
+ "autovacuum_vacuum_cost_limit": ["autovacuum_vacuum_cost_limit", "VACUUM cost limit", "integer"],
+ "autovacuum_freeze_max_age": ["autovacuum_freeze_max_age", "FREEZE maximum age", "integer"],
+ "vacuum_freeze_min_age": ["autovacuum_freeze_min_age", "FREEZE minimum age", "integer"],
+ "vacuum_freeze_table_age": ["autovacuum_freeze_table_age", "FREEZE table age", "integer"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3e29cf6a7ef5cdd2d4754eaad5b8c1ecdbfff3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/__init__.py
@@ -0,0 +1,1604 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Type Node """
+
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify
+from flask_babel import gettext
+import re
+
+import pgadmin.browser.server_groups.servers.databases as database
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import SchemaChildModule, DataTypeReader
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+
+
+class TypeModule(SchemaChildModule):
+ """
+ class TypeModule(SchemaChildModule)
+
+ A module class for Type node derived from SchemaChildModule
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the Type and it's base module.
+
+ * get_nodes(gid, sid, did, scid, tid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for type, when any of the server node is
+ initialized.
+ """
+
+ _NODE_TYPE = 'type'
+ _COLLECTION_LABEL = gettext("Types")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the TypeModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(sid, did, scid=scid,
+ base_template_path=TypeView.BASE_TEMPLATE_PATH):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for database, when any of the database node is
+ initialized.
+ """
+ return database.DatabaseModule.node_type
+
+ @property
+ def node_inode(self):
+ """
+ Load the module node as a leaf node
+ """
+ return False
+
+
+blueprint = TypeModule(__name__)
+
+
+class TypeView(PGChildNodeView, DataTypeReader, SchemaDiffObjectCompare):
+ """
+ This class is responsible for generating routes for Type node
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the TypeView and it's base view.
+
+ * check_precondition()
+ - This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+
+ * list()
+ - This function is used to list all the Type nodes within that
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within that
+ collection, Here it will create all the Type node.
+
+ * properties(gid, sid, did, scid, tid)
+ - This function will show the properties of the selected Type node
+
+ * create(gid, sid, did, scid)
+ - This function will create the new Type object
+
+ * update(gid, sid, did, scid, tid)
+ - This function will update the data for the selected Type node
+
+ * delete(self, gid, sid, scid, tid):
+ - This function will drop the Type object
+
+ * msql(gid, sid, did, scid, tid)
+ - This function is used to return modified SQL for the selected
+ Type node
+
+ * get_sql(data, scid, tid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the
+ selected Type node.
+
+ * dependency(gid, sid, did, scid, tid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected Type node.
+
+ * dependent(gid, sid, did, scid, tid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected Type node.
+
+ * additional_properties(copy_dict, tid):
+ - This function will add additional properties in response
+
+ * get_collations(gid, sid, did, scid, tid):
+ - This function will return list of collation in ajax response
+
+ * get_types(gid, sid, did, scid, tid):
+ - This function will return list of types in ajax response
+
+ * get_subtypes(gid, sid, did, scid, tid):
+ - This function will return list of subtypes in ajax response
+
+ * get_subtype_opclass(gid, sid, did, scid, tid):
+ - This function will return list of subtype opclass in ajax response
+
+ * get_subtype_diff(gid, sid, did, scid, tid):
+ - This function will return list of subtype diff functions
+ in ajax response
+
+ * get_canonical(gid, sid, did, scid, tid):
+ - This function will return list of canonical functions
+ in ajax response
+
+ * get_external_functions_list(gid, sid, did, scid, tid):
+ - This function will return list of external functions
+ in ajax response
+
+ * compare(**kwargs):
+ - This function will compare the type nodes from two
+ different schemas.
+ """
+
+ node_type = blueprint.node_type
+ icon_str = "icon-%s"
+ BASE_TEMPLATE_PATH = 'types/{0}/sql/#{1}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'tid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'children': [{'get': 'children'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'get_types': [{'get': 'get_types'}, {'get': 'get_types'}],
+ 'get_stypes': [{'get': 'get_subtypes'}, {'get': 'get_subtypes'}],
+ 'get_subopclass': [{'get': 'get_subtype_opclass'},
+ {'get': 'get_subtype_opclass'}],
+ 'get_stypediff': [{'get': 'get_subtype_diff'},
+ {'get': 'get_subtype_diff'}],
+ 'get_canonical': [{'get': 'get_canonical'}, {'get': 'get_canonical'}],
+ 'get_collations': [{'get': 'get_collations'},
+ {'get': 'get_collations'}],
+ 'get_external_functions': [{'get': 'get_external_functions_list'},
+ {'get': 'get_external_functions_list'}]
+ })
+
+ keys_to_ignore = ['oid', 'typnamespace', 'typrelid', 'typarray', 'alias',
+ 'schema', 'oid-2', 'type_acl', 'rngcollation', 'attnum',
+ 'typowner']
+
+ def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to self
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+ kwargs['sid'])
+ self.conn = self.manager.connection(did=kwargs['did'])
+
+ # Declare allows acl on type
+ self.acl = ['U']
+
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.server_type, self.manager.version)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ This function is used to list all the type nodes within that
+ collection.
+
+ Args:
+ gid: Server group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+
+ Returns:
+ JSON of available type nodes
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path, self._PROPERTIES_SQL]),
+ scid=scid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects)
+
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, tid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the type node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+
+ Returns:
+ JSON of available type child nodes
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._NODES_SQL]),
+ scid=scid,
+ tid=tid,
+ show_system_objects=self.blueprint.show_system_objects)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(
+ gettext("""Could not find the type in the database."""))
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ scid,
+ rset['rows'][0]['name'],
+ icon=self.icon_str % self.node_type
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ This function will used to create all the child node within that
+ collection.
+ Here it will create all the type node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+
+ Returns:
+ JSON of available type child nodes
+ """
+
+ res = []
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._NODES_SQL]), scid=scid,
+ show_system_objects=self.blueprint.show_system_objects)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon=self.icon_str % self.node_type,
+ description=row['description']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ def _cltype_formatter(self, in_type):
+ """
+
+ Args:
+ data: Type string
+
+ Returns:
+ We need to remove [] from type and append it
+ after length/precision so we will set flag for
+ sql template
+ """
+ if '[]' in in_type:
+ in_type = in_type.replace('[]', '')
+ self.hasSqrBracket = True
+ else:
+ self.hasSqrBracket = False
+
+ return in_type
+
+ @staticmethod
+ def convert_length_precision_to_string(data):
+ """
+ This function is used to convert length & precision to string
+ to handle case like when user gives 0 as length
+
+ Args:
+ data: Data from client
+
+ Returns:
+ Converted data
+ """
+ if 'tlength' in data and data['tlength'] is not None:
+ data['tlength'] = str(data['tlength'])
+ if 'precision' in data and data['precision'] is not None:
+ data['precision'] = str(data['precision'])
+ return data
+
+ def _additional_properties_composite(self, rows):
+ """
+ Used by additional_properties internally for composite type.
+ :param rows: list of data
+ :return: formatted response
+ """
+ res = dict()
+ properties_list = []
+ # To display in composite collection grid
+ composite_lst = []
+
+ for row in rows:
+ # We will fetch Full type name
+
+ typelist = ' '.join([row['attname'], row['fulltype']])
+ if (
+ not row['collname'] or
+ (
+ row['collname'] == 'default' and
+ row['collnspname'] == 'pg_catalog'
+ )
+ ):
+ full_collate = ''
+ collate = ''
+ else:
+ full_collate = get_driver(PG_DEFAULT_DRIVER).qtIdent(
+ self.conn, row['collnspname'], row['collname'])
+ collate = ' COLLATE ' + full_collate
+
+ typelist += collate
+ properties_list.append(typelist)
+
+ is_tlength, is_precision, _ = \
+ self.get_length_precision(row.get('elemoid', None))
+
+ # Split length, precision from type name for grid
+ t_len, t_prec = DataTypeReader.parse_length_precision(
+ row['fulltype'], is_tlength, is_precision)
+
+ type_name = DataTypeReader.parse_type_name(row['typname'])
+
+ row['type'] = self._cltype_formatter(type_name)
+ row['hasSqrBracket'] = self.hasSqrBracket
+ row = self.convert_length_precision_to_string(row)
+ composite_lst.append({
+ 'attnum': row['attnum'], 'member_name': row['attname'],
+ 'type': type_name,
+ 'collation': full_collate, 'cltype': row['type'],
+ 'tlength': t_len, 'precision': t_prec,
+ 'is_tlength': is_tlength, 'is_precision': is_precision,
+ 'hasSqrBracket': row['hasSqrBracket'],
+ 'fulltype': row['fulltype']})
+
+ # Adding both results
+ res['member_list'] = ', '.join(properties_list)
+ res['composite'] = composite_lst
+
+ return res
+
+ def _additional_properties_advanced_server_type(self, data):
+ """
+ Used by additional_properties internally for advanced server types.
+ :param rows: list of data
+ :return: formatted response
+ """
+ is_tlength, is_precision, _ = \
+ self.get_length_precision(data.get('elemoid', None))
+
+ # Split length, precision from type name for grid
+ t_len, t_prec = DataTypeReader.parse_length_precision(
+ data['fulltype'], is_tlength, is_precision)
+
+ data = self.convert_length_precision_to_string(data)
+ data['type'] = self._cltype_formatter(data['type'])
+ data['cltype'] = self._cltype_formatter(data['type'])
+ data['hasSqrBracket'] = self.hasSqrBracket
+ data['tlength'] = t_len,
+ data['precision'] = t_prec
+ data['is_tlength'] = is_tlength,
+ data['is_precision'] = is_precision,
+ data['maxsize'] = data['typndims']
+
+ return data
+
+ def additional_properties(self, copy_dict, tid):
+ """
+ We will use this function to add additional properties according to
+ type
+
+ Returns:
+ additional properties for type like range/composite/enum
+
+ """
+ # Fetching type of type
+ of_type = copy_dict['typtype']
+ res = dict()
+
+ render_args = {'typtype': of_type}
+ if of_type == 'c':
+ render_args['typrelid'] = copy_dict['typrelid']
+ else:
+ render_args['tid'] = tid
+
+ if of_type in ('c', 'e', 'r', 'N', 'V', 'A'):
+ SQL = render_template("/".join([self.template_path,
+ 'additional_properties.sql']),
+ **render_args)
+ status, rset = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # If type is of Composite then we need to add members list in our
+ # output
+ if of_type == 'c':
+ # To display in properties
+ res = self._additional_properties_composite(rset['rows'])
+
+ if of_type in ('N', 'V'):
+ # To display in properties
+ res = self._additional_properties_advanced_server_type(
+ rset['rows'][0])
+
+ # If type is of ENUM then we need to add labels in our output
+ if of_type == 'e':
+ # To display in properties
+ properties_list = []
+ # To display in enum grid
+ enum_list = []
+ for row in rset['rows']:
+ properties_list.append(row['enumlabel'])
+ enum_list.append({'label': row['enumlabel']})
+
+ # Adding both results in ouput
+ res['enum_list'] = ', '.join(properties_list)
+ res['enum'] = enum_list
+
+ # If type is of Range then we need to add collation,subtype etc in our
+ # output
+ if of_type == 'r':
+ range_dict = dict(rset['rows'][0])
+ res.update(range_dict)
+
+ if 'seclabels' in copy_dict and copy_dict['seclabels'] is not None:
+ sec_labels = []
+ for sec in copy_dict['seclabels']:
+ sec = re.search(r'([^=]+)=(.*$)', sec)
+ sec_labels.append({
+ 'provider': sec.group(1),
+ 'label': sec.group(2)
+ })
+ res['seclabels'] = sec_labels
+
+ # Returning only additional properties only
+ return res
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, tid):
+ """
+ This function will show the properties of the selected type node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ scid: Schema ID
+ tid: Type ID
+
+ Returns:
+ JSON of selected type node
+ """
+ status, res = self._fetch_properties(scid, tid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, tid):
+ """
+ This function is used to fecth the properties of the specified object.
+ :param scid:
+ :param tid:
+ :return:
+ """
+
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(
+ gettext("""Could not find the type in the database."""))
+
+ # Making copy of output for future use
+ copy_dict = dict(res['rows'][0])
+
+ # We need to parse & convert ACL coming from database to json format
+ SQL = render_template("/".join([self.template_path, self._ACL_SQL]),
+ scid=scid, tid=tid)
+ status, acl = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=acl)
+
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ copy_dict['typacl'] = []
+
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ if row['deftype'] in copy_dict:
+ copy_dict[row['deftype']].append(priv)
+ else:
+ copy_dict[row['deftype']] = [priv]
+
+ # Calling function to check and additional properties if available
+ copy_dict.update(self.additional_properties(copy_dict, tid))
+
+ return True, copy_dict
+
+ @check_precondition
+ def get_collations(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of collation available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': ''}]
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_collations.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['collation'],
+ 'value': row['collation']}
+ )
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_types(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of types available
+ as AJAX response.
+ """
+ res = []
+ try:
+ SQL = render_template("/".join([self.template_path,
+ 'get_types.sql']))
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ # Check against PGOID for specific type
+ if row['elemoid']:
+ if row['elemoid'] in (1560, 1561, 1562, 1563, 1042, 1043,
+ 1014, 1015):
+ typeval = 'L'
+ elif row['elemoid'] in (1083, 1114, 1115, 1183, 1184, 1185,
+ 1186, 1187, 1266, 1270):
+ typeval = 'D'
+ elif row['elemoid'] in (1231, 1700):
+ typeval = 'P'
+ else:
+ typeval = ' '
+
+ # Logic to set precision & length/min/max values
+ precision, length, min_val,\
+ max_val = TypeView.set_precision_and_len_val(typeval)
+
+ res.append(
+ {'label': row['typname'], 'value': row['typname'],
+ 'typval': typeval, 'precision': precision,
+ 'length': length, 'min_val': min_val, 'max_val': max_val,
+ 'is_collatable': row['is_collatable']
+ }
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @staticmethod
+ def set_precision_and_len_val(typeval):
+ """
+ Logic to set precision & length/min/max values
+ :param typeval: type value to check precision, Length.
+ :return: precision, length, min val and max val.
+ """
+ # Attaching properties for precession
+ # & length validation for current type
+ precision = False
+ length = False
+ min_val = 0
+ max_val = 0
+
+ if typeval == 'P':
+ precision = True
+
+ if precision or typeval in ('L', 'D'):
+ length = True
+ min_val = 0 if typeval == 'D' else 1
+ if precision:
+ max_val = 1000
+ elif min_val:
+ # Max of integer value
+ max_val = 2147483647
+ else:
+ max_val = 10
+ return precision, length, min_val, max_val
+
+ @check_precondition
+ def get_subtypes(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of subtypes available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': ''}]
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ subtype=True, conn=self.conn)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['stype'], 'value': row['stype'],
+ 'is_collate': row['is_collate']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_subtype_opclass(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of subtype opclass available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': ''}]
+ data = request.args
+
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ subtype_opclass=True, data=data,
+ conn=self.conn)
+ if SQL:
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['opcname'],
+ 'value': row['opcname']})
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_subtype_diff(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of subtypes diff functions available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': ''}]
+ data = request.args
+
+ try:
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ get_opcintype=True, data=data,
+ conn=self.conn)
+ if SQL:
+ status, opcintype = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=opcintype)
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ opcintype=opcintype, conn=self.conn)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['stypdiff'],
+ 'value': row['stypdiff']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_canonical(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of canonical functions available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': ''}]
+ data = request.args
+ canonical = True
+
+ try:
+ # We want to send data only if in we are in edit mode
+ # else we will disable the combobox
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ getoid=True, data=data, conn=self.conn)
+ if SQL:
+ status, oid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=oid)
+ # If oid is None then do not run SQL
+ if oid is None:
+ canonical = False
+
+ SQL = render_template("/".join([self.template_path,
+ self._GET_SUBTYPES_SQL]),
+ canonical=canonical, conn=self.conn, oid=oid)
+ if SQL:
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['canonical'],
+ 'value': row['canonical']})
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def get_external_functions_list(self, gid, sid, did, scid, tid=None):
+ """
+ This function will return list of external functions available
+ as AJAX response.
+ """
+ res = [{'label': '', 'value': '', 'cbtype': 'all'}]
+
+ try:
+ # The SQL generated below will populate Input/Output/Send/
+ # Receive/Analyze/TypModeIN/TypModOUT combo box
+ sql = render_template("/".join([self.template_path,
+ self._GET_EXTERNAL_FUNCTIONS_SQL]),
+ extfunc=True)
+ if sql:
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['func'], 'value': row['func'],
+ 'cbtype': 'all'})
+
+ # The SQL generated below will populate TypModeIN combo box
+ sql = render_template("/".join([self.template_path,
+ self._GET_EXTERNAL_FUNCTIONS_SQL]),
+ typemodin=True)
+ if sql:
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['func'], 'value': row['func'],
+ 'cbtype': 'typmodin'})
+
+ # The SQL generated below will populate TypModeIN combo box
+ self._get_data_for_type_modein(res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _get_data_for_type_modein(self, res):
+ """
+ Data for TypModeIN combo box
+ :param res: response object.
+ :return:
+ """
+ sql = render_template("/".join([self.template_path,
+ self._GET_EXTERNAL_FUNCTIONS_SQL]),
+ typemodout=True)
+ if sql:
+ status, rset = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['func'], 'value': row['func'],
+ 'cbtype': 'typmodout'})
+
+ @staticmethod
+ def _checks_for_create_type(data):
+ required_args = {
+ 'name': 'Name',
+ 'typtype': 'Type'
+ }
+ for arg in required_args:
+ if arg not in data:
+ return True, make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ # Additional checks goes here
+ # If type is range then check if subtype is defined or not
+ if data and data[arg] == 'r' and \
+ ('typname' not in data or data['typname'] is None):
+ return True, make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Subtype must be defined for range types.'
+ )
+ )
+ # If type is external then check if input/output
+ # conversion function is defined
+ if data and data[arg] == 'b' and (
+ 'typinput' not in data or
+ 'typoutput' not in data or
+ data['typinput'] is None or
+ data['typoutput'] is None):
+ return True, make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'External types require both input and output '
+ 'conversion functions.'
+ )
+ )
+ return False, ''
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will creates new the type object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ is_error, errmsg = TypeView._checks_for_create_type(data)
+ if is_error:
+ return errmsg
+
+ # To format privileges coming from client
+ if 'typacl' in data and data['typacl'] is not None:
+ data['typacl'] = parse_priv_to_db(data['typacl'], self.acl)
+
+ data = self._convert_for_sql(data)
+
+ try:
+ if 'composite' in data and len(data['composite']) > 0:
+ for each_type in data['composite']:
+ each_type = self.convert_length_precision_to_string(
+ each_type)
+ each_type['cltype'] = self._cltype_formatter(
+ each_type['type'])
+ each_type['hasSqrBracket'] = self.hasSqrBracket
+
+ of_type = data.get('typtype', None)
+ if of_type in ('N', 'V'):
+ data = self.convert_length_precision_to_string(data)
+ data['cltype'] = self._cltype_formatter(data['type'])
+ data['hasSqrBracket'] = self.hasSqrBracket
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if 'schema' in data:
+ # we need scid to update in browser tree
+ SQL = render_template("/".join([self.template_path,
+ 'get_scid.sql']),
+ schema=data['schema'], conn=self.conn)
+ status, scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=scid)
+
+ # we need oid to add object in tree at browser
+ SQL = render_template("/".join([self.template_path,
+ self._OID_SQL]),
+ scid=scid, data=data, conn=self.conn)
+ status, tid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=tid)
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ scid,
+ data['name'],
+ icon="icon-type"
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, tid):
+ """
+ This function will updates the existing type object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ """
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ try:
+ SQL, name = self.get_sql(gid, sid, data, scid, tid)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template("/".join([self.template_path,
+ 'get_scid.sql']),
+ tid=tid, conn=self.conn)
+
+ # Get updated schema oid
+ status, scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ other_node_info = {}
+ if 'description' in data:
+ other_node_info['description'] = data['description']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ tid,
+ scid,
+ name,
+ icon=self.icon_str % self.node_type,
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ def _get_req_delete_data(self, tid, only_sql):
+ """
+ This function get data from request
+ :param tid: Table Id
+ :param only_sql: Flag for sql only.
+ :return: data and cascade flag.
+ """
+ if tid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [tid]}
+
+ cascade = self._check_cascade_operation()
+
+ return data, cascade
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, tid=None, only_sql=False):
+ """
+ This function will updates the existing type object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ only_sql: Return only sql if True
+ """
+ data, cascade = self._get_req_delete_data(tid, only_sql)
+
+ try:
+ for tid in data['ids']:
+ sql = render_template(
+ "/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ if not res['rows']:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=gettext(
+ 'The specified type could not be found.\n'
+ )
+ )
+
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+
+ sql = render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data,
+ cascade=cascade,
+ conn=self.conn)
+
+ # Used for schema diff tool
+ if only_sql:
+ return sql
+
+ status, res = self.conn.execute_scalar(sql)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("Type dropped"),
+ data={
+ 'id': tid,
+ 'scid': scid
+ }
+ )
+
+ except Exception as e:
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, tid=None):
+ """
+ This function will generates modified sql for type object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ """
+ req = request.args
+ data = dict()
+
+ # converting nested request data in proper json format
+ for key, val in req.items():
+ if key in ['composite', 'enum', 'seclabels', 'typacl']:
+ data[key] = json.loads(val)
+ else:
+ data[key] = val
+
+ try:
+ sql, _ = self.get_sql(gid, sid, data, scid, tid)
+ # Most probably this is due to error
+ if not isinstance(sql, str):
+ return sql
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified SQL"
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+ except Exception as e:
+ internal_server_error(errormsg=str(e))
+
+ def _convert_for_sql(self, data):
+ """
+ This function will convert combobox values into
+ readable format for sql & msql function
+ """
+ # Convert combobox value into readable format
+
+ if 'typstorage' in data and data['typstorage'] is not None:
+ if data['typstorage'] == 'p':
+ data['typstorage'] = 'PLAIN'
+ elif data['typstorage'] == 'e':
+ data['typstorage'] = 'EXTERNAL'
+ elif data['typstorage'] == 'm':
+ data['typstorage'] = 'MAIN'
+ elif data['typstorage'] == 'x':
+ data['typstorage'] = 'EXTENDED'
+
+ if 'typalign' in data and data['typalign'] is not None:
+ if data['typalign'] == 'c':
+ data['typalign'] = 'char'
+ elif data['typalign'] == 's':
+ data['typalign'] = 'int2'
+ elif data['typalign'] == 'i':
+ data['typalign'] = 'int4'
+ elif data['typalign'] == 'd':
+ data['typalign'] = 'double'
+
+ return data
+
+ def _get_new_sql(self, data, is_sql):
+ """
+ Used by get_sql internally for new type SQL
+ :param data: input data
+ :param is_sql: is sql
+ :return: generated SQL
+ """
+ required_args = [
+ 'name',
+ 'typtype'
+ ]
+
+ definition_incomplete = "-- definition incomplete"
+ for arg in required_args:
+ if arg not in data:
+ return definition_incomplete
+
+ # Additional checks go here
+ # If type is range then check if subtype is defined or not
+ if data.get(arg, None) == 'r' and \
+ data.get('typname', None) is None:
+ return definition_incomplete
+
+ # If type is external then check if input/output
+ # conversion function is defined
+ if data.get(arg, None) == 'b' and (
+ data.get('typinput', None) is None or
+ data.get('typoutput', None) is None):
+ return definition_incomplete
+
+ # Privileges
+ if data.get('typacl', None):
+ data['typacl'] = parse_priv_to_db(data['typacl'], self.acl)
+
+ data = self._convert_for_sql(data)
+
+ if len(data.get('composite', [])) > 0:
+ for each_type in data['composite']:
+ each_type = self.convert_length_precision_to_string(
+ each_type)
+ each_type['cltype'] = self._cltype_formatter(
+ each_type['type'])
+ each_type['hasSqrBracket'] = self.hasSqrBracket
+
+ of_type = data.get('typtype', None)
+ if of_type in ('N', 'V', 'A'):
+ data = self.convert_length_precision_to_string(data)
+ data['cltype'] = self._cltype_formatter(data['type'])
+ data['hasSqrBracket'] = self.hasSqrBracket
+ if of_type == 'V':
+ data['typndims'] = data['maxsize']
+
+ SQL = render_template("/".join([self.template_path,
+ self._CREATE_SQL]),
+ data=data, conn=self.conn, is_sql=is_sql)
+
+ return SQL, data['name']
+
+ def get_sql(self, gid, sid, data, scid, tid=None, is_sql=False):
+ """
+ This function will generate sql from model data
+ """
+ if tid is None:
+ return self._get_new_sql(data, is_sql)
+
+ for key in ['added', 'changed', 'deleted']:
+ if key in data.get('typacl', []):
+ data['typacl'][key] = parse_priv_to_db(
+ data['typacl'][key], self.acl)
+
+ for each_type in data.get('composite', {}).get(key, []):
+ each_type = self. \
+ convert_length_precision_to_string(each_type)
+ if 'type' in each_type:
+ each_type['cltype'] = self._cltype_formatter(
+ each_type['type'])
+ each_type['hasSqrBracket'] = self.hasSqrBracket
+
+ of_type = data.get('typtype', None)
+ if of_type in ('N', 'V', 'A'):
+ data = self.convert_length_precision_to_string(data)
+ data['cltype'] = self._cltype_formatter(data['type'])
+ data['hasSqrBracket'] = self.hasSqrBracket
+
+ if of_type == 'V':
+ data['typndims'] = data['maxsize']
+
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the type in the database.")
+ )
+
+ # Making copy of output for future use
+ old_data = dict(res['rows'][0])
+
+ SQL = render_template("/".join([self.template_path,
+ self._ACL_SQL]),
+ scid=scid, tid=tid)
+ status, acl = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ old_data['typacl'] = []
+
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ old_data[row['deftype']] = \
+ (old_data.get(row['deftype'], None) or []).append(priv)
+
+ # Calling function to check and additional properties if available
+ old_data.update(self.additional_properties(old_data, tid))
+ old_data = self._convert_for_sql(old_data)
+
+ # If typname or collname is changed while comparing
+ # two schemas then we need to drop type and recreate it
+ render_sql = self._UPDATE_SQL
+ if any([key in data for key in
+ ['typtype', 'typname', 'collname', 'typinput', 'typoutput']]):
+ render_sql = 'type_schema_diff.sql'
+
+ SQL = render_template(
+ "/".join([self.template_path, render_sql]),
+ data=data, o_data=old_data, conn=self.conn
+ )
+
+ return SQL, old_data['name']
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, tid, **kwargs):
+ """
+ This function will generates reverse engineered sql for type object
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ json_resp: True then return json response
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._PROPERTIES_SQL]),
+ scid=scid, tid=tid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ show_system_objects=self.blueprint.show_system_objects
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(
+ gettext("Could not find the type in the database.")
+ )
+ # Making copy of output for future use
+ data = dict(res['rows'][0])
+ if target_schema:
+ data['schema'] = target_schema
+
+ SQL = render_template("/".join([self.template_path, self._ACL_SQL]),
+ scid=scid, tid=tid)
+ status, acl = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ # We will set get privileges from acl sql so we don't need
+ # it from properties sql
+ data['typacl'] = []
+
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ if row['deftype'] in data:
+ data[row['deftype']].append(priv)
+ else:
+ data[row['deftype']] = [priv]
+
+ # Privileges
+ if 'typacl' in data and data['typacl'] is not None:
+ data['nspacl'] = parse_priv_to_db(data['typacl'], self.acl)
+
+ # Calling function to check and additional properties if available
+ data.update(self.additional_properties(data, tid))
+
+ # We do not want to display table which has '-' value
+ # setting them to None so that jinja avoid displaying them
+ for k in data:
+ if data[k] == '-':
+ data[k] = None
+
+ SQL, _ = self.get_sql(gid, sid, data, scid, tid=None, is_sql=True)
+ # Most probably this is due to error
+ if not isinstance(SQL, str):
+ return SQL
+ # We are appending headers here for sql panel
+ sql_header = "-- Type: {0}\n\n-- ".format(data['name'])
+
+ sql_header += render_template("/".join([self.template_path,
+ self._DELETE_SQL]),
+ data=data, conn=self.conn)
+ SQL = sql_header + '\n\n' + SQL
+
+ if not json_resp:
+ return SQL.strip('\n')
+
+ return ajax_response(response=SQL)
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependents and return ajax response
+ for the type node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ """
+ dependents_result = self.get_dependents(
+ self.conn, tid
+ )
+
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, tid):
+ """
+ This function get the dependencies and return ajax response
+ for the type node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ tid: Type ID
+ """
+ # For composite type typrelid is required to fetch dependencies.
+ type_where = "WHERE (dep.objid={0}::oid OR dep.objid=(select typrelid \
+ from pg_type where oid = {0}::oid))".format(tid)
+ dependencies_result = self.get_dependencies(
+ self.conn, tid, where=type_where
+ )
+
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid):
+ """
+ This function will fetch the list of all the types for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join([self.template_path,
+ self._NODES_SQL]),
+ scid=scid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ res[row['name']] = data
+
+ return res
+
+ def get_sql_from_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('oid')
+ data = kwargs.get('data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if data:
+ if target_schema:
+ data['schema'] = target_schema
+ sql, _ = self.get_sql(gid=gid, sid=sid, scid=scid, data=data,
+ tid=oid)
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, tid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, tid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, tid=oid,
+ json_resp=False)
+ return sql
+
+
+SchemaDiffRegistry(blueprint.node_type, TypeView)
+TypeView.register_node_view(blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/coll-type.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/coll-type.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d473dba73eda9f788023ed04c66661053ab87a32
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/coll-type.svg
@@ -0,0 +1 @@
+coll-type
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/type.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/type.svg
new file mode 100644
index 0000000000000000000000000000000000000000..9e4e9deb7c505ecf85f7e66baf9c0a9cef8264e9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/img/type.svg
@@ -0,0 +1 @@
+type
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.js
new file mode 100644
index 0000000000000000000000000000000000000000..1dcd22ead5f3f345d65c40ae82b0a1a922380c4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.js
@@ -0,0 +1,104 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import TypeSchema, { getCompositeSchema, getRangeSchema, getExternalSchema, getDataTypeSchema } from './type.ui';
+
+define('pgadmin.node.type', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser', 'pgadmin.node.schema.dir/child',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'pgadmin.browser.collection',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+ if (!pgBrowser.Nodes['coll-type']) {
+ pgBrowser.Nodes['coll-type'] =
+ pgBrowser.Collection.extend({
+ node: 'type',
+ label: gettext('Types'),
+ type: 'coll-type',
+ columns: ['name', 'typeowner', 'description'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ if (!pgBrowser.Nodes['type']) {
+ pgBrowser.Nodes['type'] = schemaChild.SchemaChildNode.extend({
+ type: 'type',
+ sqlAlterHelp: 'sql-altertype.html',
+ sqlCreateHelp: 'sql-createtype.html',
+ dialogHelp: url_for('help.static', {'filename': 'type_dialog.html'}),
+ label: gettext('Type'),
+ collection_type: 'coll-type',
+ hasSQL: true,
+ hasDepends: true,
+ width: pgBrowser.stdW.md + 'px',
+ Init: function() {
+ /* Avoid multiple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_type_on_coll', node: 'coll-type', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Type...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_type', node: 'type', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Type...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_type', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Type...'),
+ data: {action: 'create', check: false},
+ enable: 'canCreate',
+ },
+ ]);
+
+ },
+ ext_funcs: undefined,
+ getSchema: (treeNodeInfo, itemNodeData) => {
+ let nodeObj = pgAdmin.Browser.Nodes['type'];
+ return new TypeSchema(
+ (privileges)=>getNodePrivilegeRoleSchema(nodeObj, treeNodeInfo, itemNodeData, privileges),
+ ()=>getCompositeSchema(nodeObj, treeNodeInfo, itemNodeData),
+ ()=>getRangeSchema(nodeObj, treeNodeInfo, itemNodeData),
+ ()=>getExternalSchema(nodeObj, treeNodeInfo, itemNodeData),
+ ()=>getDataTypeSchema(nodeObj, treeNodeInfo, itemNodeData),
+ {
+ roles:() => getNodeListByName('role', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ schemas:() => getNodeListByName('schema', treeNodeInfo, itemNodeData, {
+ cacheLevel: 'database'
+ }),
+ server_info: pgBrowser.serverInfo[treeNodeInfo.server._id],
+ node_info: treeNodeInfo
+ },
+ {
+ typeowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: 'catalog' in treeNodeInfo ? treeNodeInfo.catalog.label : treeNodeInfo.schema.label,
+ // If create mode then by default open composite type
+ typtype: 'c'
+ }
+ );
+ }
+ });
+ }
+ return pgBrowser.Nodes['type'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..6fd1a883bd720b57c3570238d35feccb63326dbc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/static/js/type.ui.js
@@ -0,0 +1,1493 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+
+import { getNodeAjaxOptions } from '../../../../../../../static/js/node_ajax';
+import _ from 'lodash';
+import getApiInstance from 'sources/api_instance';
+import { isEmptyString } from 'sources/validators';
+
+function isTlengthEditable(state, options) {
+ // We will store type from selected from combobox
+ let of_type = state.type;
+ // iterating over all the types
+ _.each(options, function(o) {
+ // if type from selected from combobox matches in options
+ if ( of_type == o.value ) {
+ // if length is allowed for selected type
+ if(o.length)
+ {
+ // set the values in state
+ state.is_tlength = true;
+ state.min_val = o.min_val;
+ state.max_val = o.max_val;
+ } else {
+ // set the values in state
+ state.is_tlength = false;
+ }
+ }
+ });
+ return state.is_tlength;
+}
+
+function isPrecisionEditable(state, options) {
+ // We will store type from selected from combobox
+ let of_type = state.type;
+ // iterating over all the types
+ _.each(options, function(o) {
+ // if type from selected from combobox matches in options
+ if ( of_type == o.value ) {
+ // if precession is allowed for selected type
+ if(o.precision)
+ {
+ // set the values in model
+ state.is_precision = true;
+ state.min_val = o.min_val;
+ state.max_val = o.max_val;
+ } else {
+ // set the values in model
+ state.is_precision = false;
+ }
+ }
+ });
+ return state.is_precision;
+}
+
+function getTypes(nodeObj, treeNodeInfo, itemNodeData) {
+ return getNodeAjaxOptions('get_types', nodeObj, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'domain'
+ });
+}
+
+function getCompositeSchema(nodeObj, treeNodeInfo, itemNodeData) {
+ return new CompositeSchema(
+ {
+ types: () => { return getTypes(nodeObj, treeNodeInfo, itemNodeData); },
+ collations: () => getNodeAjaxOptions('get_collations', nodeObj, treeNodeInfo, itemNodeData)
+ }
+ );
+}
+
+function getRangeSchema(nodeObj, treeNodeInfo, itemNodeData) {
+ return new RangeSchema(
+ {
+ typnameList: () => getNodeAjaxOptions('get_stypes', nodeObj, treeNodeInfo, itemNodeData),
+ getSubOpClass: (typname) => {
+ return new Promise((resolve, reject)=>{
+ const api = getApiInstance();
+
+ let _url = nodeObj.generate_url(
+ null, 'get_subopclass', itemNodeData, false,
+ treeNodeInfo,
+ );
+ let data;
+
+ if(!_.isUndefined(typname) && typname != ''){
+ api.get(_url, {
+ params: {
+ 'typname' : typname
+ }
+ }).then(res=>{
+ data = res.data.data;
+ resolve(data);
+ }).catch((err)=>{
+ reject(err);
+ });
+ } else {
+ resolve(data);
+ }
+ });
+ },
+ collationsList: () => getNodeAjaxOptions('get_collations', nodeObj, treeNodeInfo, itemNodeData),
+ getCanonicalFunctions: (name) => {
+ return new Promise((resolve, reject)=>{
+ const api = getApiInstance();
+
+ let _url = nodeObj.generate_url(
+ null, 'get_canonical', itemNodeData, false,
+ treeNodeInfo,
+ );
+ let data = [];
+
+ if(!_.isUndefined(name) && name != '' && name != null){
+ api.get(_url, {
+ params: {
+ 'name' : name
+ }
+ }).then(res=>{
+ data = res.data.data;
+ resolve(data);
+ }).catch((err)=>{
+ reject(err);
+ });
+ } else {
+ resolve(data);
+ }
+ });
+ },
+ getSubDiffFunctions: (typname, opcname) => {
+ return new Promise((resolve, reject)=>{
+ const api = getApiInstance();
+
+ let _url = nodeObj.generate_url(
+ null, 'get_stypediff', itemNodeData, false,
+ treeNodeInfo,
+ );
+ let data;
+
+ if(!_.isUndefined(typname) && typname != '' &&
+ !_.isUndefined(opcname) && opcname != ''){
+ api.get(_url, {
+ params: {
+ 'typname' : typname,
+ 'opcname': opcname
+ }
+ }).then(res=>{
+ data = res.data.data;
+ resolve(data);
+ }).catch((err)=>{
+ reject(err);
+ });
+ } else {
+ resolve(data);
+ }
+ });
+ },
+ }, {
+ node_info: treeNodeInfo
+ }
+ );
+}
+
+function getExternalSchema(nodeObj, treeNodeInfo, itemNodeData) {
+ return new ExternalSchema(
+ {
+ externalFunctionsList: () => getNodeAjaxOptions('get_external_functions', nodeObj, treeNodeInfo, itemNodeData),
+ types: () => { return getTypes(nodeObj, treeNodeInfo, itemNodeData); },
+ }, {
+ node_info: treeNodeInfo
+ }
+ );
+}
+
+function getDataTypeSchema(nodeObj, treeNodeInfo, itemNodeData) {
+ return new DataTypeSchema(
+ {
+ types: () => { return getTypes(nodeObj, treeNodeInfo, itemNodeData); }
+ }
+ );
+}
+
+function isVisible(state, type) {
+ return state.typtype === type;
+}
+
+class EnumerationSchema extends BaseUISchema {
+
+ constructor() {
+ super({
+ oid: undefined,
+ label: undefined,
+ });
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'label', label: gettext('Label'),
+ type: 'text', cell: 'text', minWidth: 640,
+ editable: (state) => {
+ return _.isUndefined(obj.isNew) ? true : obj.isNew(state);
+ }
+ }
+ ];
+ }
+}
+
+class RangeSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, node_info={}, initValues={}) {
+ super({
+ typname: null,
+ oid: undefined,
+ is_sys_type: false,
+ ...initValues
+ });
+ this.fieldOptions = {
+ typnameList: [],
+ collationsList: [],
+ ...fieldOptions
+ };
+ this.nodeInfo = {
+ ...node_info.node_info
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ // We will disable range type control in edit mode
+ id: 'typname', label: gettext('Subtype'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.typnameList,
+ optionsLoaded: (options) => { obj.fieldOptions.typnameList = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ if(options && options.length > 0) {
+ state.subtypes = options;
+ }
+ options.forEach((option) => {
+ if(option?.label == '') {
+ return;
+ }
+ res.push({ label: option.label, value: option.value });
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Range Type'),
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ }, {
+ id: 'opcname', label: gettext('Subtype operator class'), cell: 'string',
+ mode: ['properties', 'create', 'edit'], group: gettext('Range Type'),
+ disabled: () => obj.inCatalog(),
+ readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ deps: ['typname'],
+ type: (state)=>{
+ return {
+ type: 'select',
+ options: () => obj.fieldOptions.getSubOpClass(state.typname),
+ optionsReloadBasis: state.typname,
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ }, {
+ id: 'collname', label: gettext('Collation'), cell: 'string',
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.collationsList,
+ optionsLoaded: (options) => { obj.fieldOptions.collationsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Range Type'),
+ deps: ['typname'],
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ disabled: (state) => {
+ let disableCollNameControl = obj.inCatalog();
+ if (disableCollNameControl)
+ return disableCollNameControl;
+
+ // To check if collation is allowed?
+ let of_subtype = state.typname;
+ if(!_.isUndefined(of_subtype)) {
+ // iterating over all the types
+ _.each(state.subtypes, function(s) {
+ // if subtype from selected from combobox matches
+ if ( of_subtype === s.label ) {
+ // if collation is allowed for selected subtype
+ // then enable it else disable it
+ disableCollNameControl = s.is_collate;
+ }
+ });
+ }
+ // If is_collate is true then do not disable
+ if(!disableCollNameControl) {
+ state.collname = '';
+ this.options = [];
+ }
+
+ return !disableCollNameControl;
+ },
+ readonly: function(state) {
+ return !obj.isNew(state);
+ }
+ }, {
+ id: 'rngcanonical', label: gettext('Canonical function'), cell: 'string',
+ type: (state)=>{
+ return {
+ type: 'select',
+ options: () => obj.fieldOptions.getCanonicalFunctions(state.name),
+ optionsReloadBasis: state.typname,
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Range Type'),
+ disabled: () => obj.inCatalog(),
+ readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ deps: ['name', 'typname'],
+ }, {
+ id: 'rngsubdiff', label: gettext('Subtype diff function'), cell: 'string',
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Range Type'),
+ disabled: () => obj.inCatalog(),
+ readonly: function(state) {
+ return !obj.isNew(state);
+ },
+ deps: ['typname', 'opcname'],
+ type: (state)=>{
+ let fetchOptionsBasis = state.typname + state.opcname;
+ return {
+ type: 'select',
+ options: () => obj.fieldOptions.getSubDiffFunctions(state.typname, state.opcname),
+ optionsReloadBasis: fetchOptionsBasis,
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ return obj.getFilterOptions(state, options);
+ }
+ }
+ };
+ },
+ }
+ ];
+ }
+
+ validate(state, setError) {
+
+ let errmsg = null;
+
+ if(state.typtype === 'r') {
+ if (isEmptyString(state.typname)) {
+ errmsg = gettext('Subtype cannot be empty');
+ setError('typname', errmsg);
+ return true;
+ }
+ }
+ }
+}
+
+class ExternalSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, node_info={}, initValues={}) {
+ super({
+ name: null,
+ typinput: undefined,
+ oid: undefined,
+ is_sys_type: false,
+ typtype: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ types: [],
+ externalFunctionsList: [],
+ ...fieldOptions
+ };
+ this.fieldOptions.typeCategory = [
+ {label :'Array types', value : 'A'},
+ {label :'Boolean types', value : 'B'},
+ {label :'Composite types', value : 'C'},
+ {label :'Date/time types', value : 'D'},
+ {label :'Enum types', value : 'E'},
+ {label :'Geometric types', value : 'G'},
+ {label :'Network address types', value : 'I'},
+ {label :'Numeric types', value : 'N'},
+ {label :'Pseudo-types', value : 'P'},
+ {label :'String types', value : 'S'},
+ {label :'Timespan types', value : 'T'},
+ {label :'User-defined types', value : 'U'},
+ {label :'Bit-string types', value : 'V'},
+ {label :'unknown type', value : 'X'},
+ ];
+ this.fieldOptions.typeAlignOptions = [
+ {label: 'char', value: 'c'},
+ {label: 'int2', value: 's'},
+ {label: 'int4', value: 'i'},
+ {label: 'double', value: 'd'},
+ ];
+ this.fieldOptions.typStorageOptions = [
+ {label: 'PLAIN', value: 'p'},
+ {label: 'EXTERNAL', value: 'e'},
+ {label: 'MAIN', value: 'm'},
+ {label: 'EXTENDED', value: 'x'},
+ ];
+ this.nodeInfo = {
+ ...node_info.node_info
+ };
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ // Function will help us to fill combobox
+ external_func_combo(control) {
+ let result = [];
+ _.each(control, function(item) {
+
+ if(item?.label == '') {
+ return;
+ }
+ // if type from selected from combobox matches in options
+ if ( item.cbtype == 'all' ) {
+ result.push(item);
+ }
+ });
+ return result;
+ }
+
+ filterFunctionOptions(state, options) {
+ let res = [];
+ if (state && this.isNew(state)) {
+ res = this.external_func_combo(options);
+ } else {
+ res = options;
+ }
+ return res;
+ }
+
+ getFunctionType(state) {
+ let obj = this;
+ return {
+ type: 'select',
+ options: obj.fieldOptions.externalFunctionsList,
+ optionsLoaded: (options) => { obj.fieldOptions.externalFunctionsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ return obj.filterFunctionOptions(state, options);
+ }
+ }
+ };
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'spacer_ctrl', group: gettext('Required'), mode: ['edit', 'create'], type: 'spacer',
+ },{
+ id: 'typinput', label: gettext('Input function'),
+ mode: ['properties', 'create', 'edit'], group: gettext('Required'),
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ type: (state) => {
+ return obj.getFunctionType(state);
+ },
+ }, {
+ id: 'typoutput', label: gettext('Output function'),
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Required'),
+ type: (state) => {
+ return obj.getFunctionType(state);
+ },
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ disabled: () => obj.inCatalog(),
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'spacer_ctrl_optional_1', group: gettext('Optional-1'), mode: ['edit', 'create'], type: 'spacer',
+ },{
+ id: 'typreceive', label: gettext('Receive function'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.externalFunctionsList,
+ optionsLoaded: (options) => { obj.fieldOptions.externalFunctionsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ res = obj.external_func_combo(options);
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ },
+ group: gettext('Optional-1'),
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typsend', label: gettext('Send function'),
+ group: gettext('Optional-1'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.externalFunctionsList,
+ optionsLoaded: (options) => { obj.fieldOptions.externalFunctionsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ return obj.filterFunctionOptions(state, options);
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typmodin', label: gettext('Typmod in function'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.externalFunctionsList,
+ optionsLoaded: (options) => { obj.fieldOptions.externalFunctionsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ _.each(options, function(item) {
+ if(item?.label == '') {
+ return;
+ }
+ // if type from selected from combobox matches in options
+ if ( item.cbtype === 'typmodin' || item.cbtype === 'all') {
+ res.push(item);
+ }
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'], group: gettext('Optional-1'),
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typmodout', label: gettext('Typmod out function'),
+ group: gettext('Optional-1'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.externalFunctionsList,
+ optionsLoaded: (options) => { obj.fieldOptions.externalFunctionsList = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ _.each(options, function(item) {
+ if(item?.label == '') {
+ return;
+ }
+ // if type from selected from combobox matches in options
+ if ( item.cbtype === 'typmodout' || item.cbtype === 'all') {
+ res.push(item);
+ }
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'typlen', label: gettext('Internal length'),
+ cell: 'integer', group: gettext('Optional-1'),
+ type: 'int', mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'variable', label: gettext('Variable?'), cell: 'switch',
+ group: gettext('Optional-1'), type: 'switch',
+ mode: ['create','edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'typdefault', label: gettext('Default?'),
+ cell: 'string', group: gettext('Optional-1'),
+ type: 'text', mode: ['properties', 'create','edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'typanalyze', label: gettext('Analyze function'),
+ group: gettext('Optional-1'),
+ type: (state) => {
+ return obj.getFunctionType(state);
+ },
+ mode: ['properties', 'create','edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typcategory', label: gettext('Category type'),
+ cell: 'string',
+ group: gettext('Optional-1'),
+ type: () => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.typeCategory,
+ optionsLoaded: (options) => { obj.fieldOptions.typeCategory = options; },
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ }
+ };
+ },
+ mode: ['properties', 'create','edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typispreferred', label: gettext('Preferred?'),
+ type: 'switch', mode: ['properties', 'create','edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ group: gettext('Optional-1'),
+ },{
+ id: 'spacer_ctrl_optional_2', group: gettext('Optional-2'), mode: ['edit', 'create'], type: 'spacer',
+ },{
+ id: 'element', label: gettext('Element type'),
+ group: gettext('Optional-2'),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.types,
+ controlProps: {
+ allowClear: true,
+ placeholder: '',
+ width: '100%',
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ _.each(options, function(item) {
+ if(item?.label == '') {
+ return;
+ }
+ // if type from selected from combobox matches in options
+ res.push(item);
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ },
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'typdelim', label: gettext('Delimiter'),
+ cell: 'string',
+ type: 'text',
+ mode: ['properties', 'create', 'edit'],
+ group: gettext('Optional-2'),
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ },{
+ id: 'typalign', label: gettext('Alignment type'),
+ cell: 'string', group: gettext('Optional-2'),
+ type: 'select',
+ options: obj.fieldOptions.typeAlignOptions,
+ mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ },{
+ id: 'typstorage', label: gettext('Storage type'),
+ type: 'select', mode: ['properties', 'create', 'edit'],
+ group: gettext('Optional-2'), cell: 'string',
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: true, placeholder: '', width: '100%' },
+ options: obj.fieldOptions.typStorageOptions,
+ },{
+ id: 'typbyval', label: gettext('Passed by value?'),
+ cell: 'switch',
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ group: gettext('Optional-2'),
+ },{
+ id: 'is_collatable', label: gettext('Collatable?'),
+ cell: 'switch', min_version: 90100, group: gettext('Optional-2'),
+ type: 'switch', mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ // End of extension tab
+ }];
+ }
+
+ validate(state, setError) {
+
+ let errmsg = null;
+
+ if(state.typtype === 'b') {
+
+ if (isEmptyString(state.typinput)) {
+ errmsg = gettext('Input function cannot be empty');
+ setError('typinput', errmsg);
+ return true;
+ }
+
+ if (isEmptyString(state.typoutput)) {
+ errmsg = gettext('Output function cannot be empty');
+ setError('typoutput', errmsg);
+ return true;
+ }
+ }
+ return false;
+ }
+}
+
+class CompositeSchema extends BaseUISchema {
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ oid: undefined,
+ is_sys_type: false,
+ attnum: undefined,
+ member_name: undefined,
+ type: undefined,
+ tlength: null,
+ is_tlength: false,
+ precision: undefined,
+ is_precision: false,
+ collation: undefined,
+ min_val: undefined,
+ max_val: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ types: [],
+ collations: [],
+ ...fieldOptions
+ };
+ this.type_options = {};
+ }
+
+ setTypeOptions(options) {
+ options.forEach((option)=>{
+ this.type_options[option.value] = {
+ ...option,
+ };
+ });
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ onTypeChange(state, changeSource) {
+ if(_.isArray(changeSource) && changeSource[2] == 'type') {
+ return {...state
+ , value: null
+ };
+ }
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'member_name', label: gettext('Member Name'),
+ type: 'text', cell: 'text'
+ },
+ {
+ id: 'type', label: gettext('Type'),
+ type: 'text',
+ cell: ()=>({
+ cell: 'select', options: obj.fieldOptions.types,
+ optionsLoaded: (options)=>{obj.setTypeOptions(options);},
+ controlProps: {
+ allowClear: false,
+ }
+ }),
+ }, {
+ // Note: There are ambiguities in the PG catalogs and docs between
+ // precision and scale. In the UI, we try to follow the docs as
+ // closely as possible, therefore we use Length/Precision and Scale
+ id: 'tlength', label: gettext('Length/Precision'), deps: ['type'], type: 'text',
+ disabled: false,
+ cell: 'int',
+ depChange: (state, changeSource)=>{
+ if(_.isArray(changeSource) && changeSource[2] == 'type') {
+ state.tlength = null;
+ return {...state
+ , value: null
+ };
+ }
+ },
+ editable: (state)=>{
+ return isTlengthEditable(state, obj.type_options);
+ }
+ }, {
+ // Note: There are ambiguities in the PG catalogs and docs between
+ // precision and scale. In the UI, we try to follow the docs as
+ // closely as possible, therefore we use Length/Precision and Scale
+ id: 'precision', label: gettext('Scale'), deps: ['type'],
+ type: 'text', disabled: false, cell: 'int',
+ depChange: (state, changeSource)=>{
+ return obj.onTypeChange(state, changeSource);
+ },
+ editable: (state) => {
+ return isPrecisionEditable(state, obj.type_options);
+ },
+ }, {
+ id: 'collation', label: gettext('Collation'), type: 'text',
+ depChange: (state, changeSource)=>{
+ return obj.onTypeChange(state, changeSource);
+ },
+ cell: ()=>({
+ cell: 'select', options: obj.fieldOptions.collations,
+ controlProps: {
+ allowClear: false,
+ }
+ }),
+ deps: ['type'],
+ editable: (state) => {
+ // We will store type from selected from combobox
+ let of_type = state.type;
+ let flag = false;
+ if(obj.type_options) {
+ // iterating over all the types
+ _.each(obj.type_options, function(o) {
+ // if type from selected from combobox matches in options
+ if ( of_type == o.value ) {
+ if(o.is_collatable) {
+ flag = true;
+ return;
+ }
+ }
+ });
+ }
+ return flag;
+ },
+ }];
+ }
+
+ validate(state, setError) {
+
+ let self = this,
+ errmsg = null;
+
+ if(self.top?.sessData?.typtype === 'c') {
+ if (isEmptyString(state.member_name)) {
+ errmsg = gettext('Please specify the value for member name.');
+ setError('member_name', errmsg);
+ return true;
+ } else if(isEmptyString(state.type)) {
+ errmsg = gettext('Please specify the type.');
+ setError('type', errmsg);
+ return true;
+ }
+ if(_.isUndefined(errmsg) || errmsg == null) {
+ setError('member_name', null);
+ setError('type', null);
+ }
+ }
+ return false;
+ }
+}
+
+class DataTypeSchema extends BaseUISchema {
+
+ constructor(fieldOptions = {}, initValues={}) {
+ super({
+ oid: undefined,
+ is_sys_type: false,
+ attnum: undefined,
+ member_name: undefined,
+ type: undefined,
+ tlength: null,
+ is_tlength: false,
+ precision: undefined,
+ is_precision: false,
+ min_val: undefined,
+ max_val: undefined,
+ attlen: undefined,
+ min_val_attlen: undefined,
+ max_val_attlen: undefined,
+ attprecision: null,
+ min_val_attprecision: undefined,
+ max_val_attprecision: undefined,
+ ...initValues
+ });
+ this.types = fieldOptions.types;
+ this.type_options = [];
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let dataTypeObj = this;
+ return [{
+ id: 'type',
+ label: gettext('Data Type'),
+ group: gettext('Definition'),
+ mode: ['edit', 'create'],
+ disabled: false,
+ readonly: function (state) {
+ return !dataTypeObj.isNew(state);
+ },
+ node: 'type',
+ cache_node: 'domain',
+ editable: true,
+ deps: ['typtype'],
+ type: (state) => {
+ return {
+ type: 'select',
+ options: dataTypeObj.types,
+ optionsLoaded: (options) => { dataTypeObj.types = options; },
+ controlProps: {
+ allowClear: false,
+ filter: (options) => {
+ let data_types = [];
+ options.forEach((option) => {
+ if (!(option.value.includes('[]'))) {
+ data_types.push(option);
+ }
+ });
+ state.type_options = data_types;
+ return data_types;
+ }
+ }
+ };
+ }
+ },{
+ id: 'maxsize',
+ group: gettext('Definition'),
+ label: gettext('Size'),
+ type: 'int',
+ deps: ['typtype'],
+ cell: 'int',
+ mode: ['create', 'edit'],
+ readonly: function (state) {
+ return !dataTypeObj.isNew(state);
+ },
+ visible: (state) => isVisible(state, 'V'),
+ },{
+ // Note: There are ambiguities in the PG catalogs and docs between
+ // precision and scale. In the UI, we try to follow the docs as
+ // closely as possible, therefore we use Length/Precision and Scale
+ id: 'tlength',
+ group: gettext('Data Type'),
+ label: gettext('Length/Precision'),
+ mode: ['edit', 'create'],
+ deps: ['type'],
+ type: 'text',
+ cell: 'int',
+ readonly: function (state) {
+ return !dataTypeObj.isNew(state);
+ },
+ visible: (state) => isVisible(state, 'N'),
+ disabled: function(state) {
+
+ let of_type = state.type,
+ flag = true;
+ if (state.type_options) {
+ _.each(state.type_options, function (o) {
+ if (of_type == o.value) {
+ if (o.length) {
+ state.min_val_attlen = o.min_val;
+ state.max_val_attlen = o.max_val;
+ flag = false;
+ }
+ }
+ });
+ }
+ flag && setTimeout(function () {
+ if (state.attlen) {
+ state.attlen = null;
+ }
+ }, 10);
+ return flag;
+ },
+ editable: (state)=>{
+ let options = state.type_options;
+ return isTlengthEditable(state, options);
+ }
+ },{
+ // Note: There are ambiguities in the PG catalogs and docs between
+ // precision and scale. In the UI, we try to follow the docs as
+ // closely as possible, therefore we use Length/Precision and Scale
+ id: 'precision',
+ group: gettext('Data Type'),
+ label: gettext('Scale'),
+ mode: ['edit', 'create'],
+ deps: ['type'],
+ type: 'text',
+ readonly: function (state) {
+ return !dataTypeObj.isNew(state);
+ },
+ cell: 'int',
+ visible: (state) => isVisible(state, 'N'),
+ disabled: function(state) {
+ let of_type = state.type,
+ flag = true;
+ _.each(state.type_options, function(o) {
+ if ( of_type == o.value ) {
+ if(o.precision) {
+ state.min_val_attprecision = 0;
+ state.max_val_attprecision = o.max_val;
+ flag = false;
+ }
+ }
+ });
+
+ flag && setTimeout(function() {
+ if(state.attprecision) {
+ state.attprecision = null;
+ }
+ },10);
+ return flag;
+ },
+ editable: function(state) {
+ let options = state.type_options;
+ return isPrecisionEditable(state, options);
+ },
+ }];
+ }
+}
+
+export default class TypeSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, compositeSchema, rangeSchema, externalSchema, dataTypeSchema, fieldOptions = {}, initValues={}) {
+ super({
+ name: null,
+ oid: undefined,
+ is_sys_type: false,
+ typtype: undefined,
+ typeowner: undefined,
+ schema: undefined,
+ ...initValues
+ });
+ this.fieldOptions = {
+ roles: [],
+ schemas: [],
+ server_info: [],
+ node_info: [],
+ ...fieldOptions
+ };
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.compositeSchema = compositeSchema(); // create only once the composite schema to avoid initializing the current (i.e. top)
+ this.getRangeSchema = rangeSchema;
+ this.getExternalSchema = externalSchema;
+ this.getDataTypeSchema = dataTypeSchema;
+ this.nodeInfo = this.fieldOptions.node_info;
+ }
+
+ isInvalidColumnAdded(state) {
+
+ let tempCol = _.map(state.enum, 'label');
+ let dontAddColumn = false;
+
+ if(tempCol.length == 1 && tempCol[0] == undefined) {
+ dontAddColumn = true;
+ } else {
+ tempCol.forEach(function(enumVal) {
+ if(enumVal == undefined) {
+ dontAddColumn = true;
+ }
+ });
+ }
+ return dontAddColumn;
+ }
+
+ schemaCheck(state) {
+ if(this.fieldOptions?.node_info?.schema) {
+ if(!state)
+ return true;
+ if (this.isNew(state)) {
+ return false;
+ } else {
+ return state && state.typtype === 'p';
+ }
+ }
+ return true;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'string',
+ type: 'text', mode: ['properties', 'create', 'edit'],
+ noEmpty: true,
+ disabled: (state) => obj.schemaCheck(state),
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string',
+ type: 'text' , mode: ['properties'],
+ },{
+ id: 'typeowner', label: gettext('Owner'), cell: 'string',
+ mode: ['properties', 'create', 'edit'], noEmpty: true,
+ type: 'select', options: this.fieldOptions.roles,
+ controlProps: { allowClear: false },
+ disabled: () => obj.inCatalog(),
+ },{
+ id: 'schema', label: gettext('Schema'), cell: 'string',
+ mode: ['create', 'edit'], noEmpty: true,
+ disabled: (state) => obj.schemaCheck(state),
+ type: (state) => {
+ return {
+ type: 'select',
+ options: obj.fieldOptions.schemas,
+ optionsLoaded: (options) => { obj.fieldOptions.schemas = options; },
+ controlProps: {
+ allowClear: true,
+ filter: (options) => {
+ let res = [];
+ if (state && obj.isNew(state)) {
+ options.forEach((option) => {
+ // If schema name start with pg_* then we need to exclude them
+ if(option?.label.match(/^pg_/)) {
+ return;
+ }
+ res.push({ label: option.label, value: option.value, image: 'icon-schema' });
+ });
+ } else {
+ res = options;
+ }
+ return res;
+ }
+ }
+ };
+ }
+ },
+ {
+ id: 'typtype', label: gettext('Type'),
+ mode: ['create','edit'], group: gettext('Definition'),
+ type: 'select',
+ disabled: () => obj.inCatalog(),
+ readonly: function (state) {
+ return !obj.isNew(state);
+ },
+ controlProps: { allowClear: false },
+ options: function() {
+ let typetype = [
+ {label: gettext('Composite'), value: 'c'},
+ {label: gettext('Enumeration'), value: 'e'},
+ {label: gettext('External'), value: 'b'},
+ {label: gettext('Range'), value: 'r'},
+ {label: gettext('Shell'), value: 'p'},
+ ];
+ if (obj.fieldOptions.server_info.server_type === 'ppas' &&
+ obj.fieldOptions.server_info.version >= 90500){
+ typetype.push(
+ {label: gettext('Nested Table'), value: 'N'},
+ {label: gettext('Varying Array'), value: 'V'}
+ );
+ }
+ return typetype;
+ },
+ },
+ {
+ id: 'composite', label: gettext('Composite Type'),
+ editable: true, type: 'collection',
+ group: gettext('Definition'), mode: ['edit', 'create'],
+ uniqueCol : ['member_name'],
+ canAdd: true, canEdit: false, canDelete: true,
+ disabled: () => obj.inCatalog(),
+ schema: obj.compositeSchema,
+ deps: ['typtype'],
+ depChange: (state)=>{
+ if(_.isArray(state.composite) && state.composite.length > 0 && state.typtype !== 'c') {
+ state.composite.splice(0, state.composite.length);
+ }
+ },
+ visible: (state) => isVisible(state, 'c'),
+ },
+ {
+ id: 'enum', label: gettext('Enumeration type'),
+ schema: new EnumerationSchema(),
+ type: 'collection',
+ group: gettext('Definition'), mode: ['edit', 'create'],
+ canAddRow: function(state) {
+ return !obj.isInvalidColumnAdded(state);
+ },
+ canEdit: false,
+ canDeleteRow: function(state) {
+ // We will disable it if it's in 'edit' mode
+ return obj.isNew(state);
+ },
+ canEditRow: false,
+ disabled: () => obj.inCatalog(),
+ deps: ['typtype'],
+ uniqueCol : ['label'],
+ visible: (state) => isVisible(state, 'e'),
+ }, {
+ type: 'nested-fieldset',
+ group: gettext('Definition'),
+ label: '',
+ deps: ['typtype'],
+ mode: ['edit', 'create'],
+ visible: function(state) {
+ return state.typtype === 'N' || state.typtype === 'V';
+ },
+ schema: obj.getDataTypeSchema()
+ }, {
+ // We will disable range type control in edit mode
+ type: 'nested-fieldset',
+ group: gettext('Definition'),
+ label: '',
+ mode: ['edit', 'create'],
+ visible: (state) => isVisible(state, 'r'),
+ deps: ['typtype'],
+ schema: obj.getRangeSchema(),
+ }, {
+ type: 'nested-tab',
+ group: gettext('Definition'),
+ label: gettext('External Type'), deps: ['typtype'],
+ mode: ['create', 'edit'], tabPanelExtraClasses:'inline-tab-panel-padded',
+ visible: (state) => isVisible(state, 'b'),
+ schema: obj.getExternalSchema(),
+ },
+ {
+ id: 'alias', label: gettext('Alias'), cell: 'string',
+ type: 'text', mode: ['properties'],
+ disabled: () => obj.inCatalog(),
+ },
+ {
+ id: 'member_list', label: gettext('Members'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'c'),
+ },{
+ id: 'enum_list', label: gettext('Labels'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'e'),
+ },
+ {
+ id: 'typname', label: gettext('SubType'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'r'),
+ },
+ {
+ id: 'opcname', label: gettext('Subtype operator class'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'r'),
+ },
+ {
+ id: 'collname', label: gettext('Collation'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'r'),
+ },
+ {
+ id: 'rngcanonical', label: gettext('Canonical function'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'r'),
+ },
+ {
+ id: 'rngsubdiff', label: gettext('Subtype diff function'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'r'),
+ },
+ {
+ id: 'typinput', label: gettext('Input function'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'b'),
+ },
+ {
+ id: 'typoutput', label: gettext('Output function'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'b'),
+ },
+ {
+ id: 'type', label: gettext('Data Type'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: function(state) {
+ return state.typtype === 'N' || state.typtype === 'V';
+ }
+ },
+ {
+ id: 'tlength', label: gettext('Length/Precision'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'N'),
+ },
+ {
+ id: 'precision', label: gettext('Scale'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'N'),
+ },
+ {
+ id: 'maxsize', label: gettext('Size'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Definition'),
+ disabled: () => obj.inCatalog(),
+ visible: (state) => isVisible(state, 'V'),
+ },
+ {
+ id: 'type_acl', label: gettext('Privileges'), cell: 'string',
+ type: 'text', mode: ['properties'], group: gettext('Security'),
+ disabled: () => obj.inCatalog(),
+ },
+ {
+ id: 'is_sys_type', label: gettext('System type?'), cell: 'switch',
+ type: 'switch', mode: ['properties'],
+ disabled: () => obj.inCatalog(),
+ },
+ {
+ id: 'description', label: gettext('Comment'), cell: 'string',
+ type: 'multiline', mode: ['properties', 'create', 'edit'],
+ disabled: () => obj.inCatalog(),
+ },
+ {
+ id: 'typacl', label: gettext('Privileges'), type: 'collection',
+ group: gettext('Security'),
+ schema: this.getPrivilegeRoleSchema(['U']),
+ mode: ['edit', 'create'], canDelete: true,
+ uniqueCol : ['grantee'], deps: ['typtype'],
+ canAdd: function(state) {
+ // Do not allow to add when shell type is selected
+ // Clear acl & security label collections as well
+ if (state.typtype === 'p') {
+ let acl = state.typacl;
+ if(acl && acl.length > 0)
+ acl.splice(0, acl.length);
+ }
+ return (state.typtype !== 'p');
+ },
+ },
+ {
+ id: 'seclabels', label: gettext('Security labels'),
+ schema: new SecLabelSchema(),
+ editable: false, type: 'collection',
+ group: gettext('Security'), mode: ['edit', 'create'],
+ min_version: 90100, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'], deps: ['typtype'],
+ canAdd: function(state) {
+ // Do not allow to add when shell type is selected
+ // Clear acl & security label collections as well
+ if (state.typtype === 'p') {
+ let secLabs = state.seclabels;
+ if(secLabs && secLabs.length > 0)
+ secLabs.splice(0, secLabs.length);
+ }
+ return (state.typtype !== 'p');
+ },
+ }];
+ }
+}
+
+export {
+ CompositeSchema,
+ EnumerationSchema,
+ ExternalSchema,
+ RangeSchema,
+ getCompositeSchema,
+ getRangeSchema,
+ getExternalSchema,
+ getDataTypeSchema
+};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/macros/get_full_type_sql_format.macros b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/macros/get_full_type_sql_format.macros
new file mode 100644
index 0000000000000000000000000000000000000000..f77460080aea10541f7e085bf4f9f38a8c7e027b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/macros/get_full_type_sql_format.macros
@@ -0,0 +1,78 @@
+{% macro CREATE_TYPE_SQL(conn, type_name, type_length, type_precision, is_type_array) %}
+{% if type_name.startswith('time') and type_length %}
+{#############################################################}
+{###### Need to check against separate time types - START ######}
+{#############################################################}
+{% if type_name == "timestamp without time zone" %}
+timestamp({{ type_length }}) without time zone{% elif type_name == "timestamp with time zone" %}
+timestamp({{ type_length }}) with time zone{% elif type_name == "time without time zone" %}
+time({{ type_length }}) without time zone{% elif type_name == "time with time zone" %}
+time({{ type_length }}) with time zone{% endif %}{% if is_type_array %}
+[]{% endif %}
+{#############################################################}
+{###### Need to check against separate time types - END ######}
+{#############################################################}
+{% else %}
+{{ type_name }}{% if type_length %}
+({{ type_length }}{% if type_precision%}, {{ type_precision }}{% endif %}){% endif %}{% if is_type_array %}
+[]{% endif %}
+{% endif %}
+{% endmacro %}
+{######################################################}
+{##### BELOW MACRO IS USED FOR COLUMN TYPE UPDATE #####}
+{######################################################}
+{% macro UPDATE_TYPE_SQL(conn, data, o_data) %}
+{% if data.attprecision is defined and data.attprecision is none %}
+{% set old_precision = none %}
+{% elif data.attprecision is defined and data.attprecision is not none %}
+{% set data_precision = data.attprecision %}
+{% set old_precision = o_data.attprecision %}
+{% else %}
+{% set old_precision = o_data.attprecision %}
+{% endif %}
+{% if data.attlen is defined and data.attlen is none %}
+{% set old_length = none %}
+{% set old_precision = none %}
+{% set data_precision = none %}
+{% else %}
+{% set old_length = o_data.attlen %}
+{% endif %}
+{% if data.cltype and data.cltype.startswith('time') and data.attlen %}
+{#############################################################}
+{###### Need to check against separate time types - START ######}
+{#############################################################}
+{% if data.cltype == "timestamp without time zone" %}
+timestamp({{ data.attlen }}) without time zone {% elif data.cltype == "timestamp with time zone" %}
+timestamp({{ data.attlen }}) with time zone {% elif data.cltype == "time without time zone" %}
+time({{ data.attlen }}) without time zone {% elif data.cltype == "time with time zone" %}
+time({{ data.attlen }}) with time zone {% endif %}{% if data.hasSqrBracket %}[]{% endif %}
+{#############################################################}
+{# if only type changes, we need to give previous length to current type#}
+{#############################################################}
+{% elif data.cltype and data.cltype.startswith('time') %}
+{% if data.cltype == "timestamp without time zone" %}
+timestamp{% if o_data.attlen is not none %}({{ o_data.attlen }}){% endif %} without time zone {% elif data.cltype == "timestamp with time zone" %}
+timestamp{% if o_data.attlen is not none %}({{ o_data.attlen }}){% endif %} with time zone {% elif data.cltype == "time without time zone" %}
+time{% if o_data.attlen is not none %}({{ o_data.attlen }}){% endif %} without time zone {% elif data.cltype == "time with time zone" %}
+time{% if o_data.attlen is not none %}({{ o_data.attlen }}){% endif %} with time zone {% endif %}{% if data.hasSqrBracket %}[]{% endif %}
+{#############################################################}
+{# if only length changes, we need to give previous length to current type#}
+{#############################################################}
+{% elif data.attlen and o_data.cltype.startswith('time') %}
+{% if o_data.cltype == "timestamp without time zone" %}
+timestamp({{ data.attlen }}) without time zone {% elif o_data.cltype == "timestamp with time zone" %}
+timestamp({{ data.attlen }}) with time zone {% elif o_data.cltype == "time without time zone" %}
+time({{ data.attlen }}) without time zone {% elif o_data.cltype == "time with time zone" %}
+time({{ data.attlen }}) with time zone {% endif %}{% if o_data.hasSqrBracket %}[]{% endif %}
+{###### Need to check against separate time types - END ######}
+{% elif (data.cltype and not data.cltype.startswith('time')) or not o_data.cltype.startswith('time') %}
+{#############################################################}
+{########## We will create SQL for other types here ##########}
+{#############################################################}
+{% if data.cltype %}{{ data.cltype }}{% elif o_data.typnspname != 'pg_catalog' %}{{conn|qtTypeIdent(o_data.typnspname, o_data.cltype)}}{% else %}{{conn|qtTypeIdent(o_data.cltype)}}{% endif %}{% if (data.attlen and data.attlen is not none) or (data_precision and data_precision is not none) or (old_length and old_length is not none and old_length|int >0) or (old_precision and old_precision is not none) %}
+{% if data.attlen and data.attlen is not none %}
+({{ data.attlen }}{% elif old_length and old_length is not none %}({{ old_length }}{% endif %}{% if data_precision and data_precision is not none %}
+, {{ data_precision }}){% elif old_precision and old_precision is not none %}, {{ old_precision }}){% else %}){% endif %}
+{% endif %}{% if o_data.hasSqrBracket %}[]{% endif %}
+{% endif %}
+{% endmacro %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..54dc1eed12f8dc2b0c608a6ae24893e197382726
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/acl.sql
@@ -0,0 +1,27 @@
+SELECT 'typacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT t.typacl
+ FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+ WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+ {% if tid %}
+ AND t.oid = {{tid}}::oid
+ {% endif %}
+ ) acl,
+ (SELECT (d).grantee AS grantee, (d).grantor AS grantor, (d).is_grantable
+ AS is_grantable, (d).privilege_type AS privilege_type FROM (SELECT
+ pg_catalog.aclexplode(t.typacl) as d FROM pg_catalog.pg_type t WHERE t.oid = {{tid}}::oid) a ORDER BY privilege_type) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/additional_properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/additional_properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a953bbf91c7bd4beb516950c6327aaccb57f5c6c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/additional_properties.sql
@@ -0,0 +1,44 @@
+{# The SQL given below will fetch composite type#}
+{% if typtype == 'c' %}
+SELECT attnum, attname, pg_catalog.format_type(t.oid,NULL) AS typname, attndims, atttypmod, nsp.nspname,
+ (SELECT COUNT(1) from pg_catalog.pg_type t2 WHERE t2.typname=t.typname) > 1 AS isdup,
+ collname, nspc.nspname as collnspname, att.attrelid,
+ pg_catalog.format_type(t.oid, att.atttypmod) AS fulltype,
+ CASE WHEN t.typelem > 0 THEN t.typelem ELSE t.oid END as elemoid
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type t ON t.oid=atttypid
+ JOIN pg_catalog.pg_namespace nsp ON t.typnamespace=nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_type b ON t.typelem=b.oid
+ LEFT OUTER JOIN pg_catalog.pg_collation c ON att.attcollation=c.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON c.collnamespace=nspc.oid
+ WHERE att.attrelid = {{typrelid}}::oid
+ ORDER by attnum;
+{% endif %}
+
+{# The SQL given below will fetch enum type#}
+{% if typtype == 'e' %}
+SELECT enumlabel
+FROM pg_catalog.pg_enum
+ WHERE enumtypid={{tid}}::oid
+ ORDER by enumsortorder
+{% endif %}
+
+{# The SQL given below will fetch range type#}
+{% if typtype == 'r' %}
+SELECT rngsubtype, st.typname,
+ rngcollation,
+ CASE WHEN n.nspname IS NOT NULL THEN pg_catalog.concat(pg_catalog.quote_ident(n.nspname), '.', pg_catalog.quote_ident(col.collname)) ELSE col.collname END AS collname,
+ rngsubopc, opc.opcname,
+ rngcanonical, rngsubdiff as rngsubdiff_proc,
+ CASE WHEN length(ns.nspname::text) > 0 AND length(pgpr.proname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(ns.nspname), '.', pg_catalog.quote_ident(pgpr.proname))
+ ELSE '' END AS rngsubdiff
+FROM pg_catalog.pg_range
+ LEFT JOIN pg_catalog.pg_type st ON st.oid=rngsubtype
+ LEFT JOIN pg_catalog.pg_collation col ON col.oid=rngcollation
+ LEFT JOIN pg_catalog.pg_namespace n ON col.collnamespace=n.oid
+ LEFT JOIN pg_catalog.pg_opclass opc ON opc.oid=rngsubopc
+ LEFT JOIN pg_catalog.pg_proc pgpr ON pgpr.oid = rngsubdiff
+ LEFT JOIN pg_catalog.pg_namespace ns ON ns.oid=pgpr.pronamespace
+ WHERE rngtypid={{tid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..20d3b8b255246a86119d6ad6d01655e5297024ac
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_type t
+LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if not showsysobj %}
+ AND ct.oid is NULL
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a2d4da1b03adaabbaf1f27e831b04a388cc67e3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/create.sql
@@ -0,0 +1,84 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{## If user selected shell type then just create type template ##}
+{% if data and data.typtype == 'p' %}
+CREATE TYPE {{ conn|qtIdent(data.schema, data.name) }};
+{% endif %}
+{### Composite Type ###}
+{% if data and data.typtype == 'c' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS
+({{"\n\t"}}{% if data.composite %}{% for d in data.composite %}{% if loop.index != 1 %},{{"\n\t"}}{% endif %}{{ conn|qtIdent(d.member_name) }} {% if is_sql %}{{ d.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, d.cltype, d.tlength, d.precision, d.hasSqrBracket) }}{% endif %}{% if d.collation %} COLLATE {{d.collation}}{% endif %}{% endfor %}{% endif %}{{"\n"}});
+{% endif %}
+{### Enum Type ###}
+{% if data and data.typtype == 'e' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS ENUM
+ ({% for e in data.enum %}{% if loop.index != 1 %}, {% endif %}{{ e.label|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{### Range Type ###}
+{% if data and data.typtype == 'r' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS RANGE
+(
+ {% if data.typname %}SUBTYPE={{ conn|qtTypeIdent(data.typname) }}{% endif %}{% if data.collname %},
+ COLLATION = {{ data.collname }}{% endif %}{% if data.opcname %},
+ SUBTYPE_OPCLASS = {{ data.opcname }}{% endif %}{% if data.rngcanonical %},
+ CANONICAL = {{ data.rngcanonical }}{% endif %}{% if data.rngsubdiff %},
+ SUBTYPE_DIFF = {{ data.rngsubdiff }}{% endif %}
+
+);
+{% endif %}
+{### External Type ###}
+{% if data and data.typtype == 'b' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+(
+ {% if data.typinput %}INPUT = {{data.typinput}}{% endif %}{% if data.typoutput %},
+ OUTPUT = {{ data.typoutput }}{% endif %}{% if data.typreceive %},
+ RECEIVE = {{data.typreceive}}{% endif %}{% if data.typsend %},
+ SEND = {{data.typsend}}{% endif %}{% if data.typmodin %},
+ TYPMOD_IN = {{data.typmodin}}{% endif %}{% if data.typmodout %},
+ TYPMOD_OUT = {{data.typmodout}}{% endif %}{% if data.typanalyze %},
+ ANALYZE = {{data.typanalyze}}{% endif %}{% if data.typlen %},
+ INTERNALLENGTH = {{data.typlen}}{% endif %}{% if data.typbyval %},
+ PASSEDBYVALUE{% endif %}{% if data.typalign %},
+ ALIGNMENT = {{data.typalign}}{% endif %}{% if data.typstorage %},
+ STORAGE = {{data.typstorage}}{% endif %}{% if data.typcategory %},
+ CATEGORY = {{data.typcategory|qtLiteral(conn)}}{% endif %}{% if data.typispreferred %},
+ PREFERRED = {{data.typispreferred}}{% endif %}{% if data.typdefault %},
+ DEFAULT = {{data.typdefault|qtLiteral(conn)}}{% endif %}{% if data.element %},
+ ELEMENT = {{data.element}}{% endif %}{% if data.typdelim %},
+ DELIMITER = {{data.typdelim|qtLiteral(conn)}}{% endif %}{% if data.is_collatable %},
+ COLLATABLE = {{data.is_collatable}}{% endif %}
+
+);
+{% endif %}
+{### Type Owner ###}
+{% if data and data.typeowner %}
+
+ALTER TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+ OWNER TO {{ conn|qtIdent(data.typeowner) }};
+{% endif %}
+{### Type Comments ###}
+{% if data and data.description %}
+
+COMMENT ON TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{### ACL ###}
+{% if data.typacl %}
+
+{% for priv in data.typacl %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+
+{% for r in data.seclabels %}
+{% if r.provider and r.label %}
+{{ SECLABEL.SET(conn, 'TYPE', data.name, r.provider, r.label, data.schema) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f09cbb87dd038d16107299c5c4262b0d31e9b3a7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP TYPE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}{% if cascade%} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2b5cb534c432b6ec387fab12fb020013dbddde42
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_collations.sql
@@ -0,0 +1,7 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
+ ELSE '' END AS collation
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE c.collnamespace=n.oid
+ORDER BY nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_external_functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_external_functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..425df884582e3fb4b9281129df54799ece0b510d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_external_functions.sql
@@ -0,0 +1,42 @@
+{### Input/Output/Send/Receive/Analyze function list also append into TypModeIN/TypModOUT ###}
+{% if extfunc %}
+SELECT proname, nspname,
+ CASE WHEN (length(nspname::text) > 0 AND nspname != 'public') and length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ WHEN length(proname::text) > 0 THEN
+ pg_catalog.quote_ident(proname)
+ ELSE '' END AS func
+FROM (
+ SELECT proname, nspname, max(proargtypes[0]) AS arg0, max(proargtypes[1]) AS arg1
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+GROUP BY proname, nspname
+HAVING count(proname) = 1) AS uniquefunc
+WHERE arg0 <> 0 AND (arg1 IS NULL OR arg1 <> 0);
+{% endif %}
+{### TypmodIN list ###}
+{% if typemodin %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS func
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype=(SELECT oid FROM pg_catalog.pg_type WHERE typname='int4')
+ AND proargtypes[0]=(SELECT oid FROM pg_catalog.pg_type WHERE typname='_cstring')
+ AND proargtypes[1] IS NULL
+ORDER BY nspname, proname;
+{% endif %}
+{### TypmodOUT list ###}
+{% if typemodout %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS func
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype=(SELECT oid FROM pg_catalog.pg_type WHERE typname='cstring')
+ AND proargtypes[0]=(SELECT oid FROM pg_catalog.pg_type WHERE typname='int4')
+ AND proargtypes[1] IS NULL
+ORDER BY nspname, proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1196af4c0c7964374e38d056207d59f47d79e80d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_oid.sql
@@ -0,0 +1,11 @@
+{# Below will provide oid for newly created type #}
+SELECT t.oid
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if data %}
+ AND t.typname = {{data.name|qtLiteral(conn)}}
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_scid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_scid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8c3c05add41375f56c7fc7bd582b5bc3e4b0bf3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_scid.sql
@@ -0,0 +1,15 @@
+{% if tid %}
+SELECT
+ t.typnamespace as scid
+FROM
+ pg_catalog.pg_type t
+WHERE
+ t.oid = {{tid}}::oid;
+{% else %}
+SELECT
+ ns.oid as scid
+FROM
+ pg_catalog.pg_namespace ns
+WHERE
+ ns.nspname = {{schema|qtLiteral(conn)}}::text;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_subtypes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_subtypes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bc788310b3682360bb5558829f444db123ab801d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_subtypes.sql
@@ -0,0 +1,56 @@
+{### To fill subtype combobox ###}
+{% if subtype %}
+SELECT DISTINCT typ.typname AS stype,
+ (CASE WHEN typ.typcollation > 0 THEN true ELSE false END) AS is_collate
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype = typ.oid
+WHERE opc.opcmethod = 403
+ORDER BY 1
+{% endif %}
+{### To fill subtype opclass combobox ###}
+{% if subtype_opclass and data and data.typname %}
+SELECT opc.opcname
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype=typ.oid
+ AND typ.typname = {{ data.typname|qtLiteral(conn) }}
+WHERE opc.opcmethod = 403
+ORDER BY opcname;
+{% endif %}
+{### To fetch opcinttype from subtype opclass ###}
+{% if get_opcintype and data and data.typname and data.opcname %}
+SELECT opc.opcintype
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype=typ.oid
+ AND typ.typname = {{ data.typname|qtLiteral(conn) }}
+WHERE opc.opcmethod = 403
+ AND opc.opcname = {{ data.opcname|qtLiteral(conn) }}
+ORDER BY opcname;
+{% endif %}
+{### To fill subtype diff function combobox ###}
+{% if opcintype %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS stypdiff
+FROM pg_catalog.pg_proc
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype = 701
+ AND proargtypes = '{{opcintype}} {{opcintype}}'
+ORDER BY proname;
+{% endif %}
+{### To fill canonical combobox ###}
+{% if getoid %}
+SELECT oid FROM pg_catalog.pg_type
+WHERE typname = {{ data.name|qtLiteral(conn) }}
+{% endif %}
+{% if canonical and oid %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS canonical
+FROM pg_catalog.pg_proc
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype= {{ oid }}
+ AND proargtypes = '{{ oid }}'
+ORDER BY proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4beb5757466d59671e77f28f8ca2eee10d641cc7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/get_types.sql
@@ -0,0 +1,11 @@
+SELECT * FROM
+ (SELECT pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END AS elemoid,
+ typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup,
+ CASE WHEN t.typcollation != 0 THEN TRUE ELSE FALSE END AS is_collatable
+FROM pg_catalog.pg_type t
+ JOIN pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+WHERE (NOT (typname = 'unknown' AND nspname = 'pg_catalog')) AND typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r') AND NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = typname and relkind != 'c') AND (typname not like '_%' OR NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = substring(typname from 2)::name and relkind != 'c')) AND nsp.nspname != 'information_schema'
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8032959e111747363afde42351c1ea4107cb5dc9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/nodes.sql
@@ -0,0 +1,18 @@
+SELECT t.oid, t.typname AS name, des.description
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = t.typnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if tid %}
+ AND t.oid = {{tid}}::oid
+{% endif %}
+{% if not show_system_objects %}
+ AND ct.oid is NULL
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..09728bf206e11e5b338dc3b6785e37009d3d1fdf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/properties.sql
@@ -0,0 +1,24 @@
+SELECT t.oid, t.typname AS name,
+ (CASE WHEN CAST(coalesce(t.typcollation, '0') AS integer) = 100 THEN true ElSE false END) AS is_collatable,
+ t.typacl AS type_acl,
+ t.*, pg_catalog.format_type(t.oid, null) AS alias,
+ pg_catalog.pg_get_userbyid(t.typowner) as typeowner, e.typname as element,
+ description, ct.oid AS taboid,
+ nsp.nspname AS schema,
+ --MinimumVersion 9.1 START
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=t.oid) AS seclabels,
+ -- END
+ (CASE WHEN (t.oid <= {{ datlastsysoid}}::oid OR ct.oid != 0) THEN true ElSE false END) AS is_sys_type
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = t.typnamespace
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if tid %}
+ AND t.oid = {{tid}}::oid
+{% endif %}
+{% if not show_system_objects %}
+ AND ct.oid is NULL
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/type_schema_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/type_schema_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..246e3bc1d153a02482acb6b8a721f428ef05509e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/type_schema_diff.sql
@@ -0,0 +1,105 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+-- WARNING:
+-- We have found the difference in either of Type or SubType or Collation,
+-- so we need to drop the existing type first and re-create it.
+DROP TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }} CASCADE;
+
+{## If user selected shell type then just create type template ##}
+{% if data and data.typtype == 'p' %}
+CREATE TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }};
+{% endif %}
+{### Composite Type ###}
+{% if data and data.typtype == 'c' %}
+{% if data.composite %}{% set typinput = data.typinput %}{% elif o_data.typinput %}{% set typinput = o_data.typinput %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS
+({{"\n\t"}}{% if data.composite.added %}{% for d in data.composite.added %}{% if loop.index != 1 %},{{"\n\t"}}{% endif %}{{ conn|qtIdent(d.member_name) }} {% if is_sql %}{{ d.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, d.cltype, d.tlength, d.precision, d.hasSqrBracket) }}{% endif %}{% if d.collation %} COLLATE {{d.collation}}{% endif %}{% endfor %}{% endif %}{{"\n"}});
+{% endif %}
+{### Enum Type ###}
+{% if data and data.typtype == 'e' %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS ENUM
+ ({% for e in data.enum.added %}{% if loop.index != 1 %}, {% endif %}{{ e.label|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{### Range Type ###}
+{% if data and (data.typtype == 'r' or (data.typtype is not defined and o_data.typtype == 'r')) %}
+{% if data.typname %}{% set typname = data.typname %}{% elif o_data.typname %}{% set typname = o_data.typname %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS RANGE
+(
+ {% if typname %}SUBTYPE={{ conn|qtTypeIdent(typname) }}{% endif %}{% if data.collname %},
+ COLLATION = {{ data.collname }}{% endif %}{% if data.opcname %},
+ SUBTYPE_OPCLASS = {{ data.opcname }}{% endif %}{% if data.rngcanonical %},
+ CANONICAL = {{ data.rngcanonical }}{% endif %}{% if data.rngsubdiff %},
+ SUBTYPE_DIFF = {{ data.rngsubdiff }}{% endif %}
+
+);
+{% endif %}
+{### External Type ###}
+{% if data and (data.typtype == 'b' or (data.typtype is not defined and o_data.typtype == 'b')) %}
+{% if data.typinput %}{% set typinput = data.typinput %}{% elif o_data.typinput %}{% set typinput = o_data.typinput %}{% endif %}
+{% if data.typoutput %}{% set typoutput = data.typoutput %}{% elif o_data.typoutput %}{% set typoutput = o_data.typoutput %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+(
+ {% if typinput %}INPUT = {{ typinput }}{% endif %}{% if typoutput %},
+ OUTPUT = {{ typoutput }}{% endif %}{% if data.typreceive %},
+ RECEIVE = {{data.typreceive}}{% endif %}{% if data.typsend %},
+ SEND = {{data.typsend}}{% endif %}{% if data.typmodin %},
+ TYPMOD_IN = {{data.typmodin}}{% endif %}{% if data.typmodout %},
+ TYPMOD_OUT = {{data.typmodout}}{% endif %}{% if data.typanalyze %},
+ ANALYZE = {{data.typanalyze}}{% endif %}{% if data.typlen %},
+ INTERNALLENGTH = {{data.typlen}}{% endif %}{% if data.typbyval %},
+ PASSEDBYVALUE{% endif %}{% if data.typalign %},
+ ALIGNMENT = {{data.typalign}}{% endif %}{% if data.typstorage %},
+ STORAGE = {{data.typstorage}}{% endif %}{% if data.typcategory %},
+ CATEGORY = {{data.typcategory|qtLiteral(conn)}}{% endif %}{% if data.typispreferred %},
+ PREFERRED = {{data.typispreferred}}{% endif %}{% if data.typdefault %},
+ DEFAULT = {{data.typdefault|qtLiteral(conn)}}{% endif %}{% if data.element %},
+ ELEMENT = {{data.element}}{% endif %}{% if data.typdelim %},
+ DELIMITER = {{data.typdelim|qtLiteral(conn)}}{% endif %}{% if data.is_collatable %},
+ COLLATABLE = {{data.is_collatable}}{% endif %}
+
+);
+{% endif %}
+{### Type Owner ###}
+{% if data and (data.typeowner or o_data.typeowner)%}
+
+ALTER TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+ OWNER TO {% if data.typeowner %}{{ conn|qtIdent(data.typeowner) }}{% elif o_data.typeowner %}{{ conn|qtIdent(o_data.typeowner) }}{% endif %};
+{% endif %}
+{### Type Comments ###}
+{% if data and data.description %}
+
+COMMENT ON TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{### ACL ###}
+{% if data.typacl and data.typacl|length > 0 %}
+{% if 'deleted' in data.typacl %}
+{% for priv in data.typacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.typacl %}
+{% for priv in data.typacl.changed %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.typacl %}
+{% for priv in data.typacl.added %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+
+{% for r in data.seclabels %}
+{% if r.provider and r.label %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fd40a44a082017108e6885719612ec76b78e76cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/pg/sql/default/update.sql
@@ -0,0 +1,161 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#======================================#}
+{# Below will change object owner #}
+{% if data.typeowner and data.typeowner != o_data.typeowner %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ OWNER TO {{ conn|qtIdent(data.typeowner) }};
+
+{% endif %}
+{#======================================#}
+{# Below will change objects comment #}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{#======================================#}
+{### The sql given below will update composite type ###}
+{% if data.composite and data.composite|length > 0 %}
+{% set composite = data.composite %}
+{% if 'deleted' in composite and composite.deleted|length > 0 %}
+{% for r in composite.deleted %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ DROP ATTRIBUTE {{conn|qtIdent(r.member_name)}};
+{% endfor %}
+{% endif %}
+{% if 'added' in composite and composite.added|length > 0 %}
+{% for r in composite.added %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD ATTRIBUTE {{conn|qtIdent(r.member_name)}} {{ GET_TYPE.CREATE_TYPE_SQL(conn, r.cltype, r.tlength, r.precision, r.hasSqrBracket) }}{% if r.collation %}
+ COLLATE {{r.collation}}{% endif %};
+{% endfor %}
+{% endif %}
+{% if 'changed' in composite and composite.changed|length > 0 %}
+{% for r in composite.changed %}
+{% for o in o_data.composite %}
+{##### Variables for the loop #####}
+{% set member_name = o.member_name %}
+{% set cltype = o.cltype %}
+{% set tlength = o.tlength %}
+{% set precision = o.precision %}
+{% set hasSqrBracket = o.hasSqrBracket %}
+{##### If member name changed #####}
+{% if o.attnum == r.attnum %}
+{% if r.member_name and o.member_name != r.member_name %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME ATTRIBUTE {{o.member_name}} TO {{r.member_name}};
+{% set member_name = r.member_name %}
+{% endif %}
+{##### If type changed #####}
+{% if r.cltype and cltype != r.cltype %}
+{% set cltype = r.cltype %}
+{% set hasSqrBracket = r.hasSqrBracket %}
+{##### If length is not allowed on type #####}
+{% if not r.is_tlength %}
+{% set tlength = 0 %}
+{% set precision = 0 %}
+{% endif %}
+{% endif %}
+{##### If length changed #####}
+{% if r.tlength and tlength != r.tlength %}
+{% set tlength = r.tlength %}
+{% endif %}
+{##### If precision changed #####}
+{% if tlength and r.precision and precision != r.precision %}
+{% set precision = r.precision %}
+{% endif %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ALTER ATTRIBUTE {{conn|qtIdent(member_name)}} SET DATA TYPE {{ GET_TYPE.CREATE_TYPE_SQL(conn, cltype, tlength, precision, hasSqrBracket) }}{% if r.collation %}
+ COLLATE {{r.collation}}{% endif %};
+{% endif%}
+{% endfor %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#======================================#}
+{### The sql given below will update enum type ###}
+{% if data.enum and data.enum|length > 0 %}
+{% set enum = data.enum %}
+{% set o_enum_len = o_data.enum|length %}
+{# We need actual list index from length #}
+{% set o_enum_len = o_enum_len - 1 %}
+{% if 'added' in enum and enum.added|length > 0 %}
+{% for r in enum.added %}
+{% set c_idx = loop.index %}
+{% if c_idx == 1 %}
+{# if first new element then add it after old data enum list#}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD VALUE {{r.label|qtLiteral(conn)}} {% if o_enum_len > 0 %}AFTER {{o_data.enum[o_enum_len].label|qtLiteral(conn) }}{% endif %};
+{% else %}
+{# if first new element then add it after new data enum list#}
+{% set p_idx = loop.index - 2 %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD VALUE {{r.label|qtLiteral(conn)}} AFTER {{enum.added[p_idx].label|qtLiteral(conn)}};
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#======================================#}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TYPE', o_data.name, r.provider, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#======================================#}
+{# Change the privileges #}
+{% if data.typacl and data.typacl|length > 0 %}
+{% if 'deleted' in data.typacl %}
+{% for priv in data.typacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.typacl %}
+{% for priv in data.typacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.old_grantee, o_data.name, o_data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.typacl %}
+{% for priv in data.typacl.added %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#======================================#}
+{# Below will change object name #}
+{% if data.name and data.name != o_data.name %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{#======================================#}
+{# Below will change the schema for object #}
+{# with extra if condition we will also make sure that object has correct name #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TYPE {% if data.name and data.name != o_data.name %}{{ conn|qtIdent(o_data.schema, data.name) }}
+{% else %}{{ conn|qtIdent(o_data.schema, o_data.name) }}
+{% endif %}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..54dc1eed12f8dc2b0c608a6ae24893e197382726
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/acl.sql
@@ -0,0 +1,27 @@
+SELECT 'typacl' as deftype, COALESCE(gt.rolname, 'PUBLIC') grantee, g.rolname grantor, pg_catalog.array_agg(privilege_type) as privileges, pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'USAGE' THEN 'U'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT t.typacl
+ FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+ WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+ {% if tid %}
+ AND t.oid = {{tid}}::oid
+ {% endif %}
+ ) acl,
+ (SELECT (d).grantee AS grantee, (d).grantor AS grantor, (d).is_grantable
+ AS is_grantable, (d).privilege_type AS privilege_type FROM (SELECT
+ pg_catalog.aclexplode(t.typacl) as d FROM pg_catalog.pg_type t WHERE t.oid = {{tid}}::oid) a ORDER BY privilege_type) d
+ ) d
+ LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+ LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY g.rolname, gt.rolname
+ORDER BY grantee
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/additional_properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/additional_properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8379a23e8e32bcc7b8704d36bfd1fe58595b0800
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/additional_properties.sql
@@ -0,0 +1,58 @@
+{# The SQL given below will fetch composite type#}
+{% if typtype == 'c' %}
+SELECT attnum, attname, pg_catalog.format_type(t.oid,NULL) AS typname, attndims, atttypmod, nsp.nspname,
+ (SELECT COUNT(1) from pg_catalog.pg_type t2 WHERE t2.typname=t.typname) > 1 AS isdup,
+ collname, nspc.nspname as collnspname, att.attrelid,
+ pg_catalog.format_type(t.oid, att.atttypmod) AS fulltype,
+ CASE WHEN t.typelem > 0 THEN t.typelem ELSE t.oid END as elemoid
+FROM pg_catalog.pg_attribute att
+ JOIN pg_catalog.pg_type t ON t.oid=atttypid
+ JOIN pg_catalog.pg_namespace nsp ON t.typnamespace=nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_type b ON t.typelem=b.oid
+ LEFT OUTER JOIN pg_catalog.pg_collation c ON att.attcollation=c.oid
+ LEFT OUTER JOIN pg_catalog.pg_namespace nspc ON c.collnamespace=nspc.oid
+ WHERE att.attrelid = {{typrelid}}::oid
+ ORDER by attnum;
+{% endif %}
+
+{# The SQL given below will fetch enum type#}
+{% if typtype == 'e' %}
+SELECT enumlabel
+FROM pg_catalog.pg_enum
+ WHERE enumtypid={{tid}}::oid
+ ORDER by enumsortorder
+{% endif %}
+
+{# The SQL given below will fetch range type#}
+{% if typtype == 'r' %}
+SELECT rngsubtype, st.typname,
+ rngcollation,
+ CASE WHEN n.nspname IS NOT NULL THEN pg_catalog.concat(pg_catalog.quote_ident(n.nspname), '.', pg_catalog.quote_ident(col.collname)) ELSE col.collname END AS collname,
+ rngsubopc, opc.opcname,
+ rngcanonical, rngsubdiff
+FROM pg_catalog.pg_range
+ LEFT JOIN pg_catalog.pg_type st ON st.oid=rngsubtype
+ LEFT JOIN pg_catalog.pg_collation col ON col.oid=rngcollation
+ LEFT JOIN pg_catalog.pg_namespace n ON col.collnamespace=n.oid
+ LEFT JOIN pg_catalog.pg_opclass opc ON opc.oid=rngsubopc
+ WHERE rngtypid={{tid}}::oid;
+{% endif %}
+
+{# The SQL given below will fetch enum type#}
+{% if typtype == 'N' or typtype == 'V' %}
+SELECT t.typname AS typname,
+ CASE WHEN t.typelem > 0 THEN t.typelem ELSE t.oid END AS elemoid,
+ t.typtypmod,
+ t.typtype,
+ t.typndims,
+ pg_catalog.format_type(e.oid,NULL) AS type,
+ pg_catalog.format_type(e.oid, t.typtypmod) AS fulltype,
+ nsp.nspname as typnspname,
+ e.typname as type,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup,
+ CASE WHEN t.typcollation != 0 THEN TRUE ELSE FALSE END AS is_collatable
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+WHERE t.oid={{tid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..670982a2eb693816e02cfbe256f81ce7a7bbf697
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if not showsysobj %}
+ AND ct.oid is NULL
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a2c5cec997c05e301d0c0a85cfdc1b46a56ab1a1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/create.sql
@@ -0,0 +1,94 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{## If user selected shell type then just create type template ##}
+{% if data and data.typtype == 'p' %}
+CREATE TYPE {{ conn|qtIdent(data.schema, data.name) }};
+{% endif %}
+{### Composite Type ###}
+{% if data and data.typtype == 'c' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS
+({{"\n\t"}}{% if data.composite %}{% for d in data.composite %}{% if loop.index != 1 %},{{"\n\t"}}{% endif %}{{ conn|qtIdent(d.member_name) }} {% if is_sql %}{{ d.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, d.cltype, d.tlength, d.precision, d.hasSqrBracket) }}{% endif %}{% if d.collation %} COLLATE {{d.collation}}{% endif %}{% endfor %}{% endif %}{{"\n"}});
+{% endif %}
+{### Enum Type ###}
+{% if data and data.typtype == 'e' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS ENUM
+ ({% for e in data.enum %}{% if loop.index != 1 %}, {% endif %}{{ e.label|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{### Range Type ###}
+{% if data and data.typtype == 'r' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS RANGE
+(
+ {% if data.typname %}SUBTYPE={{ conn|qtTypeIdent(data.typname) }}{% endif %}{% if data.collname %},
+ COLLATION = {{ data.collname }}{% endif %}{% if data.opcname %},
+ SUBTYPE_OPCLASS = {{ data.opcname }}{% endif %}{% if data.rngcanonical %},
+ CANONICAL = {{ data.rngcanonical }}{% endif %}{% if data.rngsubdiff %},
+ SUBTYPE_DIFF = {{ data.rngsubdiff }}{% endif %}
+
+);
+{% endif %}
+{### External Type ###}
+{% if data and data.typtype == 'b' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+(
+ {% if data.typinput %}INPUT = {{data.typinput}}{% endif %}{% if data.typoutput %},
+ OUTPUT = {{ data.typoutput }}{% endif %}{% if data.typreceive %},
+ RECEIVE = {{data.typreceive}}{% endif %}{% if data.typsend %},
+ SEND = {{data.typsend}}{% endif %}{% if data.typmodin %},
+ TYPMOD_IN = {{data.typmodin}}{% endif %}{% if data.typmodout %},
+ TYPMOD_OUT = {{data.typmodout}}{% endif %}{% if data.typanalyze %},
+ ANALYZE = {{data.typanalyze}}{% endif %}{% if data.typlen %},
+ INTERNALLENGTH = {{data.typlen}}{% endif %}{% if data.typbyval %},
+ PASSEDBYVALUE{% endif %}{% if data.typalign %},
+ ALIGNMENT = {{data.typalign}}{% endif %}{% if data.typstorage %},
+ STORAGE = {{data.typstorage}}{% endif %}{% if data.typcategory %},
+ CATEGORY = {{data.typcategory|qtLiteral(conn)}}{% endif %}{% if data.typispreferred %},
+ PREFERRED = {{data.typispreferred}}{% endif %}{% if data.typdefault %},
+ DEFAULT = {{data.typdefault|qtLiteral(conn)}}{% endif %}{% if data.element %},
+ ELEMENT = {{data.element}}{% endif %}{% if data.typdelim %},
+ DELIMITER = {{data.typdelim|qtLiteral(conn)}}{% endif %}{% if data.is_collatable %},
+ COLLATABLE = {{data.is_collatable}}{% endif %}
+
+);
+{% endif %}
+{### Nested-table Type ###}
+{% if data and data.typtype == 'N' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS TABLE OF
+ {% if is_sql %}{{ data.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.tlength, data.precision, data.hasSqrBracket) }}{% endif %};
+{% endif %}
+{### VARRAY Type ###}
+{% if data and data.typtype == 'V' %}
+CREATE TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %} AS VARRAY({{data.maxsize}}) OF
+ {% if is_sql %}{{ data.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, data.cltype, data.tlength, data.precision, data.hasSqrBracket) }}{% endif %};
+{% endif %}
+
+{### Type Owner ###}
+{% if data and data.typeowner %}
+ALTER TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+ OWNER TO {{ conn|qtIdent(data.typeowner) }};
+{% endif %}
+{### Type Comments ###}
+{% if data and data.description %}
+
+COMMENT ON TYPE {% if data.schema %}{{ conn|qtIdent(data.schema, data.name) }}{% else %}{{ conn|qtIdent(data.name) }}{% endif %}
+
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{### ACL ###}
+{% if data.typacl %}
+
+{% for priv in data.typacl %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+
+{% for r in data.seclabels %}
+{% if r.provider and r.label %}
+{{ SECLABEL.SET(conn, 'TYPE', data.name, r.provider, r.label, data.schema) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f09cbb87dd038d16107299c5c4262b0d31e9b3a7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/delete.sql
@@ -0,0 +1 @@
+DROP TYPE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}{% if cascade%} CASCADE{% endif %};
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_collations.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_collations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2b5cb534c432b6ec387fab12fb020013dbddde42
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_collations.sql
@@ -0,0 +1,7 @@
+SELECT --nspname, collname,
+ CASE WHEN length(nspname::text) > 0 AND length(collname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(collname))
+ ELSE '' END AS collation
+FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n
+WHERE c.collnamespace=n.oid
+ORDER BY nspname, collname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_external_functions.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_external_functions.sql
new file mode 100644
index 0000000000000000000000000000000000000000..425df884582e3fb4b9281129df54799ece0b510d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_external_functions.sql
@@ -0,0 +1,42 @@
+{### Input/Output/Send/Receive/Analyze function list also append into TypModeIN/TypModOUT ###}
+{% if extfunc %}
+SELECT proname, nspname,
+ CASE WHEN (length(nspname::text) > 0 AND nspname != 'public') and length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ WHEN length(proname::text) > 0 THEN
+ pg_catalog.quote_ident(proname)
+ ELSE '' END AS func
+FROM (
+ SELECT proname, nspname, max(proargtypes[0]) AS arg0, max(proargtypes[1]) AS arg1
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+GROUP BY proname, nspname
+HAVING count(proname) = 1) AS uniquefunc
+WHERE arg0 <> 0 AND (arg1 IS NULL OR arg1 <> 0);
+{% endif %}
+{### TypmodIN list ###}
+{% if typemodin %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS func
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype=(SELECT oid FROM pg_catalog.pg_type WHERE typname='int4')
+ AND proargtypes[0]=(SELECT oid FROM pg_catalog.pg_type WHERE typname='_cstring')
+ AND proargtypes[1] IS NULL
+ORDER BY nspname, proname;
+{% endif %}
+{### TypmodOUT list ###}
+{% if typemodout %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(pg_catalog.quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS func
+FROM pg_catalog.pg_proc p
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype=(SELECT oid FROM pg_catalog.pg_type WHERE typname='cstring')
+ AND proargtypes[0]=(SELECT oid FROM pg_catalog.pg_type WHERE typname='int4')
+ AND proargtypes[1] IS NULL
+ORDER BY nspname, proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1196af4c0c7964374e38d056207d59f47d79e80d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_oid.sql
@@ -0,0 +1,11 @@
+{# Below will provide oid for newly created type #}
+SELECT t.oid
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if data %}
+ AND t.typname = {{data.name|qtLiteral(conn)}}
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_scid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_scid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8c3c05add41375f56c7fc7bd582b5bc3e4b0bf3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_scid.sql
@@ -0,0 +1,15 @@
+{% if tid %}
+SELECT
+ t.typnamespace as scid
+FROM
+ pg_catalog.pg_type t
+WHERE
+ t.oid = {{tid}}::oid;
+{% else %}
+SELECT
+ ns.oid as scid
+FROM
+ pg_catalog.pg_namespace ns
+WHERE
+ ns.nspname = {{schema|qtLiteral(conn)}}::text;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_subtypes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_subtypes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bc788310b3682360bb5558829f444db123ab801d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_subtypes.sql
@@ -0,0 +1,56 @@
+{### To fill subtype combobox ###}
+{% if subtype %}
+SELECT DISTINCT typ.typname AS stype,
+ (CASE WHEN typ.typcollation > 0 THEN true ELSE false END) AS is_collate
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype = typ.oid
+WHERE opc.opcmethod = 403
+ORDER BY 1
+{% endif %}
+{### To fill subtype opclass combobox ###}
+{% if subtype_opclass and data and data.typname %}
+SELECT opc.opcname
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype=typ.oid
+ AND typ.typname = {{ data.typname|qtLiteral(conn) }}
+WHERE opc.opcmethod = 403
+ORDER BY opcname;
+{% endif %}
+{### To fetch opcinttype from subtype opclass ###}
+{% if get_opcintype and data and data.typname and data.opcname %}
+SELECT opc.opcintype
+FROM pg_catalog.pg_opclass opc
+ JOIN pg_catalog.pg_type typ ON opc.opcintype=typ.oid
+ AND typ.typname = {{ data.typname|qtLiteral(conn) }}
+WHERE opc.opcmethod = 403
+ AND opc.opcname = {{ data.opcname|qtLiteral(conn) }}
+ORDER BY opcname;
+{% endif %}
+{### To fill subtype diff function combobox ###}
+{% if opcintype %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS stypdiff
+FROM pg_catalog.pg_proc
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype = 701
+ AND proargtypes = '{{opcintype}} {{opcintype}}'
+ORDER BY proname;
+{% endif %}
+{### To fill canonical combobox ###}
+{% if getoid %}
+SELECT oid FROM pg_catalog.pg_type
+WHERE typname = {{ data.name|qtLiteral(conn) }}
+{% endif %}
+{% if canonical and oid %}
+SELECT proname, nspname,
+ CASE WHEN length(nspname::text) > 0 AND length(proname::text) > 0 THEN
+ pg_catalog.concat(quote_ident(nspname), '.', pg_catalog.quote_ident(proname))
+ ELSE '' END AS canonical
+FROM pg_catalog.pg_proc
+ JOIN pg_catalog.pg_namespace n ON n.oid=pronamespace
+WHERE prorettype= {{ oid }}
+ AND proargtypes = '{{ oid }}'
+ORDER BY proname;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_types.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_types.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4beb5757466d59671e77f28f8ca2eee10d641cc7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/get_types.sql
@@ -0,0 +1,11 @@
+SELECT * FROM
+ (SELECT pg_catalog.format_type(t.oid,NULL) AS typname,
+ CASE WHEN typelem > 0 THEN typelem ELSE t.oid END AS elemoid,
+ typlen, typtype, t.oid, nspname,
+ (SELECT COUNT(1) FROM pg_catalog.pg_type t2 WHERE t2.typname = t.typname) > 1 AS isdup,
+ CASE WHEN t.typcollation != 0 THEN TRUE ELSE FALSE END AS is_collatable
+FROM pg_catalog.pg_type t
+ JOIN pg_catalog.pg_namespace nsp ON typnamespace=nsp.oid
+WHERE (NOT (typname = 'unknown' AND nspname = 'pg_catalog')) AND typisdefined AND typtype IN ('b', 'c', 'd', 'e', 'r') AND NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = typname and relkind != 'c') AND (typname not like '_%' OR NOT EXISTS (select 1 from pg_catalog.pg_class where relnamespace=typnamespace and relname = substring(typname from 2)::name and relkind != 'c')) AND nsp.nspname != 'information_schema'
+ ) AS dummy
+ORDER BY nspname <> 'pg_catalog', nspname <> 'public', nspname, 1
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..8032959e111747363afde42351c1ea4107cb5dc9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/nodes.sql
@@ -0,0 +1,18 @@
+SELECT t.oid, t.typname AS name, des.description
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = t.typnamespace
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if tid %}
+ AND t.oid = {{tid}}::oid
+{% endif %}
+{% if not show_system_objects %}
+ AND ct.oid is NULL
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = t.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..09728bf206e11e5b338dc3b6785e37009d3d1fdf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/properties.sql
@@ -0,0 +1,24 @@
+SELECT t.oid, t.typname AS name,
+ (CASE WHEN CAST(coalesce(t.typcollation, '0') AS integer) = 100 THEN true ElSE false END) AS is_collatable,
+ t.typacl AS type_acl,
+ t.*, pg_catalog.format_type(t.oid, null) AS alias,
+ pg_catalog.pg_get_userbyid(t.typowner) as typeowner, e.typname as element,
+ description, ct.oid AS taboid,
+ nsp.nspname AS schema,
+ --MinimumVersion 9.1 START
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabel sl1 WHERE sl1.objoid=t.oid) AS seclabels,
+ -- END
+ (CASE WHEN (t.oid <= {{ datlastsysoid}}::oid OR ct.oid != 0) THEN true ElSE false END) AS is_sys_type
+FROM pg_catalog.pg_type t
+ LEFT OUTER JOIN pg_catalog.pg_type e ON e.oid=t.typelem
+ LEFT OUTER JOIN pg_catalog.pg_class ct ON ct.oid=t.typrelid AND ct.relkind <> 'c'
+ LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=t.oid AND des.classoid='pg_type'::regclass)
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = t.typnamespace
+WHERE t.typtype != 'd' AND t.typname NOT LIKE E'\\_%' AND t.typnamespace = {{scid}}::oid
+{% if tid %}
+ AND t.oid = {{tid}}::oid
+{% endif %}
+{% if not show_system_objects %}
+ AND ct.oid is NULL
+{% endif %}
+ORDER BY t.typname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/type_schema_diff.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/type_schema_diff.sql
new file mode 100644
index 0000000000000000000000000000000000000000..246e3bc1d153a02482acb6b8a721f428ef05509e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/type_schema_diff.sql
@@ -0,0 +1,105 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+-- WARNING:
+-- We have found the difference in either of Type or SubType or Collation,
+-- so we need to drop the existing type first and re-create it.
+DROP TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }} CASCADE;
+
+{## If user selected shell type then just create type template ##}
+{% if data and data.typtype == 'p' %}
+CREATE TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }};
+{% endif %}
+{### Composite Type ###}
+{% if data and data.typtype == 'c' %}
+{% if data.composite %}{% set typinput = data.typinput %}{% elif o_data.typinput %}{% set typinput = o_data.typinput %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS
+({{"\n\t"}}{% if data.composite.added %}{% for d in data.composite.added %}{% if loop.index != 1 %},{{"\n\t"}}{% endif %}{{ conn|qtIdent(d.member_name) }} {% if is_sql %}{{ d.fulltype }}{% else %}{{ GET_TYPE.CREATE_TYPE_SQL(conn, d.cltype, d.tlength, d.precision, d.hasSqrBracket) }}{% endif %}{% if d.collation %} COLLATE {{d.collation}}{% endif %}{% endfor %}{% endif %}{{"\n"}});
+{% endif %}
+{### Enum Type ###}
+{% if data and data.typtype == 'e' %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS ENUM
+ ({% for e in data.enum.added %}{% if loop.index != 1 %}, {% endif %}{{ e.label|qtLiteral(conn) }}{% endfor %});
+{% endif %}
+{### Range Type ###}
+{% if data and (data.typtype == 'r' or (data.typtype is not defined and o_data.typtype == 'r')) %}
+{% if data.typname %}{% set typname = data.typname %}{% elif o_data.typname %}{% set typname = o_data.typname %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %} AS RANGE
+(
+ {% if typname %}SUBTYPE={{ conn|qtTypeIdent(typname) }}{% endif %}{% if data.collname %},
+ COLLATION = {{ data.collname }}{% endif %}{% if data.opcname %},
+ SUBTYPE_OPCLASS = {{ data.opcname }}{% endif %}{% if data.rngcanonical %},
+ CANONICAL = {{ data.rngcanonical }}{% endif %}{% if data.rngsubdiff %},
+ SUBTYPE_DIFF = {{ data.rngsubdiff }}{% endif %}
+
+);
+{% endif %}
+{### External Type ###}
+{% if data and (data.typtype == 'b' or (data.typtype is not defined and o_data.typtype == 'b')) %}
+{% if data.typinput %}{% set typinput = data.typinput %}{% elif o_data.typinput %}{% set typinput = o_data.typinput %}{% endif %}
+{% if data.typoutput %}{% set typoutput = data.typoutput %}{% elif o_data.typoutput %}{% set typoutput = o_data.typoutput %}{% endif %}
+CREATE TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+(
+ {% if typinput %}INPUT = {{ typinput }}{% endif %}{% if typoutput %},
+ OUTPUT = {{ typoutput }}{% endif %}{% if data.typreceive %},
+ RECEIVE = {{data.typreceive}}{% endif %}{% if data.typsend %},
+ SEND = {{data.typsend}}{% endif %}{% if data.typmodin %},
+ TYPMOD_IN = {{data.typmodin}}{% endif %}{% if data.typmodout %},
+ TYPMOD_OUT = {{data.typmodout}}{% endif %}{% if data.typanalyze %},
+ ANALYZE = {{data.typanalyze}}{% endif %}{% if data.typlen %},
+ INTERNALLENGTH = {{data.typlen}}{% endif %}{% if data.typbyval %},
+ PASSEDBYVALUE{% endif %}{% if data.typalign %},
+ ALIGNMENT = {{data.typalign}}{% endif %}{% if data.typstorage %},
+ STORAGE = {{data.typstorage}}{% endif %}{% if data.typcategory %},
+ CATEGORY = {{data.typcategory|qtLiteral(conn)}}{% endif %}{% if data.typispreferred %},
+ PREFERRED = {{data.typispreferred}}{% endif %}{% if data.typdefault %},
+ DEFAULT = {{data.typdefault|qtLiteral(conn)}}{% endif %}{% if data.element %},
+ ELEMENT = {{data.element}}{% endif %}{% if data.typdelim %},
+ DELIMITER = {{data.typdelim|qtLiteral(conn)}}{% endif %}{% if data.is_collatable %},
+ COLLATABLE = {{data.is_collatable}}{% endif %}
+
+);
+{% endif %}
+{### Type Owner ###}
+{% if data and (data.typeowner or o_data.typeowner)%}
+
+ALTER TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+ OWNER TO {% if data.typeowner %}{{ conn|qtIdent(data.typeowner) }}{% elif o_data.typeowner %}{{ conn|qtIdent(o_data.typeowner) }}{% endif %};
+{% endif %}
+{### Type Comments ###}
+{% if data and data.description %}
+
+COMMENT ON TYPE {% if o_data.schema %}{{ conn|qtIdent(o_data.schema, o_data.name) }}{% else %}{{ conn|qtIdent(o_data.name) }}{% endif %}
+
+ IS {{data.description|qtLiteral(conn)}};
+{% endif %}
+{### ACL ###}
+{% if data.typacl and data.typacl|length > 0 %}
+{% if 'deleted' in data.typacl %}
+{% for priv in data.typacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.typacl %}
+{% for priv in data.typacl.changed %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.typacl %}
+{% for priv in data.typacl.added %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{### Security Lables ###}
+{% if data.seclabels %}
+
+{% for r in data.seclabels %}
+{% if r.provider and r.label %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fd40a44a082017108e6885719612ec76b78e76cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/types/templates/types/ppas/sql/default/update.sql
@@ -0,0 +1,161 @@
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'types/macros/get_full_type_sql_format.macros' as GET_TYPE %}
+{#======================================#}
+{# Below will change object owner #}
+{% if data.typeowner and data.typeowner != o_data.typeowner %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ OWNER TO {{ conn|qtIdent(data.typeowner) }};
+
+{% endif %}
+{#======================================#}
+{# Below will change objects comment #}
+{% if data.description is defined and data.description != o_data.description %}
+COMMENT ON TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ IS {{ data.description|qtLiteral(conn) }};
+
+{% endif %}
+{#======================================#}
+{### The sql given below will update composite type ###}
+{% if data.composite and data.composite|length > 0 %}
+{% set composite = data.composite %}
+{% if 'deleted' in composite and composite.deleted|length > 0 %}
+{% for r in composite.deleted %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ DROP ATTRIBUTE {{conn|qtIdent(r.member_name)}};
+{% endfor %}
+{% endif %}
+{% if 'added' in composite and composite.added|length > 0 %}
+{% for r in composite.added %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD ATTRIBUTE {{conn|qtIdent(r.member_name)}} {{ GET_TYPE.CREATE_TYPE_SQL(conn, r.cltype, r.tlength, r.precision, r.hasSqrBracket) }}{% if r.collation %}
+ COLLATE {{r.collation}}{% endif %};
+{% endfor %}
+{% endif %}
+{% if 'changed' in composite and composite.changed|length > 0 %}
+{% for r in composite.changed %}
+{% for o in o_data.composite %}
+{##### Variables for the loop #####}
+{% set member_name = o.member_name %}
+{% set cltype = o.cltype %}
+{% set tlength = o.tlength %}
+{% set precision = o.precision %}
+{% set hasSqrBracket = o.hasSqrBracket %}
+{##### If member name changed #####}
+{% if o.attnum == r.attnum %}
+{% if r.member_name and o.member_name != r.member_name %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME ATTRIBUTE {{o.member_name}} TO {{r.member_name}};
+{% set member_name = r.member_name %}
+{% endif %}
+{##### If type changed #####}
+{% if r.cltype and cltype != r.cltype %}
+{% set cltype = r.cltype %}
+{% set hasSqrBracket = r.hasSqrBracket %}
+{##### If length is not allowed on type #####}
+{% if not r.is_tlength %}
+{% set tlength = 0 %}
+{% set precision = 0 %}
+{% endif %}
+{% endif %}
+{##### If length changed #####}
+{% if r.tlength and tlength != r.tlength %}
+{% set tlength = r.tlength %}
+{% endif %}
+{##### If precision changed #####}
+{% if tlength and r.precision and precision != r.precision %}
+{% set precision = r.precision %}
+{% endif %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ALTER ATTRIBUTE {{conn|qtIdent(member_name)}} SET DATA TYPE {{ GET_TYPE.CREATE_TYPE_SQL(conn, cltype, tlength, precision, hasSqrBracket) }}{% if r.collation %}
+ COLLATE {{r.collation}}{% endif %};
+{% endif%}
+{% endfor %}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#======================================#}
+{### The sql given below will update enum type ###}
+{% if data.enum and data.enum|length > 0 %}
+{% set enum = data.enum %}
+{% set o_enum_len = o_data.enum|length %}
+{# We need actual list index from length #}
+{% set o_enum_len = o_enum_len - 1 %}
+{% if 'added' in enum and enum.added|length > 0 %}
+{% for r in enum.added %}
+{% set c_idx = loop.index %}
+{% if c_idx == 1 %}
+{# if first new element then add it after old data enum list#}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD VALUE {{r.label|qtLiteral(conn)}} {% if o_enum_len > 0 %}AFTER {{o_data.enum[o_enum_len].label|qtLiteral(conn) }}{% endif %};
+{% else %}
+{# if first new element then add it after new data enum list#}
+{% set p_idx = loop.index - 2 %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ ADD VALUE {{r.label|qtLiteral(conn)}} AFTER {{enum.added[p_idx].label|qtLiteral(conn)}};
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#======================================#}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'TYPE', o_data.name, r.provider, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'TYPE', o_data.name, r.provider, r.label, o_data.schema) }}
+{% endfor %}
+{% endif %}
+
+{% endif %}
+{#======================================#}
+{# Change the privileges #}
+{% if data.typacl and data.typacl|length > 0 %}
+{% if 'deleted' in data.typacl %}
+{% for priv in data.typacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.typacl %}
+{% for priv in data.typacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.old_grantee, o_data.name, o_data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TYPE', priv.grantee, o_data.name, o_data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.typacl %}
+{% for priv in data.typacl.added %}
+{{ PRIVILEGE.SET(conn, 'TYPE', priv.grantee, o_data.name, priv.without_grant, priv.with_grant, o_data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{#======================================#}
+{# Below will change object name #}
+{% if data.name and data.name != o_data.name %}
+ALTER TYPE {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{#======================================#}
+{# Below will change the schema for object #}
+{# with extra if condition we will also make sure that object has correct name #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER TYPE {% if data.name and data.name != o_data.name %}{{ conn|qtIdent(o_data.schema, data.name) }}
+{% else %}{{ conn|qtIdent(o_data.schema, o_data.name) }}
+{% endif %}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a1810f38dddda6facb99315c222a228c064892f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/__init__.py
@@ -0,0 +1,2550 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Implements View and Materialized View Node"""
+
+import copy
+import re
+from functools import wraps
+
+import json
+from flask import render_template, request, jsonify, current_app
+from flask_babel import gettext
+from flask_security import current_user
+from pgadmin.browser.server_groups.servers import databases
+from config import PG_DEFAULT_DRIVER
+from pgadmin.browser.server_groups.servers.databases.schemas.utils import \
+ SchemaChildModule, parse_rule_definition, VacuumSettings, get_schema
+from pgadmin.browser.server_groups.servers.utils import parse_priv_from_db, \
+ parse_priv_to_db
+from pgadmin.browser.utils import PGChildNodeView
+from pgadmin.utils.ajax import make_json_response, internal_server_error, \
+ make_response as ajax_response, gone
+from pgadmin.utils.driver import get_driver
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+from .schema_diff_view_utils import SchemaDiffViewCompare
+from pgadmin.utils import html, does_utility_exist, get_server
+from pgadmin.model import Server
+from pgadmin.misc.bgprocess.processes import BatchProcess, IProcessDesc
+
+
+"""
+ This module is responsible for generating two nodes
+ 1) View
+ 2) Materialized View
+
+ We have created single file because view & material view has same
+ functionality. It allows us to share the same submodules for both
+ view, and material view modules.
+
+ This modules uses separate template paths for each respective node
+ - templates/view for View node
+ - templates/materialized_view for the materialized view node
+
+ [Each path contains node specific js files as well as sql template files.]
+"""
+
+
+class ViewModule(SchemaChildModule):
+ """
+ class ViewModule(SchemaChildModule):
+
+ A module class for View node derived from SchemaChildModule.
+
+ Methods:
+ -------
+ * __init__(*args, **kwargs)
+ - Method is used to initialize the View and it's base module.
+
+ * get_nodes(gid, sid, did, scid)
+ - Method is used to generate the browser collection node.
+
+ * node_inode()
+ - Method is overridden from its base class to make the node as leaf node.
+
+ * script_load()
+ - Load the module script for View, when any of the server node is
+ initialized.
+ """
+ _NODE_TYPE = 'view'
+ _COLLECTION_LABEL = gettext("Views")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the ViewModule and it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = None
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(
+ sid, did, scid, base_template_path=ViewNode.BASE_TEMPLATE_PATH +
+ '/' + ViewNode._SQL_PREFIX):
+ yield self.generate_browser_collection_node(scid)
+
+ @property
+ def script_load(self):
+ """
+ Load the module script for views, when any database node is
+ initialized, The reason is views are also listed under catalogs
+ which are loaded under database node.
+ """
+ return databases.DatabaseModule.node_type
+
+ @property
+ def csssnippets(self):
+ """
+ Returns a snippet of css to include in the page
+ """
+ snippets = [
+ render_template(
+ self._COLLECTION_CSS,
+ node_type=self.node_type,
+ _=gettext
+ ),
+ render_template(
+ "views/css/view.css",
+ node_type=self.node_type,
+ _=gettext
+ ),
+ render_template(
+ "mviews/css/mview.css",
+ node_type='mview',
+ _=gettext
+ )
+ ]
+
+ for submodule in self.submodules:
+ snippets.extend(submodule.csssnippets)
+
+ return snippets
+
+ def register(self, app, options):
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.columns import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.indexes import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.triggers import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.rules import blueprint as module
+ self.submodules.append(module)
+ from pgadmin.browser.server_groups.servers.databases.schemas.\
+ tables.compound_triggers import blueprint as module
+ self.submodules.append(module)
+
+ super().register(app, options)
+
+
+class Message(IProcessDesc):
+ def __init__(self, _sid, _data, _query):
+ self.sid = _sid
+ self.data = _data
+ self.query = _query
+
+ @property
+ def message(self):
+ msg = gettext("Refresh Materialized View ({0})")
+ opts = []
+ if not self.data['is_with_data']:
+ opts.append(gettext("WITH NO DATA"))
+ else:
+ opts.append(gettext("WITH DATA"))
+
+ if self.data['is_concurrent']:
+ opts.append(gettext("CONCURRENTLY"))
+
+ msg = msg.format(', '.join(str(x) for x in opts))
+ return msg
+
+ @property
+ def type_desc(self):
+ return gettext("Refresh Materialized View")
+
+ def get_server_name(self):
+ # Fetch the server details like hostname, port, roles etc
+ s = get_server(self.sid)
+
+ if s is None:
+ return gettext("Not available")
+ return "{0} ({1}:{2})".format(s.name, s.host, s.port)
+
+ def details(self, cmd, args):
+ return {
+ "message": self.message,
+ "query": self.query,
+ "server": self.get_server_name(),
+ "object": "{0}/{1}".format(
+ self.data['database'], self.data.get('object', 'Unknown')),
+ "type": gettext("Refresh MView")
+ }
+
+
+class MViewModule(ViewModule):
+ """
+ class MViewModule(ViewModule)
+ A module class for the materialized view node derived from ViewModule.
+ """
+
+ _NODE_TYPE = 'mview'
+ _COLLECTION_LABEL = gettext("Materialized Views")
+
+ def __init__(self, *args, **kwargs):
+ """
+ Method is used to initialize the MViewModule and
+ it's base module.
+
+ Args:
+ *args:
+ **kwargs:
+ """
+ super().__init__(*args, **kwargs)
+ self.min_ver = 90300
+ self.max_ver = None
+
+ def get_nodes(self, gid, sid, did, scid):
+ """
+ Generate the collection node
+ """
+ if self.has_nodes(
+ sid, did, scid, base_template_path=MViewNode.BASE_TEMPLATE_PATH +
+ '/' + MViewNode._SQL_PREFIX):
+ yield self.generate_browser_collection_node(scid)
+
+
+view_blueprint = ViewModule(__name__)
+mview_blueprint = MViewModule(__name__)
+
+
+def check_precondition(f):
+ """
+ This function will behave as a decorator which will checks
+ database connection before running view, it will also attaches
+ manager,conn & template_path properties to instance of the method.
+
+ Assumptions:
+ This function will always be used as decorator of a class method.
+ """
+
+ @wraps(f)
+ def wrap(*args, **kwargs):
+
+ # Here args[0] will hold self & kwargs will hold gid,sid,did
+ self = args[0]
+ pg_driver = get_driver(PG_DEFAULT_DRIVER)
+ self.qtIdent = pg_driver.qtIdent
+ self.manager = pg_driver.connection_manager(
+ kwargs['sid']
+ )
+ self.conn = self.manager.connection(did=kwargs['did'])
+ self.template_path = self.BASE_TEMPLATE_PATH.format(
+ self.manager.server_type, self.manager.version)
+
+ self.column_template_path = 'columns/sql/#{0}#'.format(
+ self.manager.version)
+
+ # Template for trigger node
+ self.trigger_template_path = 'triggers/sql/{0}/#{1}#'.format(
+ self.manager.server_type, self.manager.version)
+
+ # Template for compound trigger node
+ self.compound_trigger_template_path = (
+ 'compound_triggers/sql/{0}/#{1}#'.format(
+ self.manager.server_type, self.manager.version))
+
+ # Template for rules node
+ self.rules_template_path = 'rules/sql'
+
+ # Template for index node
+ self.index_template_path = 'indexes/sql/#{0}#'.format(
+ self.manager.version)
+
+ # Submodule list for schema diff
+ self.view_sub_modules = ['rule', 'trigger', 'index']
+ if (self.manager.server_type == 'ppas' and
+ self.manager.version >= 120000):
+ self.view_sub_modules.append('compound_trigger')
+
+ try:
+ self.allowed_acls = render_template(
+ "/".join([self.template_path, self._ALLOWED_PRIVS_JSON])
+ )
+ self.allowed_acls = json.loads(self.allowed_acls)
+ except Exception as e:
+ current_app.logger.exception(e)
+
+ return f(*args, **kwargs)
+
+ return wrap
+
+
+class ViewNode(PGChildNodeView, VacuumSettings, SchemaDiffViewCompare):
+ """
+ This class is responsible for generating routes for view node.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the ViewNode and it's base view.
+
+ * list()
+ - This function is used to list all the view nodes within the
+ collection.
+
+ * nodes()
+ - This function will used to create all the child node within the
+ collection, Here it will create all the view node.
+
+ * properties(gid, sid, did, scid)
+ - This function will show the properties of the selected view node.
+
+ * create(gid, sid, did, scid)
+ - This function will create the new view object.
+
+ * update(gid, sid, did, scid)
+ - This function will update the data for the selected view node.
+
+ * delete(self, gid, sid, scid):
+ - This function will drop the view object
+
+ * msql(gid, sid, did, scid)
+ - This function is used to return modified SQL for the selected view
+ node.
+
+ * getSQL(data, scid)
+ - This function will generate sql from model data
+
+ * sql(gid, sid, did, scid):
+ - This function will generate sql to show it in sql pane for the view
+ node.
+
+ * select_sql(gid, sid, did, scid, vid):
+ - Returns select sql for Object
+
+ * insert_sql(gid, sid, did, scid, vid):
+ - Returns INSERT Script sql for the object
+
+ * dependency(gid, sid, did, scid):
+ - This function will generate dependency list show it in dependency
+ pane for the selected view node.
+
+ * dependent(gid, sid, did, scid):
+ - This function will generate dependent list to show it in dependent
+ pane for the selected view node.
+
+ * compare(**kwargs):
+ - This function will compare the view nodes from two
+ different schemas.
+ """
+ node_type = view_blueprint.node_type
+ _SQL_PREFIX = 'sql/'
+ _ALLOWED_PRIVS_JSON = 'sql/allowed_privs.json'
+ PROPERTIES_PATH = 'sql/{0}/#{1}#/properties.sql'
+ BASE_TEMPLATE_PATH = 'views/{0}/#{1}#'
+
+ parent_ids = [
+ {'type': 'int', 'id': 'gid'},
+ {'type': 'int', 'id': 'sid'},
+ {'type': 'int', 'id': 'did'},
+ {'type': 'int', 'id': 'scid'}
+ ]
+ ids = [
+ {'type': 'int', 'id': 'vid'}
+ ]
+
+ operations = dict({
+ 'obj': [
+ {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+ {'get': 'list', 'post': 'create', 'delete': 'delete'}
+ ],
+ 'children': [{
+ 'get': 'children'
+ }],
+ 'delete': [{'delete': 'delete'}, {'delete': 'delete'}],
+ 'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+ 'sql': [{'get': 'sql'}],
+ 'msql': [{'get': 'msql'}, {'get': 'msql'}],
+ 'stats': [{'get': 'statistics'}, {'get': 'statistics'}],
+ 'dependency': [{'get': 'dependencies'}],
+ 'dependent': [{'get': 'dependents'}],
+ 'configs': [{'get': 'configs'}],
+ 'get_tblspc': [{'get': 'get_tblspc'}, {'get': 'get_tblspc'}],
+ 'select_sql': [{'get': 'select_sql'}, {'get': 'select_sql'}],
+ 'insert_sql': [{'get': 'insert_sql'}, {'get': 'insert_sql'}],
+ 'get_table_vacuum': [
+ {'get': 'get_table_vacuum'},
+ {'get': 'get_table_vacuum'}],
+ 'get_toast_table_vacuum': [
+ {'get': 'get_toast_table_vacuum'},
+ {'get': 'get_toast_table_vacuum'}]
+ })
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the variables used by methods of ViewNode.
+ """
+
+ super().__init__(*args, **kwargs)
+
+ self.manager = None
+ self.conn = None
+ self.template_path = None
+ self.allowed_acls = []
+
+ @check_precondition
+ def list(self, gid, sid, did, scid):
+ """
+ Fetches all views properties and render into properties tab
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ did=did, scid=scid)
+ status, res = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+ return ajax_response(
+ response=res['rows'],
+ status=200
+ )
+
+ @check_precondition
+ def node(self, gid, sid, did, scid, vid):
+ """
+ Lists all views under the Views Collection node
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._NODES_SQL]),
+ vid=vid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ if len(rset['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ res = self.blueprint.generate_browser_node(
+ rset['rows'][0]['oid'],
+ scid,
+ rset['rows'][0]['name'],
+ icon="icon-view" if self.node_type == 'view'
+ else "icon-mview",
+ description=rset['rows'][0]['comment']
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def nodes(self, gid, sid, did, scid):
+ """
+ Lists all views under the Views Collection node
+ """
+ res = []
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._NODES_SQL]),
+ scid=scid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ res.append(
+ self.blueprint.generate_browser_node(
+ row['oid'],
+ scid,
+ row['name'],
+ icon="icon-view" if self.node_type == 'view'
+ else "icon-mview",
+ description=row['comment']
+ ))
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, vid):
+ """
+ Fetches the properties of an individual view
+ and render in the properties tab
+ """
+ status, res = self._fetch_properties(scid, vid)
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_properties(self, scid, vid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param scid:
+ :param vid:
+ :return:
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL]
+ ), vid=vid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._ACL_SQL]), vid=vid)
+ status, dataclres = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ for row in dataclres['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ result = res['rows'][0]
+
+ # sending result to formtter
+ frmtd_reslt = self.formatter(result)
+
+ # merging formatted result with main result again
+ result.update(frmtd_reslt)
+
+ return True, result
+
+ @staticmethod
+ def formatter(result):
+ """ This function formats output for security label & variables"""
+ frmtd_result = dict()
+ sec_lbls = []
+ if 'seclabels' in result and result['seclabels'] is not None:
+ for sec in result['seclabels']:
+ import re
+ sec = re.search(r'([^=]+)=(.*$)', sec)
+ sec_lbls.append({
+ 'provider': sec.group(1),
+ 'label': sec.group(2)
+ })
+
+ frmtd_result.update({"seclabels": sec_lbls})
+ return frmtd_result
+
+ @check_precondition
+ def create(self, gid, sid, did, scid):
+ """
+ This function will create a new view object
+ """
+ required_args = [
+ 'name',
+ 'definition'
+ ]
+
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ for arg in required_args:
+ if arg not in data:
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=gettext(
+ "Could not find the required parameter ({})."
+ ).format(arg)
+ )
+ try:
+ SQL, name_or_error = self.getSQL(gid, sid, did, data)
+ if SQL is None:
+ return name_or_error
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template("/".join(
+ [self.template_path, 'sql/view_id.sql']), data=data,
+ conn=self.conn)
+ status, view_id = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ # Get updated schema oid
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._OID_SQL]),
+ vid=view_id)
+ status, new_scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=new_scid)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ view_id,
+ new_scid,
+ data['name'],
+ icon="icon-view" if self.node_type == 'view'
+ else "icon-mview",
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def update(self, gid, sid, did, scid, vid):
+ """
+ This function will update a view object
+ """
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ try:
+ SQL, name = self.getSQL(gid, sid, did, data, vid)
+ if SQL is None:
+ return name
+ SQL = SQL.strip('\n').strip(' ')
+ status, res = self.conn.execute_void(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ SQL = render_template("/".join(
+ [self.template_path, 'sql/view_id.sql']), data=data,
+ conn=self.conn)
+ status, res_data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ view_id = res_data['rows'][0]['oid']
+ new_view_name = res_data['rows'][0]['relname']
+
+ # Get updated schema oid
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._OID_SQL]),
+ vid=view_id)
+ status, new_scid = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=new_scid)
+
+ other_node_info = {}
+ if 'comment' in data:
+ other_node_info['description'] = data['comment']
+
+ return jsonify(
+ node=self.blueprint.generate_browser_node(
+ view_id,
+ new_scid,
+ new_view_name,
+ icon="icon-view" if self.node_type == 'view'
+ else "icon-mview",
+ **other_node_info
+ )
+ )
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def delete(self, gid, sid, did, scid, vid=None, only_sql=False):
+ """
+ This function will drop a view object
+ """
+ if vid is None:
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+ else:
+ data = {'ids': [vid]}
+
+ # Below will decide if it's simple drop or drop with cascade call
+
+ cascade = self._check_cascade_operation()
+
+ try:
+ for vid in data['ids']:
+ # Get name for view from vid
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ did=did,
+ vid=vid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res_data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res_data)
+
+ if not res_data['rows']:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ 'Error: Object not found.'
+ ),
+ info=self.not_found_error_msg()
+ )
+
+ # drop view
+ SQL = render_template(
+ "/".join([self.template_path,
+ self._SQL_PREFIX + self._DELETE_SQL]),
+ nspname=res_data['rows'][0]['schema'],
+ name=res_data['rows'][0]['name'], cascade=cascade
+ )
+
+ if only_sql:
+ return SQL
+
+ status, res = self.conn.execute_scalar(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ success=1,
+ info=gettext("View dropped")
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ def _get_schema(self, scid):
+ """
+ Returns Schema Name from its OID.
+
+ Args:
+ scid: Schema Id
+ """
+ SQL = render_template("/".join([self.template_path,
+ 'sql/get_schema.sql']), scid=scid)
+
+ status, schema_name = self.conn.execute_scalar(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ return schema_name
+
+ @check_precondition
+ def msql(self, gid, sid, did, scid, vid=None):
+ """
+ This function returns modified SQL
+ """
+ data = {}
+ for k, v in request.args.items():
+ try:
+ # comments should be taken as is because if user enters a
+ # json comment it is parsed by loads which should not happen
+ if k in ('comment',):
+ data[k] = v
+ else:
+ data[k] = json.loads(v)
+ except ValueError:
+ data[k] = v
+
+ sql, name_or_error = self.getSQL(gid, sid, did, data, vid)
+ if sql is None:
+ return name_or_error
+
+ sql = sql.strip('\n').strip(' ')
+
+ if sql == '':
+ sql = "--modified SQL"
+
+ return make_json_response(
+ data=sql,
+ status=200
+ )
+
+ @staticmethod
+ def _parse_privilege_data(acls, data):
+ """
+ Check and parse privilege data.
+ acls: allowed privileges
+ data: data on which we check for having privilege or not.
+ """
+ for aclcol in acls:
+ if aclcol in data:
+ allowedacl = acls[aclcol]
+
+ for key in ['added', 'changed', 'deleted']:
+ if key in data[aclcol]:
+ data[aclcol][key] = parse_priv_to_db(
+ data[aclcol][key], allowedacl['acl']
+ )
+
+ @staticmethod
+ def _get_info_from_data(data, res):
+ """
+ Get name and schema data
+ data: sql data.
+ res: properties sql response.
+ """
+ if 'name' not in data:
+ data['name'] = res['rows'][0]['name']
+ if 'schema' not in data:
+ data['schema'] = res['rows'][0]['schema']
+
+ def getSQL(self, gid, sid, did, data, vid=None):
+ """
+ This function will generate sql from model data
+ """
+ if vid is not None:
+ sql = render_template("/".join(
+ [self.template_path,
+ self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ vid=vid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(sql)
+ if not status:
+ return None, internal_server_error(errormsg=res)
+ elif len(res['rows']) == 0:
+ return None, gone(self.not_found_error_msg())
+ old_data = res['rows'][0]
+
+ ViewNode._get_info_from_data(data, res)
+
+ # Privileges
+ ViewNode._parse_privilege_data(self.allowed_acls, data)
+
+ data['del_sql'] = False
+ old_data['acl_sql'] = ''
+
+ is_error, errmsg = self._get_definition_data(vid, data, old_data,
+ res,
+ self.allowed_acls)
+ if is_error:
+ return None, errmsg
+
+ self.view_schema = old_data['schema']
+
+ try:
+ sql = self._get_update_sql(did, vid, data, old_data)
+ except Exception as e:
+ current_app.logger.exception(e)
+ return None, internal_server_error(errormsg=str(e))
+ else:
+ is_error, errmsg, sql = self._get_create_view_sql(data)
+ if is_error:
+ return None, errmsg
+
+ return sql, data['name'] if 'name' in data else old_data['name']
+
+ def _get_update_sql(self, did, vid, data, old_data):
+ """
+ Get sql for update view.
+ :param did: Database Id.
+ :param vid: View Id.
+ :param data: data for get sql.
+ :param old_data: old view data for get sql.
+ :return: sql for update view.
+ """
+ sql = render_template("/".join(
+ [self.template_path,
+ self._SQL_PREFIX + self._UPDATE_SQL]), data=data,
+ o_data=old_data, conn=self.conn)
+
+ if 'definition' in data and data['definition']:
+ sql += self.get_columns_sql(did, vid)
+ return sql
+
+ def _get_create_view_sql(self, data):
+ """
+ Get create view sql with it's privileges.
+ data: Source data for sql generation
+ return: created sql for create view.
+ """
+ required_args = [
+ 'name',
+ 'schema',
+ 'definition'
+ ]
+ for arg in required_args:
+ if arg not in data:
+ return True, make_json_response(
+ data=gettext(" -- definition incomplete"),
+ status=200
+ ), ''
+
+ # Get Schema Name from its OID.
+ if 'schema' in data and isinstance(data['schema'], int):
+ data['schema'] = self._get_schema(data['schema'])
+
+ # Privileges
+ ViewNode._parse_priv_data(self.allowed_acls, data)
+
+ sql = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ if data['definition']:
+ sql += "\n"
+ sql += render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=data)
+
+ return False, '', sql
+
+ def _get_definition_data(self, vid, data, old_data, res, acls):
+ """
+ Check and process definition data.
+ vid: View Id.
+ data: sql data.
+ old_data: properties sql data.
+ res: Response data from properties sql.
+ acls: allowed privileges.
+
+ return: If any error it will return True with error msg,
+ if not retun False with error msg empty('')
+ """
+ if 'definition' in data and self.manager.server_type == 'pg':
+ new_def = re.sub(r"\W", "", data['definition']).split('FROM')
+ old_def = re.sub(r"\W", "", res['rows'][0]['definition']
+ ).split('FROM')
+ if 'definition' in data and (
+ len(old_def) > 1 or len(new_def) > 1
+ ) and (
+ old_def[0] != new_def[0] and
+ old_def[0] not in new_def[0]
+ ):
+ data['del_sql'] = True
+
+ # If we drop and recreate the view, the
+ # privileges must be restored
+
+ # Fetch all privileges for view
+ is_error, errmsg = self._fetch_all_view_priv(vid, res)
+ if is_error:
+ return True, errmsg
+
+ old_data.update(res['rows'][0])
+
+ # Privileges
+ ViewNode._parse_priv_data(acls, old_data)
+
+ old_data['acl_sql'] = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=old_data)
+ return False, ''
+
+ def _fetch_all_view_priv(self, vid, res):
+ """
+ This is for fetch all privileges for the view.
+ vid: View ID
+ res: response data from property sql
+ """
+ sql_acl = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._ACL_SQL]), vid=vid)
+ status, dataclres = self.conn.execute_dict(sql_acl)
+ if not status:
+ return True, internal_server_error(errormsg=res)
+
+ for row in dataclres['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []
+ ).append(priv)
+ return False, ''
+
+ @staticmethod
+ def _parse_priv_data(acls, data):
+ """
+ Iterate privilege data and send it for parsing before send it to db.
+ acls: allowed privileges
+ data: data on which we check for privilege check.
+ """
+ for aclcol in acls:
+ if aclcol in data:
+ allowedacl = acls[aclcol]
+ data[aclcol] = parse_priv_to_db(
+ data[aclcol], allowedacl['acl'])
+
+ def get_index_column_details(self, idx, data):
+ """
+ This functional will fetch list of column details for index
+
+ Args:
+ idx: Index OID
+ data: Properties data
+
+ Returns:
+ Updated properties data with column details
+ """
+
+ self.index_temp_path = 'indexes'
+ SQL = render_template("/".join([self.index_temp_path,
+ 'sql/#{0}#/column_details.sql'.format(
+ self.manager.version)]), idx=idx)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ # 'attdef' comes with quotes from query so we need to strip them
+ # 'options' we need true/false to render switch ASC(false)/DESC(true)
+ columns = []
+ cols = []
+ for row in rset['rows']:
+
+ # We need all data as collection for ColumnsModel
+ cols_data = {
+ 'colname': row['attdef'],
+ 'collspcname': row['collnspname'],
+ 'op_class': row['opcname'],
+ }
+ if row['options'][0] == 'DESC':
+ cols_data['sort_order'] = True
+ columns.append(cols_data)
+
+ # We need same data as string to display in properties window
+ # If multiple column then separate it by colon
+ cols_str = row['attdef']
+ if row['collnspname']:
+ cols_str += ' COLLATE ' + row['collnspname']
+ if row['opcname']:
+ cols_str += ' ' + row['opcname']
+ if row['options'][0] == 'DESC':
+ cols_str += ' DESC'
+ cols.append(cols_str)
+
+ # Push as collection
+ data['columns'] = columns
+ # Push as string
+ data['cols'] = ', '.join(cols)
+
+ return data
+
+ def get_trigger_column_details(self, tid, clist):
+ """
+ This function will fetch list of column for trigger
+
+ Args:
+ tid: Table OID
+ clist: List of columns
+
+ Returns:
+ Updated properties data with column
+ """
+
+ self.trigger_temp_path = 'schemas/triggers'
+ SQL = render_template("/".join([self.trigger_temp_path,
+ self._GET_COLUMNS_SQL]),
+ tid=tid, clist=clist)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+ # 'tgattr' contains list of columns from table used in trigger
+ columns = []
+
+ for row in rset['rows']:
+ columns.append({'column': row['name']})
+
+ return columns
+
+ def get_rule_sql(self, vid, display_comments=True):
+ """
+ Get all non system rules of view node,
+ generate their sql and render
+ into sql tab
+ """
+
+ self.rule_temp_path = 'rules'
+ sql_data = ''
+ SQL = render_template("/".join(
+ [self.rule_temp_path, self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ tid=vid)
+
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ for rule in data['rows']:
+
+ # Generate SQL only for non system rule
+ if rule['name'] != '_RETURN':
+ res = []
+ SQL = render_template("/".join(
+ [self.rule_temp_path,
+ self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ rid=rule['oid']
+ )
+ status, res = self.conn.execute_dict(SQL)
+ res = parse_rule_definition(res)
+ SQL = render_template("/".join(
+ [self.rule_temp_path,
+ self._SQL_PREFIX + self._CREATE_SQL]),
+ data=res, display_comments=display_comments,
+ conn=self.conn)
+ sql_data += '\n'
+ sql_data += SQL
+ return sql_data
+
+ def _generate_and_return_trigger_sql(self, vid, data, display_comments,
+ sql_data):
+ """
+ Iterate trigger data and generate sql for different tabs of trigger.
+ vid: View ID
+ data: Trigger data for iteration.
+ display_comments: comments for sql
+ sql_data: Sql queries
+ return: Check if any error then return error, else return sql data.
+ """
+
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+
+ for trigger in data['rows']:
+ SQL = render_template("/".join(
+ [self.ct_trigger_temp_path,
+ self.PROPERTIES_PATH.format(
+ self.manager.server_type, self.manager.version)]),
+ tid=vid,
+ trid=trigger['oid']
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return True, internal_server_error(errormsg=res), ''
+
+ if len(res['rows']) == 0:
+ continue
+ res_rows = dict(res['rows'][0])
+ res_rows['table'] = res_rows['relname']
+ res_rows['schema'] = self.view_schema
+
+ if len(res_rows['tgattr']) > 1:
+ columns = ', '.join(res_rows['tgattr'].split(' '))
+ SQL = render_template("/".join(
+ [self.ct_trigger_temp_path,
+ 'sql/{0}/#{1}#/get_columns.sql'.format(
+ self.manager.server_type,
+ self.manager.version)]),
+ tid=trigger['oid'],
+ clist=columns)
+
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return True, internal_server_error(errormsg=rset), ''
+ columns = []
+
+ for col_row in rset['rows']:
+ columns.append(col_row['name'])
+
+ res_rows['columns'] = columns
+
+ res_rows = trigger_definition(res_rows)
+ SQL = render_template("/".join(
+ [self.ct_trigger_temp_path,
+ 'sql/{0}/#{1}#/create.sql'.format(
+ self.manager.server_type, self.manager.version)]),
+ data=res_rows, display_comments=display_comments,
+ conn=self.conn)
+ sql_data += '\n'
+ sql_data += SQL
+
+ return False, '', sql_data
+
+ def get_compound_trigger_sql(self, vid, display_comments=True):
+ """
+ Get all compound trigger nodes associated with view node,
+ generate their sql and render into sql tab
+ """
+ sql_data = ''
+ if self.manager.server_type == 'ppas' \
+ and self.manager.version >= 120000:
+
+ # Define template path
+ self.ct_trigger_temp_path = 'compound_triggers'
+
+ SQL = render_template("/".join(
+ [self.ct_trigger_temp_path,
+ 'sql/{0}/#{1}#/nodes.sql'.format(
+ self.manager.server_type, self.manager.version)]),
+ tid=vid)
+
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ is_error, errmsg, sql_data = \
+ self._generate_and_return_trigger_sql(
+ vid, data, display_comments, sql_data)
+
+ if is_error:
+ return errmsg
+
+ return sql_data
+
+ def get_trigger_sql(self, vid, display_comments=True):
+ """
+ Get all trigger nodes associated with view node,
+ generate their sql and render
+ into sql tab
+ """
+ from pgadmin.browser.server_groups.servers.databases.schemas.utils \
+ import trigger_definition
+
+ # Define template path
+ self.trigger_temp_path = 'triggers'
+
+ sql_data = ''
+ SQL = render_template("/".join(
+ [self.trigger_temp_path,
+ self.PROPERTIES_PATH.format(
+ self.manager.server_type, self.manager.version)]),
+ tid=vid)
+
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ for trigger in data['rows']:
+ SQL = render_template("/".join(
+ [self.trigger_temp_path,
+ self.PROPERTIES_PATH.format(
+ self.manager.server_type, self.manager.version)]),
+ tid=vid,
+ trid=trigger['oid']
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+
+ res_rows = dict(res['rows'][0])
+ if res_rows['tgnargs'] > 1:
+ # We know that trigger has more than 1
+ # arguments, let's join them
+ res_rows['tgargs'] = ', '.join(
+ res_rows['tgargs'])
+
+ if len(res_rows['tgattr']) > 1:
+ columns = ', '.join(res_rows['tgattr'].split(' '))
+ res_rows['columns'] = self.get_trigger_column_details(
+ trigger['oid'], columns)
+ res_rows = trigger_definition(res_rows)
+
+ # It should be relname and not table, but in create.sql
+ # (which is referred from many places) we have used
+ # data.table and not data.relname so compatibility add new key as
+ # table in res_rows.
+ res_rows['table'] = res_rows['relname']
+ res_rows['schema'] = self.view_schema
+
+ # Get trigger function with its schema name
+ SQL = render_template("/".join([
+ self.trigger_temp_path,
+ 'sql/{0}/#{1}#/get_triggerfunctions.sql'.format(
+ self.manager.server_type, self.manager.version)]),
+ tgfoid=res_rows['tgfoid'],
+ show_system_objects=self.blueprint.show_system_objects)
+
+ status, result = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=result)
+
+ # Update the trigger function which we have fetched with
+ # schemaname
+ if (
+ 'rows' in result and len(result['rows']) > 0 and
+ 'tfunctions' in result['rows'][0]
+ ):
+ res_rows['tfunction'] = result['rows'][0]['tfunctions']
+
+ # Format arguments
+ if len(res_rows['custom_tgargs']) > 0:
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ formatted_args = [driver.qtLiteral(arg, self.conn)
+ for arg in res_rows['custom_tgargs']]
+ res_rows['tgargs'] = ', '.join(formatted_args)
+ else:
+ res_rows['tgargs'] = None
+
+ SQL = render_template("/".join(
+ [self.trigger_temp_path,
+ 'sql/{0}/#{1}#/create.sql'.format(
+ self.manager.server_type, self.manager.version)]),
+ data=res_rows, display_comments=display_comments,
+ conn=self.conn)
+ sql_data += '\n'
+ sql_data += SQL
+
+ return sql_data
+
+ def get_index_sql(self, did, vid, display_comments=True):
+ """
+ Get all index associated with view node,
+ generate their sql and render
+ into sql tab
+ """
+
+ self.index_temp_path = 'indexes'
+ sql_data = ''
+ SQL = render_template("/".join(
+ [self.index_temp_path,
+ 'sql/#{0}#/properties.sql'.format(self.manager.version)]),
+ did=did,
+ tid=vid)
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ for index in data['rows']:
+ res = []
+ SQL = render_template("/".join(
+ [self.index_temp_path,
+ 'sql/#{0}#/properties.sql'.format(self.manager.version)]),
+ idx=index['oid'],
+ did=did,
+ tid=vid
+ )
+ status, res = self.conn.execute_dict(SQL)
+
+ data = dict(res['rows'][0])
+ # Adding parent into data dict, will be using it while creating sql
+ data['schema'] = data['nspname']
+ data['table'] = data['tabname']
+
+ # Add column details for current index
+ data = self.get_index_column_details(index['oid'], data)
+
+ SQL = render_template("/".join(
+ [self.index_temp_path,
+ 'sql/#{0}#/create.sql'.format(self.manager.version)]),
+ data=data, display_comments=display_comments,
+ conn=self.conn)
+ sql_data += '\n'
+ sql_data += SQL
+ return sql_data
+
+ def get_columns_sql(self, did, vid):
+ """
+ Get all column associated with view node,
+ generate their sql and render
+ into sql tab
+ """
+
+ sql_data = ''
+ SQL = render_template("/".join(
+ [self.column_template_path,
+ self._PROPERTIES_SQL.format(self.manager.version)]),
+ did=did,
+ tid=vid)
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ for rows in data['rows']:
+
+ res = {
+ 'name': rows['name'],
+ 'atttypid': rows['atttypid'],
+ 'attlen': rows['attlen'],
+ 'typnspname': rows['typnspname'],
+ 'defval': None,
+ 'description': None,
+ 'table': rows['relname'],
+ 'schema': self.view_schema
+ }
+
+ o_data = copy.deepcopy(rows)
+
+ # Generate alter statement for default value
+ if 'defval' in rows and rows['defval'] is not None:
+ res['defval'] = rows['defval']
+ o_data['defval'] = None
+
+ # Generate alter statement for comments
+ if 'description' in rows and (rows['description'] is not None or
+ rows['description'] != ''):
+ res['description'] = rows['description']
+ o_data['description'] = None
+
+ SQL = render_template("/".join(
+ [self.column_template_path,
+ self._UPDATE_SQL.format(self.manager.version)]),
+ o_data=o_data, data=res, is_view_only=True,
+ conn=self.conn)
+ sql_data += SQL
+
+ # Get Column Grant SQL
+ for rows in data['rows']:
+ res = {
+ 'name': rows['name'],
+ 'table': rows['relname'],
+ 'schema': self.view_schema
+ }
+
+ if 'attacl' in rows and rows['attacl']:
+ # We need to parse & convert ACL coming from database to json
+ # format
+ SQL = render_template(
+ "/".join([self.column_template_path, 'acl.sql']),
+ tid=vid, clid=rows['attnum'])
+ status, acl = self.conn.execute_dict(SQL)
+
+ if not status:
+ return internal_server_error(errormsg=acl)
+
+ allowed_acls = []
+ if self.allowed_acls and 'datacl' in self.allowed_acls and \
+ 'acl' in self.allowed_acls['datacl']:
+ allowed_acls = self.allowed_acls['datacl']['acl']
+
+ deftypes = set()
+ for row in acl['rows']:
+ priv = parse_priv_from_db(row)
+ res.setdefault(row['deftype'], []).append(priv)
+ deftypes.add(row['deftype'])
+
+ for deftype in deftypes:
+ res[deftype] = \
+ parse_priv_to_db(res[deftype], allowed_acls)
+
+ grant_sql = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=res)
+
+ sql_data += grant_sql
+
+ return sql_data
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, vid, **kwargs):
+ """
+ This function will generate sql to render into the sql panel
+ """
+ json_resp = kwargs.get('json_resp', True)
+ target_schema = kwargs.get('target_schema', None)
+ display_comments = True
+
+ if not json_resp:
+ display_comments = False
+
+ sql_data = ''
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL]),
+ vid=vid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ )
+
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ result = res['rows'][0]
+ if target_schema:
+ result['definition'] = result['definition'].replace(
+ result['schema'], target_schema)
+ result['schema'] = target_schema
+
+ # sending result to formtter
+ frmtd_reslt = self.formatter(result)
+
+ # merging formated result with main result again
+ result.update(frmtd_reslt)
+ self.view_schema = result.get('schema')
+
+ # Fetch all privileges for view
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._ACL_SQL]), vid=vid)
+ status, dataclres = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in dataclres['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ result.update(res['rows'][0])
+
+ # Privileges
+ for aclcol in self.allowed_acls:
+ if aclcol in result:
+ allowedacl = self.allowed_acls[aclcol]
+ result[aclcol] = parse_priv_to_db(
+ result[aclcol], allowedacl['acl']
+ )
+
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._CREATE_SQL]),
+ data=result,
+ conn=self.conn,
+ display_comments=display_comments,
+ add_replace_clause=True
+ )
+ SQL += "\n"
+ SQL += render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=result)
+
+ if ('seclabels' in result and len(result['seclabels']) > 0)\
+ or ('datacl' in result and len(result['datacl']) > 0):
+ SQL += "\n"
+
+ sql_data += SQL
+ sql_data += self.get_rule_sql(vid, display_comments)
+ sql_data += self.get_trigger_sql(vid, display_comments)
+ sql_data += self.get_compound_trigger_sql(vid, display_comments)
+ sql_data += self.get_index_sql(did, vid, display_comments)
+ sql_data += self.get_columns_sql(did, vid)
+
+ if not json_resp:
+ return sql_data
+ return ajax_response(response=sql_data)
+
+ @check_precondition
+ def get_tblspc(self, gid, sid, did, scid):
+ """
+ This function to return list of tablespaces
+ """
+ res = []
+ try:
+ SQL = render_template(
+ "/".join([self.template_path, 'sql/get_tblspc.sql'])
+ )
+ status, rset = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ res.append(
+ {'label': row['spcname'], 'value': row['spcname']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def dependents(self, gid, sid, did, scid, vid):
+ """
+ This function gets the dependents and returns an ajax response
+ for the view node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ vid: View ID
+ """
+ dependents_result = self.get_dependents(self.conn, vid)
+ return ajax_response(
+ response=dependents_result,
+ status=200
+ )
+
+ @check_precondition
+ def dependencies(self, gid, sid, did, scid, vid):
+ """
+ This function gets the dependencies and returns an ajax response
+ for the view node.
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ vid: View ID
+ """
+ dependencies_result = self.get_dependencies(self.conn, vid)
+ return ajax_response(
+ response=dependencies_result,
+ status=200
+ )
+
+ @check_precondition
+ def select_sql(self, gid, sid, did, scid, vid):
+ """
+ SELECT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ vid: View Id
+
+ Returns:
+ SELECT Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([
+ self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL
+ ]),
+ scid=scid, vid=vid, did=did,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+ data_view = res['rows'][0]
+
+ SQL = render_template(
+ "/".join([
+ self.column_template_path, self._PROPERTIES_SQL
+ ]),
+ scid=scid, tid=vid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ columns = []
+
+ # Now we have all list of columns which we need
+ data = data['rows']
+ for c in data:
+ columns.append(self.qtIdent(self.conn, c['name']))
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ else:
+ columns = '*'
+
+ sql = "SELECT {0}\n\tFROM {1};".format(
+ columns,
+ self.qtIdent(self.conn, data_view['schema'], data_view['name'])
+ )
+
+ return ajax_response(response=sql)
+
+ @check_precondition
+ def insert_sql(self, gid, sid, did, scid, vid):
+ """
+ INSERT script sql for the object
+
+ Args:
+ gid: Server Group Id
+ sid: Server Id
+ did: Database Id
+ scid: Schema Id
+ foid: Foreign Table Id
+
+ Returns:
+ INSERT Script sql for the object
+ """
+ SQL = render_template(
+ "/".join([
+ self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL
+ ]),
+ scid=scid, vid=vid, did=did,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ data_view = res['rows'][0]
+
+ SQL = render_template(
+ "/".join([
+ self.column_template_path, self._PROPERTIES_SQL
+ ]),
+ scid=scid, tid=vid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID
+ )
+ status, data = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=data)
+
+ columns = []
+ values = []
+
+ # Now we have all list of columns which we need
+ data = data['rows']
+ for c in data:
+ columns.append(self.qtIdent(self.conn, c['name']))
+ values.append('?')
+
+ if len(columns) > 0:
+ columns = ", ".join(columns)
+ values = ", ".join(values)
+ sql = "INSERT INTO {0}(\n\t{1})\n\tVALUES ({2});".format(
+ self.qtIdent(
+ self.conn, data_view['schema'], data_view['name']
+ ),
+ columns, values
+ )
+ else:
+ sql = gettext('-- Please create column(s) first...')
+
+ return ajax_response(response=sql)
+
+ def _get_sub_module_data_for_compare(self, sid, did, scid, data, vid):
+ # Get sub module data of a specified view for object
+ # comparison
+ for module in self.view_sub_modules:
+ module_view = SchemaDiffRegistry.get_node_view(module)
+ if module_view.blueprint.server_type is None or \
+ self.manager.server_type in \
+ module_view.blueprint.server_type:
+ sub_data = module_view.fetch_objects_to_compare(
+ sid=sid, did=did, scid=scid, tid=vid,
+ oid=None)
+ data[module] = sub_data
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, oid=None):
+ """
+ This function will fetch the list of all the views for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+
+ if not oid:
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._NODES_SQL]),
+ did=did, scid=scid,
+ datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ schema_diff=True)
+ status, views = self.conn.execute_2darray(SQL)
+ if not status:
+ current_app.logger.error(views)
+ return False
+
+ for row in views['rows']:
+ status, data = self._fetch_properties(scid, row['oid'])
+ if status:
+ # Fetch the data of sub module
+ self._get_sub_module_data_for_compare(
+ sid, did, scid, data, row['oid'])
+ res[row['name']] = data
+ else:
+ status, data = self._fetch_properties(scid, oid)
+ if not status:
+ current_app.logger.error(data)
+ return False
+ res = data
+
+ return res
+
+ def get_sql_from_view_diff(self, **kwargs):
+ """
+ This function is used to get the DDL/DML statements.
+ :param kwargs
+ :return:
+ """
+ gid = kwargs.get('gid')
+ sid = kwargs.get('sid')
+ did = kwargs.get('did')
+ scid = kwargs.get('scid')
+ oid = kwargs.get('tid')
+ diff_data = kwargs.get('diff_data', None)
+ drop_sql = kwargs.get('drop_sql', False)
+ target_schema = kwargs.get('target_schema', None)
+
+ if diff_data:
+ if target_schema:
+ diff_data['schema'] = target_schema
+ sql, _ = self.getSQL(gid, sid, did, diff_data, oid)
+ if sql.find('DROP VIEW') != -1:
+ sql = gettext("""
+-- Changing the columns in a view requires dropping and re-creating the view.
+-- This may fail if other objects are dependent upon this view,
+-- or may cause procedural functions to fail if they are not modified to
+-- take account of the changes.
+""") + sql
+ else:
+ if drop_sql:
+ sql = self.delete(gid=gid, sid=sid, did=did,
+ scid=scid, vid=oid, only_sql=True)
+ elif target_schema:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, vid=oid,
+ target_schema=target_schema, json_resp=False)
+ else:
+ sql = self.sql(gid=gid, sid=sid, did=did, scid=scid, vid=oid,
+ json_resp=False)
+ return sql
+
+ def get_submodule_template_path(self, module_name):
+ """
+ This function is used to get the template path based on module name.
+ :param module_name:
+ :return:
+ """
+ template_path = None
+ if module_name == 'trigger':
+ template_path = self.trigger_template_path
+ elif module_name == 'index':
+ template_path = self.index_template_path
+ elif module_name == 'rule':
+ template_path = self.rules_template_path
+ elif module_name == 'compound_trigger':
+ template_path = self.compound_trigger_template_path
+
+ return template_path
+
+ def get_view_submodules_dependencies(self, **kwargs):
+ """
+ This function is used to get the dependencies of view and it's
+ submodules.
+ :param kwargs:
+ :return:
+ """
+ vid = kwargs['tid']
+ view_dependencies = []
+ view_deps = self.get_dependencies(self.conn, vid)
+ if len(view_deps) > 0:
+ view_dependencies.extend(view_deps)
+
+ # Iterate all the submodules of the table and fetch the dependencies.
+ for module in self.view_sub_modules:
+ module_view = SchemaDiffRegistry.get_node_view(module)
+ template_path = self.get_submodule_template_path(module)
+
+ SQL = render_template("/".join([template_path,
+ 'nodes.sql']), tid=vid)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=rset)
+
+ for row in rset['rows']:
+ result = module_view.get_dependencies(
+ self.conn, row['oid'], where=None,
+ show_system_objects=None, is_schema_diff=True)
+ if len(result) > 0:
+ view_dependencies.extend(result)
+
+ # Remove the same table from the dependency list
+ for item in view_dependencies:
+ if 'oid' in item and item['oid'] == vid:
+ view_dependencies.remove(item)
+
+ return view_dependencies
+
+
+# Override the operations for materialized view
+mview_operations = {
+ 'refresh_data': [{'put': 'refresh_data'}, {}],
+ 'check_utility_exists': [{'get': 'check_utility_exists'}, {}],
+ 'get_access_methods': [{}, {'get': 'get_access_methods'}],
+}
+mview_operations.update(ViewNode.operations)
+
+
+class MViewNode(ViewNode, VacuumSettings):
+ """
+ This class is responsible for generating routes for
+ materialized view node.
+
+ Methods:
+ -------
+ * __init__(**kwargs)
+ - Method is used to initialize the MView and it's base view.
+
+ * create(gid, sid, did, scid)
+ - Raise an error - we cannot create a material view.
+
+ * update(gid, sid, did, scid)
+ - This function will update the data for the selected material node
+
+ * delete(self, gid, sid, scid):
+ - Raise an error - we cannot delete a material view.
+
+ * getSQL(data, scid)
+ - This function will generate sql from model data
+
+ * refresh_data(gid, sid, did, scid, vid):
+ - This function will refresh view object
+ """
+ node_type = mview_blueprint.node_type
+ operations = mview_operations
+ TOAST_STR = 'toast.'
+ BASE_TEMPLATE_PATH = 'mviews/{0}/#{1}#'
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize the variables used by methods of ViewNode.
+ """
+
+ super().__init__(*args, **kwargs)
+
+ self.allowed_acls = []
+
+ @staticmethod
+ def ppas_template_path(ver):
+ """
+ Returns the template path for PPAS servers.
+ """
+ return 'ppas/#{0}#'.format(ver)
+
+ @staticmethod
+ def pg_template_path(ver):
+ """
+ Returns the template path for PostgreSQL servers.
+ """
+ return 'pg/#{0}#'.format(ver)
+
+ @staticmethod
+ def merge_to_vacuum_data(old_data, data, vacuum_key):
+ """
+ Used by getSQL method to merge vacuum data
+ """
+ if vacuum_key not in data:
+ return
+
+ if 'changed' not in data[vacuum_key]:
+ return
+
+ for item in data[vacuum_key]['changed']:
+ old_data_item_key = item['name']
+ if vacuum_key == 'vacuum_toast':
+ old_data_item_key = 'toast_' + item['name']
+ item['name'] = 'toast.' + item['name']
+
+ if 'value' not in item.keys():
+ continue
+ if item['value'] is None:
+ if old_data[old_data_item_key] != item['value']:
+ data['vacuum_data']['reset'].append(item)
+ elif old_data[old_data_item_key] is None or \
+ float(old_data[old_data_item_key]) != \
+ float(item['value']):
+ data['vacuum_data']['changed'].append(item)
+
+ def _getSQL_existing(self, did, data, vid):
+ """
+ Used by getSQL to get SQL for existing mview.
+ """
+ status, res = self._fetch_mview_properties(did, None, vid)
+
+ if not status:
+ return res
+
+ old_data = res
+
+ if 'name' not in data:
+ data['name'] = res['name']
+ if 'schema' not in data:
+ data['schema'] = res['schema']
+
+ # merge vacuum lists into one
+ data['vacuum_data'] = {}
+ data['vacuum_data']['changed'] = []
+ data['vacuum_data']['reset'] = []
+
+ # table vacuum: separate list of changed and reset data for
+ self.merge_to_vacuum_data(old_data, data, 'vacuum_table')
+ # table vacuum toast: separate list of changed and reset data for
+ self.merge_to_vacuum_data(old_data, data, 'vacuum_toast')
+
+ # Privileges
+ for aclcol in self.allowed_acls:
+ if aclcol in data:
+ allowedacl = self.allowed_acls[aclcol]
+
+ for key in ['added', 'changed', 'deleted']:
+ if key in data[aclcol]:
+ data[aclcol][key] = parse_priv_to_db(
+ data[aclcol][key], allowedacl['acl']
+ )
+
+ try:
+ SQL = render_template("/".join(
+ [self.template_path,
+ self._SQL_PREFIX + self._UPDATE_SQL]), data=data,
+ o_data=old_data, conn=self.conn)
+ except Exception as e:
+ current_app.logger.exception(e)
+ return None, internal_server_error(errormsg=str(e))
+
+ return SQL, old_data['name']
+
+ def _getSQL_new(self, data):
+ """
+ Used by getSQL to get SQL for new mview.
+ """
+ required_args = [
+ 'name',
+ 'schema',
+ 'definition'
+ ]
+ for arg in required_args:
+ if arg not in data:
+ return None, make_json_response(
+ data=gettext(" -- definition incomplete"),
+ status=200
+ )
+
+ # Get Schema Name from its OID.
+ if 'schema' in data and isinstance(data['schema'], int):
+ data['schema'] = self._get_schema(data['schema'])
+
+ # merge vacuum lists into one
+ vacuum_table = [item for item in data.get('vacuum_table', [])
+ if 'value' in item.keys() and
+ item['value'] is not None]
+ vacuum_toast = [
+ {'name': self.TOAST_STR + item['name'], 'value': item['value']}
+ for item in data.get('vacuum_toast', [])
+ if 'value' in item.keys() and item['value'] is not None]
+
+ # add vacuum_toast dict to vacuum_data
+ data['vacuum_data'] = []
+ if data.get('autovacuum_custom', False):
+ data['vacuum_data'] = vacuum_table
+
+ if data.get('toast_autovacuum', False):
+ data['vacuum_data'] += vacuum_toast
+
+ # Privileges
+ for aclcol in self.allowed_acls:
+ if aclcol in data:
+ allowedacl = self.allowed_acls[aclcol]
+ data[aclcol] = parse_priv_to_db(
+ data[aclcol], allowedacl['acl']
+ )
+
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._CREATE_SQL]),
+ data=data, conn=self.conn)
+ if data['definition']:
+ SQL += "\n"
+ SQL += render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=data)
+
+ return SQL, data.get('name', None)
+
+ def getSQL(self, gid, sid, did, data, vid=None):
+ """
+ This function will generate sql from model data
+ """
+ if vid is not None:
+ SQL, data_name = self._getSQL_existing(did, data, vid)
+ else:
+ SQL, data_name = self._getSQL_new(data)
+
+ return SQL, data_name
+
+ @check_precondition
+ def sql(self, gid, sid, did, scid, vid, **kwargs):
+ """
+ This function will generate sql to render into the sql panel
+ """
+ json_resp = kwargs.get('json_resp', True)
+
+ display_comments = True
+
+ if not json_resp:
+ display_comments = False
+
+ sql_data = ''
+ status, result = self._fetch_mview_properties(did, scid, vid)
+
+ if not status:
+ return result
+
+ # merge vacuum lists into one
+ vacuum_table = [item for item in result['vacuum_table']
+ if
+ 'value' in item.keys() and item['value'] is not None]
+ vacuum_toast = [
+ {'name': self.TOAST_STR + item['name'], 'value': item['value']}
+ for item in result['vacuum_toast'] if
+ 'value' in item.keys() and item['value'] is not None]
+
+ result['vacuum_data'] = vacuum_table + vacuum_toast
+
+ # Privileges
+ for aclcol in self.allowed_acls:
+ if aclcol in result:
+ allowedacl = self.allowed_acls[aclcol]
+ result[aclcol] = parse_priv_to_db(
+ result[aclcol], allowedacl['acl']
+ )
+
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._CREATE_SQL]),
+ data=result,
+ conn=self.conn,
+ display_comments=display_comments,
+ add_not_exists_clause=True
+ )
+ SQL += "\n"
+ SQL += render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._GRANT_SQL]),
+ data=result)
+
+ sql_data += SQL
+ sql_data += self.get_rule_sql(vid, display_comments)
+ sql_data += self.get_trigger_sql(vid, display_comments)
+ sql_data += self.get_index_sql(did, vid, display_comments)
+ sql_data = sql_data.strip('\n')
+
+ if not json_resp:
+ return sql_data
+ return ajax_response(response=sql_data)
+
+ @check_precondition
+ def get_table_vacuum(self, gid, sid, did, scid):
+ """
+ Fetch the default values for autovacuum
+ fields, return an array of
+ - label
+ - name
+ - setting
+ values
+ """
+
+ res = self.get_vacuum_table_settings(self.conn, sid)
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ @check_precondition
+ def get_toast_table_vacuum(self, gid, sid, did, scid):
+ """
+ Fetch the default values for autovacuum
+ fields, return an array of
+ - label
+ - name
+ - setting
+ values
+ """
+ res = self.get_vacuum_toast_settings(self.conn, sid)
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ @check_precondition
+ def properties(self, gid, sid, did, scid, vid):
+ """
+ Fetches the properties of an individual view
+ and render in the properties tab
+ """
+ status, res = self._fetch_mview_properties(did, scid, vid)
+
+ if not status:
+ return res
+
+ return ajax_response(
+ response=res,
+ status=200
+ )
+
+ def _fetch_mview_properties(self, did, scid, vid):
+ """
+ This function is used to fetch the properties of the specified object
+ :param did:
+ :param scid:
+ :param vid:
+ :return:
+ """
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._PROPERTIES_SQL]
+ ), did=did, vid=vid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ if len(res['rows']) == 0:
+ return False, gone(self.not_found_error_msg())
+
+ # Set value based on
+ # x: No set, t: true, f: false
+ res['rows'][0]['autovacuum_enabled'] = 'x' \
+ if res['rows'][0]['autovacuum_enabled'] is None else \
+ {True: 't', False: 'f'}[res['rows'][0]['autovacuum_enabled']]
+
+ res['rows'][0]['toast_autovacuum_enabled'] = 'x' \
+ if res['rows'][0]['toast_autovacuum_enabled'] is None else \
+ {True: 't', False: 'f'}[res['rows'][0]['toast_autovacuum_enabled']]
+
+ # Enable custom autovaccum only if one of the options is set
+ # or autovacuum is set
+ res['rows'][0]['autovacuum_custom'] = any([
+ res['rows'][0]['autovacuum_vacuum_threshold'],
+ res['rows'][0]['autovacuum_vacuum_scale_factor'],
+ res['rows'][0]['autovacuum_analyze_threshold'],
+ res['rows'][0]['autovacuum_analyze_scale_factor'],
+ res['rows'][0]['autovacuum_vacuum_cost_delay'],
+ res['rows'][0]['autovacuum_vacuum_cost_limit'],
+ res['rows'][0]['autovacuum_freeze_min_age'],
+ res['rows'][0]['autovacuum_freeze_max_age'],
+ res['rows'][0]['autovacuum_freeze_table_age']]) \
+ or res['rows'][0]['autovacuum_enabled'] in ('t', 'f')
+
+ res['rows'][0]['toast_autovacuum'] = any([
+ res['rows'][0]['toast_autovacuum_vacuum_threshold'],
+ res['rows'][0]['toast_autovacuum_vacuum_scale_factor'],
+ res['rows'][0]['toast_autovacuum_analyze_threshold'],
+ res['rows'][0]['toast_autovacuum_analyze_scale_factor'],
+ res['rows'][0]['toast_autovacuum_vacuum_cost_delay'],
+ res['rows'][0]['toast_autovacuum_vacuum_cost_limit'],
+ res['rows'][0]['toast_autovacuum_freeze_min_age'],
+ res['rows'][0]['toast_autovacuum_freeze_max_age'],
+ res['rows'][0]['toast_autovacuum_freeze_table_age']]) \
+ or res['rows'][0]['toast_autovacuum_enabled'] in ('t', 'f')
+
+ res['rows'][0]['vacuum_settings_str'] = ''
+
+ if res['rows'][0]['reloptions'] is not None:
+ res['rows'][0]['vacuum_settings_str'] += '\n'.\
+ join(res['rows'][0]['reloptions'])
+
+ if res['rows'][0]['toast_reloptions'] is not None:
+ res['rows'][0]['vacuum_settings_str'] += '\n' \
+ if res['rows'][0]['vacuum_settings_str'] != "" else ""
+ res['rows'][0]['vacuum_settings_str'] += '\n'.\
+ join(map(lambda o: self.TOAST_STR + o,
+ res['rows'][0]['toast_reloptions']))
+
+ res['rows'][0]['vacuum_settings_str'] = res['rows'][0][
+ 'vacuum_settings_str'
+ ].replace('=', ' = ')
+
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._ACL_SQL]), vid=vid)
+ status, dataclres = self.conn.execute_dict(SQL)
+ if not status:
+ return False, internal_server_error(errormsg=res)
+
+ for row in dataclres['rows']:
+ priv = parse_priv_from_db(row)
+ res['rows'][0].setdefault(row['deftype'], []).append(priv)
+
+ result = res['rows'][0]
+
+ # sending result to formtter
+ frmtd_reslt = self.formatter(result)
+
+ # merging formated result with main result again
+ result.update(frmtd_reslt)
+
+ result['vacuum_table'] = self.parse_vacuum_data(
+ self.conn, result, 'table')
+ result['vacuum_toast'] = self.parse_vacuum_data(
+ self.conn, result, 'toast')
+
+ return True, result
+
+ @check_precondition
+ def refresh_data(self, gid, sid, did, scid, vid):
+ """
+ This function will refresh view object
+ """
+
+ # Below will decide if it's refresh data or refresh concurrently
+ data = request.form if request.form else json.loads(
+ request.data
+ )
+
+ is_concurrent = data['concurrent']
+ with_data = data['with_data']
+ data = dict()
+ data['is_concurrent'] = is_concurrent
+ data['is_with_data'] = with_data
+ try:
+
+ # Fetch view name by view id
+ SQL = render_template("/".join(
+ [self.template_path, 'sql/get_view_name.sql']), vid=vid)
+ status, res = self.conn.execute_dict(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+ if len(res['rows']) == 0:
+ return gone(self.not_found_error_msg())
+
+ # Refresh view
+ SQL = render_template(
+ "/".join([self.template_path, 'sql/refresh.sql']),
+ name=res['rows'][0]['name'],
+ nspname=res['rows'][0]['schema'],
+ is_concurrent=is_concurrent,
+ with_data=with_data
+ )
+ data['object'] = "{0}.{1}".format(res['rows'][0]['schema'],
+ res['rows'][0]['name'])
+
+ # Fetch the server details like hostname, port, roles etc
+ server = Server.query.filter_by(
+ id=sid).first()
+
+ if server is None:
+ return make_json_response(
+ success=0,
+ errormsg=gettext("Could not find the given server")
+ )
+
+ # To fetch MetaData for the server
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ manager = driver.connection_manager(server.id)
+ conn = manager.connection()
+ connected = conn.connected()
+
+ if not connected:
+ return make_json_response(
+ success=0,
+ errormsg=gettext("Please connect to the server first.")
+ )
+ # Fetch the database name from connection manager
+ db_info = manager.db_info.get(did, None)
+ if db_info:
+ data['database'] = db_info['datname']
+ else:
+ return make_json_response(
+ success=0,
+ errormsg=gettext(
+ "Could not find the database on the server.")
+ )
+ utility = manager.utility('sql')
+ ret_val = does_utility_exist(utility)
+ if ret_val:
+ return make_json_response(
+ success=0,
+ errormsg=ret_val
+ )
+
+ args = [
+ '--host',
+ manager.local_bind_host if manager.use_ssh_tunnel
+ else server.host,
+ '--port',
+ str(manager.local_bind_port) if manager.use_ssh_tunnel
+ else str(server.port),
+ '--username', server.username, '--dbname',
+ data['database'],
+ '--command', SQL
+ ]
+
+ try:
+ p = BatchProcess(
+ desc=Message(sid, data, SQL),
+ cmd=utility, args=args, manager_obj=manager
+ )
+ p.set_env_variables(server)
+ p.start()
+ jid = p.id
+ except Exception as e:
+ current_app.logger.exception(e)
+ return make_json_response(
+ status=410,
+ success=0,
+ errormsg=str(e)
+ )
+ # Return response
+ return make_json_response(
+ data={
+ 'job_id': jid,
+ 'desc': p.desc.message,
+ 'status': True,
+ 'info': gettext(
+ 'Materialized view refresh job created.')
+ }
+ )
+ except Exception as e:
+ current_app.logger.exception(e)
+ return internal_server_error(errormsg=str(e))
+
+ @check_precondition
+ def fetch_objects_to_compare(self, sid, did, scid, oid=None):
+ """
+ This function will fetch the list of all the mviews for
+ specified schema id.
+
+ :param sid: Server Id
+ :param did: Database Id
+ :param scid: Schema Id
+ :return:
+ """
+ res = dict()
+ SQL = render_template("/".join(
+ [self.template_path, self._SQL_PREFIX + self._NODES_SQL]),
+ did=did, scid=scid, datlastsysoid=self._DATABASE_LAST_SYSTEM_OID,
+ schema_diff=True)
+ status, rset = self.conn.execute_2darray(SQL)
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ for row in rset['rows']:
+ status, data = self._fetch_mview_properties(did, scid, row['oid'])
+ if status:
+ # Fetch the data of sub module
+ self._get_sub_module_data_for_compare(
+ sid, did, scid, data, row['oid'])
+ res[row['name']] = data
+
+ return res
+
+ @check_precondition
+ def check_utility_exists(self, gid, sid, did, scid, vid):
+ """
+ This function checks the utility file exist on the given path.
+
+ Args:
+ sid: Server ID
+ Returns:
+ None
+ """
+ server = Server.query.filter_by(
+ id=sid, user_id=current_user.id
+ ).first()
+
+ if server is None:
+ return make_json_response(
+ success=0,
+ errormsg=gettext("Could not find the specified server.")
+ )
+
+ driver = get_driver(PG_DEFAULT_DRIVER)
+ manager = driver.connection_manager(server.id)
+
+ utility = manager.utility('sql')
+ ret_val = does_utility_exist(utility)
+ if ret_val:
+ return make_json_response(
+ success=0,
+ errormsg=ret_val
+ )
+
+ return make_json_response(success=1)
+
+ @check_precondition
+ def statistics(self, gid, sid, did, scid, vid=None):
+ """
+ Statistics
+
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ vid: View ID
+
+ Returns the statistics for a particular MView if vid is specified,
+ otherwise it will return statistics for all the MView in that
+ schema.
+ """
+ status, schema_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.template_path, 'sql/get_schema.sql']),
+ conn=self.conn, scid=scid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=schema_name)
+
+ if vid is None:
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path,
+ 'sql/coll_mview_stats.sql']), conn=self.conn,
+ schema_name=schema_name
+ )
+ )
+ else:
+ # For Individual mview stats
+
+ # Check if pgstattuple extension is already created?
+ # if created then only add extended stats
+ status, is_pgstattuple = self.conn.execute_scalar("""
+ SELECT (count(extname) > 0) AS is_pgstattuple
+ FROM pg_catalog.pg_extension
+ WHERE extname='pgstattuple'
+ """)
+ if not status:
+ return internal_server_error(errormsg=is_pgstattuple)
+
+ # Fetch MView name
+ status, mview_name = self.conn.execute_scalar(
+ render_template(
+ "/".join([self.template_path, 'sql/get_view_name.sql']),
+ conn=self.conn, scid=scid, vid=vid
+ )
+ )
+ if not status:
+ return internal_server_error(errormsg=mview_name)
+
+ status, res = self.conn.execute_dict(
+ render_template(
+ "/".join([self.template_path, 'sql/stats.sql']),
+ conn=self.conn, schema_name=schema_name,
+ mview_name=mview_name,
+ is_pgstattuple=is_pgstattuple, vid=vid
+ )
+ )
+
+ if not status:
+ return internal_server_error(errormsg=res)
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+ @check_precondition
+ def get_access_methods(self, gid, sid, did, scid, vid=None):
+ """
+ Args:
+ gid: Server Group ID
+ sid: Server ID
+ did: Database ID
+ scid: Schema ID
+ vid: View ID
+
+ Returns the access method to be used by mview
+ """
+ res = []
+ sql = render_template("/".join([self.template_path,
+ 'sql/get_access_methods.sql']))
+ status, rest = self.conn.execute_2darray(sql)
+ if not status:
+ return internal_server_error(errormsg=rest)
+
+ for row in rest['rows']:
+ res.append(
+ {'label': row['amname'], 'value': row['amname']}
+ )
+
+ return make_json_response(
+ data=res,
+ status=200
+ )
+
+
+SchemaDiffRegistry(view_blueprint.node_type, ViewNode)
+ViewNode.register_node_view(view_blueprint)
+SchemaDiffRegistry(mview_blueprint.node_type, MViewNode)
+MViewNode.register_node_view(mview_blueprint)
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/children/__init__.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/children/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0f13e21f0d6815e12408358fe6657ac678245da
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/children/__init__.py
@@ -0,0 +1,17 @@
+"""
+We will use the existing modules for creating children module under
+materialize views.
+
+Do not remove these imports as they will be automatically imported by the view
+module as its children
+"""
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.columns \
+ import blueprint as columns_module
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.indexes \
+ import blueprint as indexes_modules
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.triggers \
+ import blueprint as triggers_modules
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.rules \
+ import blueprint as rules_modules
+from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
+ compound_triggers import blueprint as compound_trigger_modules
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/schema_diff_view_utils.py b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/schema_diff_view_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d55e9fa90b2e072af04aed64d0325ac0e187afe1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/schema_diff_view_utils.py
@@ -0,0 +1,238 @@
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+""" Implements Utility class for View."""
+
+import copy
+
+from pgadmin.utils.ajax import internal_server_error
+from pgadmin.tools.schema_diff.directory_compare import compare_dictionaries,\
+ are_dictionaries_identical
+from pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare
+from pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry
+
+
+class SchemaDiffViewCompare(SchemaDiffObjectCompare):
+ view_keys_to_ignore = ['oid', 'schema', 'xmin', 'oid-2', 'setting']
+
+ trigger_keys_to_ignore = ['xmin', 'tgrelid', 'tgfoid', 'tfunction',
+ 'tgqual', 'tgconstraint', 'nspname']
+
+ keys_to_ignore = view_keys_to_ignore + trigger_keys_to_ignore
+
+ def compare(self, **kwargs):
+ """
+ This function is used to compare all the table objects
+ from two different schemas.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = {'sid': kwargs.get('source_sid'),
+ 'did': kwargs.get('source_did'),
+ 'scid': kwargs.get('source_scid')}
+ target_params = {'sid': kwargs.get('target_sid'),
+ 'did': kwargs.get('target_did'),
+ 'scid': kwargs.get('target_scid')}
+ ignore_owner = kwargs.get('ignore_owner')
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+ ignore_tablespace = kwargs.get('ignore_tablespace')
+ ignore_grants = kwargs.get('ignore_grants')
+
+ group_name = kwargs.get('group_name')
+ source_schema_name = kwargs.get('source_schema_name', None)
+ source_views = {}
+ target_views = {}
+
+ status, target_schema = self.get_schema(**target_params)
+ if not status:
+ return internal_server_error(errormsg=target_schema)
+
+ if 'scid' in source_params and source_params['scid'] is not None:
+ source_views = self.fetch_objects_to_compare(**source_params)
+
+ if 'scid' in target_params and target_params['scid'] is not None:
+ target_views = self.fetch_objects_to_compare(**target_params)
+
+ # If both the dict have no items then return None.
+ if not (source_views or target_views) or (
+ len(source_views) <= 0 and len(target_views) <= 0):
+ return None
+
+ return compare_dictionaries(view_object=self,
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source_dict=source_views,
+ target_dict=target_views,
+ node=self.node_type,
+ node_label=self.blueprint.collection_label,
+ group_name=group_name,
+ ignore_keys=self.keys_to_ignore,
+ source_schema_name=source_schema_name,
+ ignore_owner=ignore_owner,
+ ignore_whitespaces=ignore_whitespaces,
+ ignore_tablespace=ignore_tablespace,
+ ignore_grants=ignore_grants)
+
+ def ddl_compare(self, **kwargs):
+ """
+ This function will compare properties of 2 views and
+ return the source DDL, target DDL and Difference of them.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = {'sid': kwargs.get('source_sid'),
+ 'did': kwargs.get('source_did'),
+ 'scid': kwargs.get('source_scid'),
+ 'tid': kwargs.get('source_oid')
+ }
+
+ target_params = {'sid': kwargs.get('target_sid'),
+ 'did': kwargs.get('target_did'),
+ 'scid': kwargs.get('target_scid'),
+ 'tid': kwargs.get('target_oid')
+ }
+
+ source = self.get_sql_from_view_diff(**source_params)
+ target = self.get_sql_from_view_diff(**target_params)
+
+ return {'source_ddl': source,
+ 'target_ddl': target,
+ 'diff_ddl': ''
+ }
+
+ def get_sql_from_submodule_diff(self, **kwargs):
+ """
+ This function returns the DDL/DML statements of the
+ submodules of table based on the comparison status.
+
+ :param kwargs:
+ :return:
+ """
+ source_params = kwargs.get('source_params')
+ target_params = kwargs.get('target_params')
+ target_schema = kwargs.get('target_schema')
+ source = kwargs.get('source')
+ target = kwargs.get('target')
+ diff_dict = kwargs.get('diff_dict')
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+ diff = ''
+
+ # Get the difference DDL/DML statements for table
+ if isinstance(diff_dict, dict) and len(diff_dict) > 0:
+ target_params['diff_data'] = diff_dict
+ diff = self.get_sql_from_view_diff(**target_params)
+
+ ignore_sub_modules = ['column']
+ if self.manager.server_type == 'pg' or self.manager.version < 120000:
+ ignore_sub_modules.append('compound_trigger')
+
+ # Iterate through all the sub modules of the table
+ for module in self.blueprint.submodules:
+ if module.node_type not in ignore_sub_modules:
+ module_view = \
+ SchemaDiffRegistry.get_node_view(module.node_type)
+
+ dict1 = copy.deepcopy(source[module.node_type])
+ dict2 = copy.deepcopy(target[module.node_type])
+
+ # Find the duplicate keys in both the dictionaries
+ dict1_keys = set(dict1.keys())
+ dict2_keys = set(dict2.keys())
+ intersect_keys = dict1_keys.intersection(dict2_keys)
+
+ # Keys that are available in source and missing in target.
+ added = dict1_keys - dict2_keys
+ diff = SchemaDiffViewCompare._compare_source_only(
+ added, module_view, source_params, target_params,
+ dict1, diff, target_schema)
+
+ # Keys that are available in target and missing in source.
+ removed = dict2_keys - dict1_keys
+ diff = SchemaDiffViewCompare._compare_target_only(
+ removed, module_view, source_params, target_params,
+ dict2, diff, target_schema)
+
+ # Keys that are available in both source and target.
+ other_param = {
+ "dict1": dict1,
+ "dict2": dict2,
+ "source": source,
+ "target": target,
+ "target_schema": target_schema,
+ "ignore_whitespaces": ignore_whitespaces
+ }
+ diff = self._compare_source_and_target(
+ intersect_keys, module_view, source_params,
+ target_params, diff, **other_param)
+
+ return diff
+
+ @staticmethod
+ def _compare_source_only(added, module_view, source_params, target_params,
+ dict1, diff, target_schema):
+ for item in added:
+ source_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=dict1[item],
+ target=None,
+ comp_status='source_only'
+ )
+
+ diff += '\n' + source_ddl
+ return diff
+
+ @staticmethod
+ def _compare_target_only(removed, module_view, source_params,
+ target_params, dict2, diff, target_schema):
+ for item in removed:
+ target_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=None,
+ target=dict2[item],
+ comp_status='target_only'
+ )
+
+ diff += '\n' + target_ddl
+ return diff
+
+ def _compare_source_and_target(self, intersect_keys, module_view,
+ source_params, target_params, diff,
+ **kwargs):
+ dict1 = kwargs['dict1']
+ dict2 = kwargs['dict2']
+ source = kwargs['source']
+ target = kwargs['target']
+ target_schema = kwargs['target_schema']
+ ignore_whitespaces = kwargs.get('ignore_whitespaces')
+
+ for key in intersect_keys:
+ # Recursively Compare the two dictionary
+ if not are_dictionaries_identical(
+ dict1[key], dict2[key], self.keys_to_ignore,
+ ignore_whitespaces):
+ diff_ddl = module_view.ddl_compare(
+ source_params=source_params,
+ target_params=target_params,
+ target_schema=target_schema,
+ source=dict1[key],
+ target=dict2[key],
+ comp_status='different',
+ parent_source_data=source,
+ parent_target_data=target
+ )
+
+ diff += '\n' + diff_ddl
+ return diff
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/css/view.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/css/view.css
new file mode 100644
index 0000000000000000000000000000000000000000..c9c46d9fb2a835ba06652daaffb5d0f1407b4ecf
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/css/view.css
@@ -0,0 +1,7 @@
+.sql_field_height_140 {
+ height: 140px;
+}
+
+.sql_field_width_full {
+ width: 100%;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-mview.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-mview.svg
new file mode 100644
index 0000000000000000000000000000000000000000..e2a8add9e559cb51f37f76ff641df06756cbc797
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-mview.svg
@@ -0,0 +1 @@
+coll-mview
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-view.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-view.svg
new file mode 100644
index 0000000000000000000000000000000000000000..62c70e9b151d3c1356a6fbcb5114afe0303f78d5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/coll-view.svg
@@ -0,0 +1 @@
+coll-view
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/mview.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/mview.svg
new file mode 100644
index 0000000000000000000000000000000000000000..7e901be86265992111513def8334367365198336
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/mview.svg
@@ -0,0 +1 @@
+mview
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/view.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/view.svg
new file mode 100644
index 0000000000000000000000000000000000000000..4c63b1cc79429131855d37f1fef4a2b3c189c3b7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/img/view.svg
@@ -0,0 +1 @@
+view
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.js
new file mode 100644
index 0000000000000000000000000000000000000000..e07dbd5f2380372fa0b4404a25d1e1ac419efefa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.js
@@ -0,0 +1,241 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import MViewSchema from './mview.ui';
+import { getNodeListByName, getNodeAjaxOptions } from '../../../../../../../static/js/node_ajax';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import { getNodeVacuumSettingsSchema } from '../../../../../static/js/vacuum.ui';
+import _ from 'lodash';
+import getApiInstance from '../../../../../../../../static/js/api_instance';
+
+define('pgadmin.node.mview', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child',
+ 'pgadmin.node.schema.dir/schema_child_tree_node', 'sources/utils',
+], function(
+ gettext, url_for, pgAdmin, pgBrowser,
+ schemaChild, schemaChildTreeNode, commonUtils
+) {
+
+ /**
+ Create and add a view collection into nodes
+ @param {variable} label - Label for Node
+ @param {variable} type - Type of Node
+ @param {variable} columns - List of columns to
+ display under under properties.
+ */
+ if (!pgBrowser.Nodes['coll-mview']) {
+ pgBrowser.Nodes['coll-mview'] =
+ pgBrowser.Collection.extend({
+ node: 'mview',
+ label: gettext('Materialized Views'),
+ type: 'coll-mview',
+ columns: ['name', 'owner', 'comment'],
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Total Size')],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ /**
+ Create and Add a View Node into nodes
+ @param {variable} parent_type - The list of nodes
+ under which this node to display
+ @param {variable} type - Type of Node
+ @param {variable} hasSQL - To show SQL tab
+ @param {variable} canDrop - Adds drop view option
+ in the context menu
+ @param {variable} canDropCascade - Adds drop Cascade
+ view option in the context menu
+ */
+ if (!pgBrowser.Nodes['mview']) {
+ pgBrowser.Nodes['mview'] = schemaChild.SchemaChildNode.extend({
+ type: 'mview',
+ sqlAlterHelp: 'sql-altermaterializedview.html',
+ sqlCreateHelp: 'sql-creatematerializedview.html',
+ dialogHelp: url_for('help.static', {'filename': 'materialized_view_dialog.html'}),
+ label: gettext('Materialized View'),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Total Size'), gettext('Indexes size'), gettext('Table size'),
+ gettext('TOAST table size'), gettext('Tuple length'),
+ gettext('Dead tuple length'), gettext('Free space')],
+ hasScriptTypes: ['create', 'select'],
+ collection_type: 'coll-mview',
+ width: pgBrowser.stdW.md + 'px',
+ Init: function() {
+
+ // Avoid mulitple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ /**
+ Add "create view" menu option into context and object menu
+ for the following nodes:
+ coll-mview, view and schema.
+ @property {data} - Allow create view option on schema node or
+ system view nodes.
+ */
+ pgAdmin.Browser.add_menu_category(
+ 'refresh_mview', gettext('Refresh View'), 18, '');
+ pgBrowser.add_menus([{
+ name: 'create_mview_on_coll', node: 'coll-mview', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1,
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ label: gettext('Materialized View...'),
+ },{
+ name: 'create_mview', node: 'mview', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1,
+ data: {action: 'create', check: true}, enable: 'canCreate',
+ label: gettext('Materialized View...'),
+ },{
+ name: 'create_mview', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 18,
+ data: {action: 'create', check: false}, enable: 'canCreate',
+ label: gettext('Materialized View...'),
+ },{
+ name: 'refresh_mview_data', node: 'mview', module: this,
+ priority: 1, callback: 'refresh_mview', category: 'refresh_mview',
+ applies: ['object', 'context'], label: gettext('With data'),
+ data: {concurrent: false, with_data: true},
+ },{
+ name: 'refresh_mview_nodata', node: 'mview',
+ callback: 'refresh_mview', priority: 2, module: this,
+ category: 'refresh_mview', applies: ['object', 'context'],
+ label: gettext('With no data'), data: {
+ concurrent: false, with_data: false,
+ },
+ },{
+ name: 'refresh_mview_concurrent', node: 'mview', module: this,
+ category: 'refresh_mview', enable: 'is_version_supported',
+ data: {concurrent: true, with_data: true}, priority: 3,
+ applies: ['object', 'context'], callback: 'refresh_mview',
+ label: gettext('With data (concurrently)'),
+ },{
+ name: 'refresh_mview_concurrent_nodata', node: 'mview', module: this,
+ category: 'refresh_mview', enable: 'is_version_supported',
+ data: {concurrent: true, with_data: false}, priority: 4,
+ applies: ['object', 'context'], callback: 'refresh_mview',
+ label: gettext('With no data (concurrently)'),
+ }]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new MViewSchema(
+ (privileges)=>getNodePrivilegeRoleSchema('', treeNodeInfo, itemNodeData, privileges),
+ ()=>getNodeVacuumSettingsSchema(this, treeNodeInfo, itemNodeData),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {cacheLevel: 'database'}),
+ spcname: ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=> {
+ return (m.label != 'pg_global');
+ }),
+ table_amname_list: ()=>getNodeAjaxOptions('get_access_methods', this, treeNodeInfo, itemNodeData),
+ nodeInfo: treeNodeInfo,
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: ('schema' in treeNodeInfo)? treeNodeInfo.schema.label : ''
+ }
+ );
+ },
+
+ refresh_mview: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined,
+ server_data = null;
+
+ if (!d)
+ return false;
+
+ let j = i;
+ while (j) {
+ let node_data = pgBrowser.tree.itemData(j);
+ if (node_data._type == 'server') {
+ server_data = node_data;
+ break;
+ }
+
+ if (pgBrowser.tree.hasParent(j)) {
+ j = pgBrowser.tree.parent(j);
+ } else {
+ pgAdmin.Browser.notifier.alert(gettext('Please select server or child node from tree.'));
+ break;
+ }
+ }
+
+ if (!server_data) {
+ return;
+ }
+
+ if (!commonUtils.hasBinariesConfiguration(pgBrowser, server_data)) {
+ return;
+ }
+
+ const api = getApiInstance();
+ api.get(obj.generate_url(i, 'check_utility_exists' , d, true))
+ .then(({data: res})=>{
+ if (!res.success) {
+ pgAdmin.Browser.notifier.alert(
+ gettext('Utility not found'),
+ res.errormsg
+ );
+ return;
+ }
+
+ api.put(obj.generate_url(i, 'refresh_data' , d, true), {'concurrent': args.concurrent, 'with_data': args.with_data})
+ .then(({data: refreshed_res})=>{
+ if (refreshed_res.data?.status) {
+ //Do nothing as we are creating the job and exiting from the main dialog
+ pgBrowser.BgProcessManager.startProcess(refreshed_res.data.job_id, refreshed_res.data.desc);
+ } else {
+ pgAdmin.Browser.notifier.alert(
+ gettext('Failed to create materialized view refresh job.'),
+ refreshed_res.errormsg
+ );
+ }
+ })
+ .catch((error)=>{
+ pgAdmin.Browser.notifier.pgRespErrorNotify(
+ error, gettext('Failed to create materialized view refresh job.')
+ );
+ });
+ })
+ .catch(()=>{
+ pgAdmin.Browser.notifier.alert(
+ gettext('Utility not found'),
+ gettext('Failed to fetch Utility information')
+ );
+ });
+ },
+
+ is_version_supported: function(data, item) {
+ let t = pgAdmin.Browser.tree,
+ i = item || t.selected(),
+ info = t?.getTreeNodeHierarchy(i),
+ version = _.isUndefined(info) ? 0 : info.server.version;
+
+ // disable refresh concurrently if server version is 9.3
+ return (version >= 90400);
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['mview'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..96d477ecad1eaae3144eb337884d39368e161ea0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/mview.ui.js
@@ -0,0 +1,170 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import { isEmptyString } from 'sources/validators';
+
+
+export default class MViewSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, getVacuumSettingsSchema, fieldOptions={}, initValues={}) {
+ super({
+ spcname: undefined,
+ toast_autovacuum_enabled: 'x',
+ autovacuum_enabled: 'x',
+ warn_text: undefined,
+ amname: undefined,
+ ...initValues
+ });
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.getVacuumSettingsSchema = getVacuumSettingsSchema;
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ spcname: [],
+ nodeInfo: null,
+ amname: [],
+ ...fieldOptions,
+ };
+
+ this.nodeInfo = this.fieldOptions.nodeInfo;
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', disabled: obj.inCatalog(), noEmpty: true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'owner', label: gettext('Owner'),
+ type: 'select', cell: 'text',
+ options: obj.fieldOptions.role, controlProps: { allowClear: false },
+ disabled: obj.inCatalog(),
+ },{
+ id: 'schema', label: gettext('Schema'), cell: 'text',
+ type: 'select', options: obj.fieldOptions.schema, mode: ['create', 'edit'],
+ cache_node: 'database', disabled: obj.inCatalog(),
+ controlProps: {
+ allowClear: false,
+ first_empty: false
+ },
+ },{
+ id: 'system_view', label: gettext('System materialized view?'), cell: 'text',
+ type: 'switch', mode: ['properties'],
+ },
+ {
+ id: 'acl', label: gettext('Privileges'),
+ mode: ['properties'], type: 'text', group: gettext('Security'),
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'text',
+ type: 'multiline',
+ },{
+ id: 'with_data', label: gettext('With data?'),
+ group: gettext('Definition'), mode: ['edit', 'create'],
+ type: 'switch',
+ },{
+ id: 'spcname', label: gettext('Tablespace'), cell: 'text',
+ type: 'select', group: gettext('Definition'),
+ options: obj.fieldOptions.spcname,
+ controlProps: {
+ allowClear: false,
+ first_empty: false,
+ },
+ }, {
+ id: 'amname', label: gettext('Access Method'), group: gettext('Definition'),
+ type: (state)=>{
+ return {
+ type: 'select', options: obj.fieldOptions.table_amname_list,
+ controlProps: {
+ allowClear: obj.isNew(state),
+ }
+ };
+ }, mode: ['create', 'properties', 'edit'], min_version: 120000,
+ disabled: (state) => {
+ if (obj.getServerVersion() < 150000 && !obj.isNew(state)) {
+ return true;
+ }
+ },
+ },{
+ id: 'fillfactor', label: gettext('Fill factor'),
+ group: gettext('Definition'), mode: ['edit', 'create'],
+ noEmpty: false, type: 'int', controlProps: {min: 10, max: 100}
+ },{
+ id: 'vacuum_settings_str', label: gettext('Storage settings'),
+ type: 'multiline', group: gettext('Definition'), mode: ['properties'],
+ },{
+ id: 'definition', label: gettext('Definition'), cell: 'text',
+ type: 'sql', mode: ['create', 'edit'], group: gettext('Code'),
+ isFullTab: true, controlProps: { readOnly: this.nodeInfo && 'catalog' in this.nodeInfo },
+ },
+ {
+ type: 'nested-tab', group: gettext('Parameter'), mode: ['create', 'edit'],
+ schema: this.getVacuumSettingsSchema(),
+ },
+ {
+ id: 'datacl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['a', 'r', 'w', 'd', 'D', 'x', 't']),
+ uniqueCol : ['grantee'],
+ editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ },
+ {
+ // Add Security Labels Control
+ id: 'seclabels', label: gettext('Security labels'),
+ schema: new SecLabelSchema(),
+ editable: false, type: 'collection',
+ canEdit: false, group: gettext('Security'), canDelete: true,
+ mode: ['edit', 'create'], canAdd: true,
+ control: 'unique-col-collection',
+ uniqueCol : ['provider'],
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+ let obj = this;
+
+ if (isEmptyString(state.service)) {
+
+ /* mview definition validation*/
+ if (isEmptyString(state.definition)) {
+ errmsg = gettext('Please enter view code.');
+ setError('definition', errmsg);
+ return true;
+ } else {
+ setError('definition', null);
+ }
+
+ if (state.definition) {
+ obj.warningText = null;
+ if (obj.origData.oid !== undefined && state.definition !== obj.origData.definition) {
+ obj.warningText = gettext(
+ 'Updating the definition will drop and re-create the materialized view. It may result in loss of information about its dependent objects.'
+ ) + '' + gettext('Do you want to continue?') + ' ';
+ }
+ }
+ return false;
+ } else {
+ _.each(['definition'], (item) => {
+ setError(item, null);
+ });
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.js
new file mode 100644
index 0000000000000000000000000000000000000000..7929e2bf15c4fb2f11df88d927ed5f1f014fb1a6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.js
@@ -0,0 +1,114 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeListByName } from '../../../../../../../static/js/node_ajax';
+import { getNodePrivilegeRoleSchema } from '../../../../../static/js/privilege.ui';
+import ViewSchema from './view.ui';
+
+define('pgadmin.node.view', [
+ 'sources/gettext', 'sources/url_for', 'pgadmin.browser',
+ 'pgadmin.node.schema.dir/child', 'pgadmin.node.schema.dir/schema_child_tree_node',
+ 'pgadmin.node.rule',
+], function(
+ gettext, url_for, pgBrowser, schemaChild, schemaChildTreeNode
+) {
+
+
+ /**
+ Create and add a view collection into nodes
+ @param {variable} label - Label for Node
+ @param {variable} type - Type of Node
+ @param {variable} columns - List of columns to
+ display under under properties.
+ */
+ if (!pgBrowser.Nodes['coll-view']) {
+ pgBrowser.Nodes['coll-view'] =
+ pgBrowser.Collection.extend({
+ node: 'view',
+ label: gettext('Views'),
+ type: 'coll-view',
+ columns: ['name', 'owner', 'comment'],
+ canDrop: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ canDropCascade: schemaChildTreeNode.isTreeItemOfChildOfSchema,
+ });
+ }
+
+ /**
+ Create and Add a View Node into nodes
+ @param {variable} parent_type - The list of nodes
+ under which this node to display
+ @param {variable} type - Type of Node
+ @param {variable} hasSQL - To show SQL tab
+ */
+ if (!pgBrowser.Nodes['view']) {
+ pgBrowser.Nodes['view'] = schemaChild.SchemaChildNode.extend({
+ type: 'view',
+ sqlAlterHelp: 'sql-alterview.html',
+ sqlCreateHelp: 'sql-createview.html',
+ dialogHelp: url_for('help.static', {'filename': 'view_dialog.html'}),
+ label: gettext('View'),
+ hasSQL: true,
+ hasDepends: true,
+ hasScriptTypes: ['create', 'select', 'insert'],
+ collection_type: 'coll-view',
+ Init: function() {
+
+ // Avoid mulitple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ /**
+ Add "create view" menu option into context and object menu
+ for the following nodes:
+ coll-view, view and schema.
+ @property {data} - Allow create view option on schema node or
+ system view nodes.
+ */
+ pgBrowser.add_menus([{
+ name: 'create_view_on_coll', node: 'coll-view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('View...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_view', node: 'view', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 1, label: gettext('View...'),
+ data: {action: 'create', check: true},
+ enable: 'canCreate',
+ },{
+ name: 'create_view', node: 'schema', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 17, label: gettext('View...'),
+ data: {action: 'create', check: false},
+ enable: 'canCreate',
+ },
+ ]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ return new ViewSchema(
+ (privileges)=>getNodePrivilegeRoleSchema('', treeNodeInfo, itemNodeData, privileges),
+ treeNodeInfo,
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ schema: ()=>getNodeListByName('schema', treeNodeInfo, itemNodeData, {cacheLevel: 'database'}),
+ },
+ {
+ owner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ schema: treeNodeInfo.schema ? treeNodeInfo.schema.label : ''
+ }
+ );
+ },
+ });
+ }
+
+ return pgBrowser.Nodes['view'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..7885792d0dd92fad8872847ea9c4357c59a4ca12
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/static/js/view.ui.js
@@ -0,0 +1,180 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../../../static/js/sec_label.ui';
+import { isEmptyString } from 'sources/validators';
+
+
+export default class ViewSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema, nodeInfo, fieldOptions={}, initValues={}) {
+ super({
+ owner: undefined,
+ schema: undefined,
+ ...initValues
+ });
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.nodeInfo = nodeInfo;
+ this.warningText = null;
+ this.fieldOptions = {
+ role: [],
+ schema: [],
+ ...fieldOptions,
+ };
+
+ }
+
+ get idAttribute() {
+ return 'oid';
+ }
+
+ notInSchema() {
+ return this.nodeInfo && 'catalog' in this.nodeInfo;
+ }
+
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), cell: 'text',
+ type: 'text', disabled: obj.notInSchema, noEmpty: true,
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'text',
+ type: 'text', mode: ['properties'],
+ },{
+ id: 'owner', label: gettext('Owner'), cell: 'text',
+ node: 'role', disabled: obj.notInSchema,
+ type: 'select', controlProps: { allowClear: false },
+ options: obj.fieldOptions.role
+ },{
+ id: 'schema', label: gettext('Schema'), cell: 'text',
+ type: 'select', disabled: obj.notInSchema, mode: ['create', 'edit'],
+ controlProps: {
+ allowClear: false,
+ first_empty: false,
+ },
+ options: obj.fieldOptions.schema
+ },{
+ id: 'system_view', label: gettext('System view?'), cell: 'text',
+ type: 'switch', mode: ['properties'],
+ },{
+ id: 'acl', label: gettext('Privileges'),
+ mode: ['properties'], type: 'text', group: gettext('Security'),
+ },{
+ id: 'comment', label: gettext('Comment'), cell: 'text',
+ type: 'multiline', disabled: obj.notInSchema,
+ },{
+ id: 'security_barrier', label: gettext('Security barrier?'),
+ type: 'switch', min_version: '90200', group: gettext('Definition'),
+ disabled: obj.notInSchema,
+ },{
+ id: 'security_invoker', label: gettext('Security invoker?'),
+ type: 'switch', min_version: '150000', group: gettext('Definition'),
+ disabled: obj.notInSchema,
+ },{
+ id: 'check_option', label: gettext('Check options'),
+ type: 'select', group: gettext('Definition'),
+ min_version: '90400', mode:['properties', 'create', 'edit'],
+ controlProps: {
+ // Set select2 option width to 100%
+ allowClear: false,
+ }, disabled: obj.notInSchema,
+ options:[{
+ label: gettext('No'), value: 'no',
+ },{
+ label: gettext('Local'), value: 'local',
+ },{
+ label: gettext('Cascaded'), value: 'cascaded',
+ }],
+ },{
+ id: 'definition', label: gettext('Code'), cell: 'text',
+ type: 'sql', mode: ['create', 'edit'], group: gettext('Code'),
+ isFullTab: true,
+ controlProps: { readOnly: obj.nodeInfo && 'catalog' in obj.nodeInfo },
+ },
+
+ {
+ id: 'datacl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['a', 'r', 'w', 'd', 'D', 'x', 't']),
+ uniqueCol : ['grantee'],
+ editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ },
+ {
+ // Add Security Labels Control
+ id: 'seclabels', label: gettext('Security labels'),
+ schema: new SecLabelSchema(),
+ editable: false, type: 'collection',
+ canEdit: false, group: gettext('Security'), canDelete: true,
+ mode: ['edit', 'create'], canAdd: true,
+ uniqueCol : ['provider'],
+ }
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+ let obj = this;
+ if (isEmptyString(state.service)) {
+
+ /* view definition validation*/
+ if (isEmptyString(state.definition)) {
+ errmsg = gettext('Please enter view code.');
+ setError('definition', errmsg);
+ return true;
+ } else {
+ setError('definition', null);
+ }
+
+ if (state.definition) {
+ if (!(obj.nodeInfo.server.server_type == 'pg' &&
+ // No need to check this when creating a view
+ obj.origData.oid !== undefined
+ ) || (
+ state.definition === obj.origData.definition
+ )) {
+ obj.warningText = null;
+ return false;
+ }
+
+ let old_def = obj.origData.definition?.replace(
+ /\s/gi, ''
+ ).split('FROM'),
+ new_def = [];
+
+ if (state.definition !== undefined) {
+ new_def = state.definition.replace(
+ /\s/gi, ''
+ ).split('FROM');
+ }
+
+ if ((old_def.length != new_def.length) || (
+ old_def.length > 1 && (
+ old_def[0] != new_def[0]
+ )
+ )) {
+ obj.warningText = gettext(
+ 'Changing the columns in a view requires dropping and re-creating the view. This may fail if other objects are dependent upon this view, or may cause procedural functions to fail if they are not modified to take account of the changes.'
+ ) + '' + gettext('Do you wish to continue?') +
+ ' ';
+ } else {
+ obj.warningText = null;
+ }
+ return false;
+ }
+
+ } else {
+ _.each(['definition'], (item) => {
+ setError(item, null);
+ });
+ }
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/css/mview.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/css/mview.css
new file mode 100644
index 0000000000000000000000000000000000000000..06c0c1b1470a08d5fb2f20fdaef7100a4e930f37
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/css/mview.css
@@ -0,0 +1,9 @@
+.icon-mview{
+ background-image: url('{{ url_for('NODE-mview.static', filename='img/mview.svg') }}') !important;
+ border-radius: 10px;
+ background-size: 20px !important;
+ background-repeat: no-repeat;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f05f828ce59ef83b1af5cf6a6b37dff8185c1c58
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create.sql
@@ -0,0 +1,50 @@
+{# ===================== Create new view ===================== #}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE MATERIALIZED VIEW{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if data.default_amname and data.default_amname != data.amname %}
+USING {{data.amname}}
+{% elif not data.default_amname and data.amname %}
+USING {{data.amname}}
+{% endif %}
+{% if(data.fillfactor or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') or data['vacuum_data']|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% for field in data['vacuum_data'] %}
+{% if field.value is defined and field.value != '' and field.value != none %}
+{% if ns.add_comma %},
+{% endif %} {{ field.name }} = {{ field.value|lower }}{% set ns.add_comma = true%}{% endif %}{% endfor %}
+{{ '\n' }})
+{% endif %}
+{% if data.spcname %}TABLESPACE {{ data.spcname }}
+{% endif %}AS
+{{ data.definition.rstrip(';') }}
+{% if data.with_data %}
+WITH DATA;
+{% else %}
+WITH NO DATA;
+{% endif %}
+{% if data.owner %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create_access_method.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create_access_method.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e5505b2e0f391824b74ebb096d7de872d7b328d4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/create_access_method.sql
@@ -0,0 +1,3 @@
+CREATE ACCESS METHOD {{ data.name }}
+ TYPE {{ data.type }}
+ HANDLER {{ data.handler }}
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/get_access_methods.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/get_access_methods.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2a93232bfa64b16dcd90042a49e97b7c7c7d0f83
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/get_access_methods.sql
@@ -0,0 +1,3 @@
+-- Fetches access methods
+SELECT oid, amname
+FROM pg_catalog.pg_am WHERE amtype = 't';
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..96f4fda4abc08cb56c2c2300984bb2d03de4c225
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/properties.sql
@@ -0,0 +1,112 @@
+{# ========================== Fetch Materialized View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ c.relispopulated AS with_data,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ (SELECT st.setting from pg_catalog.pg_settings st
+ WHERE st.name = 'default_table_access_method') as default_amname,
+ c.relacl,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ description AS comment,
+ pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
+ {# ============= Checks if it is system view ================ #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ c.reloptions AS reloptions, tst.reloptions AS toast_reloptions, am.amname,
+ (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
+FROM
+ pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
+LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = c.relam
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'm'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4ce4a7f9b704a38dba2cc853f5358c69b2a301d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/12_plus/sql/update.sql
@@ -0,0 +1,207 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.amname and data.amname != o_data.amname %}
+USING {{ data.amname }}
+{% endif %}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcname and o_data.spcname != data.spcname -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcname }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/15_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/15_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ca6ba22b2e53e7e2e2dd27277fcf93ec9a0ff532
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/15_plus/sql/update.sql
@@ -0,0 +1,214 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.amname and data.amname != o_data.amname%}
+USING {{ data.amname }}
+{% endif %}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcname and o_data.spcname != data.spcname -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcname }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ======= Change Access Method ========= #}
+{% if data.amname and o_data.amname != data.amname %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET ACCESS METHOD {{ data.amname }};
+
+{% endif %}
+{# ======= Change Access Method end ========= #}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a658b1764569ccf95c22242e8e9f0824f0b626e0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/acl.sql
@@ -0,0 +1,42 @@
+{#============================Get ACLs=========================#}
+{% if vid %}
+SELECT
+ 'datacl' as deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(privilege_type) as privileges,
+ pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee,
+ d.grantor,
+ d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'TRUNCATE' THEN 'D'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ relacl
+ FROM
+ pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON
+ (cl.oid=descr.objoid AND descr.classoid='pg_class'::regclass)
+ WHERE
+ cl.oid = {{ vid }}::OID AND relkind = 'm'
+ ) acl,
+ pg_catalog.aclexplode(relacl) d
+ ) d
+LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY
+ g.rolname,
+ gt.rolname
+ORDER BY grantee
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..f01bb73c163f9b626740ac59ebfb834f1dab81aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/allowed_privs.json
@@ -0,0 +1,6 @@
+{
+ "datacl": {
+ "type": "MVIEW",
+ "acl": ["a", "r", "w", "d", "D", "x", "t"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/coll_mview_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/coll_mview_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c9acdde6135ab5d473aef6af47ad7ce7716ea9e6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/coll_mview_stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ st.relname AS {{ conn|qtIdent(_('View Name')) }},
+ pg_catalog.pg_relation_size(st.relid)
+ + CASE WHEN cl.reltoastrelid = 0 THEN 0 ELSE pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0) END
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=st.relid)::int8, 0) AS {{ conn|qtIdent(_('Total Size')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ vacuum_count AS {{ conn|qtIdent(_('Vacuum counter')) }},
+ autovacuum_count AS {{ conn|qtIdent(_('Autovacuum counter')) }},
+ analyze_count AS {{ conn|qtIdent(_('Analyze counter')) }},
+ autoanalyze_count AS {{ conn|qtIdent(_('Autoanalyze counter')) }}
+FROM
+ pg_catalog.pg_stat_all_tables st
+JOIN
+ pg_catalog.pg_class cl on cl.oid=st.relid and cl.relkind = 'm'
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ORDER BY st.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..02ea09f76d20d82fb4f26eca516f66134039b355
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class c
+WHERE
+ c.relkind = 'm'
+{% if scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..56b2fcef6719d103cb5ba7e36be97c83f437be23
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/create.sql
@@ -0,0 +1,45 @@
+{# ===================== Create new view ===================== #}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE MATERIALIZED VIEW{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if(data.fillfactor or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') or data['vacuum_data']|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% for field in data['vacuum_data'] %}
+{% if field.value is defined and field.value != '' and field.value != none %}
+{% if ns.add_comma %},
+{% endif %} {{ field.name }} = {{ field.value|lower }}{% set ns.add_comma = true%}{% endif %}{% endfor %}
+{{ '\n' }})
+{% endif %}
+{% if data.spcname %}TABLESPACE {{ data.spcname }}
+{% endif %}AS
+{{ data.definition.rstrip(';') }}
+{% if data.with_data %}
+WITH DATA;
+{% else %}
+WITH NO DATA;
+{% endif %}
+{% if data.owner %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2f45fceebfe5c8dcfe472d4f220cc2e1c299435f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/delete.sql
@@ -0,0 +1,13 @@
+{# =================== Drop/Cascade materialized view by name ====================#}
+{% if vid %}
+SELECT
+ c.relname As name,
+ nsp.nspname
+FROM
+ pg_catalog.pg_class c
+LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
+WHERE
+ c.relfilenode = {{ vid }};
+{% elif (name and nspname) %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }} {% if cascade %} CASCADE {% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d56a189bb30f568bef4d3c98ebe8b7d96bfb8332
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_oid.sql
@@ -0,0 +1,9 @@
+{# ===== fetch new assigned schema id ===== #}
+{% if vid %}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{vid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..df31e8e7148470581ad989bc842e13ea04d6c352
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_schema.sql
@@ -0,0 +1,7 @@
+{# ===== fetch schema name =====#}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_view_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_view_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..87bb97cb5ea9989e244eb8b724134a123e55f22b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/get_view_name.sql
@@ -0,0 +1,11 @@
+{# ===== get view name against view id ==== #}
+{% if vid %}
+SELECT
+ c.relname AS name,
+ nsp.nspname AS schema
+FROM
+ pg_catalog.pg_class c
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE
+ c.oid = {{vid}}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c8228cb89e6964ce2ff1dffb7c59d6436fae4ec8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/grant.sql
@@ -0,0 +1,6 @@
+{# ===== Grant Permissions to User Role on Views/Tables ==== #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{# We will generate Security Label SQL using macro #}
+{% if data.seclabels %}{% for r in data.seclabels %}{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}{% endfor %}{% endif %}
+{% if data.datacl %}{% for priv in data.datacl %}{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}{% endfor %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6f919f176352a22a3550167459a805c7d4ffbf9e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/nodes.sql
@@ -0,0 +1,19 @@
+SELECT
+ c.oid,
+ c.relname AS name,
+ description AS comment
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+WHERE
+ c.relkind = 'm'
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ c.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d63c1b7cdad2f3e2d4073b840191da4fe3979c5d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/properties.sql
@@ -0,0 +1,109 @@
+{# ========================== Fetch Materialized View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ c.relispopulated AS with_data,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ c.relacl,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ description AS comment,
+ pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
+ {# ============= Checks if it is system view ================ #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ c.reloptions AS reloptions, tst.reloptions AS toast_reloptions,
+ (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
+FROM
+ pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'm'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/refresh.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/refresh.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a45595fa85b44badd6ac9499e38bc88dbcb144f6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/refresh.sql
@@ -0,0 +1,2 @@
+{#= Refresh materialized view =#}
+REFRESH MATERIALIZED VIEW{% if is_concurrent %} CONCURRENTLY{% endif %} {{ conn|qtIdent(nspname, name) }} WITH {% if not with_data %}NO {% endif %}DATA;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d04588d4e936c49c42d229c05cc56599f9836683
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/stats.sql
@@ -0,0 +1,53 @@
+SELECT
+ seq_scan AS {{ conn|qtIdent(_('Sequential scans')) }},
+ seq_tup_read AS {{ conn|qtIdent(_('Sequential tuples read')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ heap_blks_read AS {{ conn|qtIdent(_('Heap blocks read')) }},
+ heap_blks_hit AS {{ conn|qtIdent(_('Heap blocks hit')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ toast_blks_read AS {{ conn|qtIdent(_('Toast blocks read')) }},
+ toast_blks_hit AS {{ conn|qtIdent(_('Toast blocks hit')) }},
+ tidx_blks_read AS {{ conn|qtIdent(_('Toast index blocks read')) }},
+ tidx_blks_hit AS {{ conn|qtIdent(_('Toast index blocks hit')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ pg_catalog.pg_relation_size(stat.relid) AS {{ conn|qtIdent(_('Table size')) }},
+ CASE WHEN cl.reltoastrelid = 0 THEN NULL ELSE pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0))
+ END AS {{ conn|qtIdent(_('Toast table size')) }},
+ COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=stat.relid)::int8, 0)
+ AS {{ conn|qtIdent(_('Indexes size')) }}
+{% if is_pgstattuple %}
+{#== EXTENDED STATS ==#}
+ ,tuple_count AS {{ conn|qtIdent(_('Tuple count')) }},
+ tuple_len AS {{ conn|qtIdent(_('Tuple length')) }},
+ tuple_percent AS {{ conn|qtIdent(_('Tuple percent')) }},
+ dead_tuple_count AS {{ conn|qtIdent(_('Dead tuple count')) }},
+ dead_tuple_len AS {{ conn|qtIdent(_('Dead tuple length')) }},
+ dead_tuple_percent AS {{ conn|qtIdent(_('Dead tuple percent')) }},
+ free_space AS {{ conn|qtIdent(_('Free space')) }},
+ free_percent AS {{ conn|qtIdent(_('Free percent')) }}
+FROM
+ pgstattuple('{{schema_name}}.{{mview_name}}'), pg_catalog.pg_stat_all_tables stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_tables stat
+{% endif %}
+JOIN
+ pg_catalog.pg_statio_all_tables statio ON stat.relid = statio.relid
+JOIN
+ pg_catalog.pg_class cl ON cl.oid=stat.relid
+WHERE
+ stat.relid = {{ vid }}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a9c742de75ba03af53fc8bb3b0f90f93d5384c5c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/update.sql
@@ -0,0 +1,204 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcoid and o_data.spcoid != data.spcoid -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcoid }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/view_id.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/view_id.sql
new file mode 100644
index 0000000000000000000000000000000000000000..29a8a8cfa3fea437bed85a9117c13a17f6975ad7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/pg/default/sql/view_id.sql
@@ -0,0 +1,6 @@
+{# ===== Below will provide view id for last created view ==== #}
+{% if data %}
+SELECT c.oid, c.relname FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE c.relname = {{ data.name|qtLiteral(conn) }} and nsp.nspname = {{ data.schema|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..64b8597765d93189d1cbd00df30159fe8858aab1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/create.sql
@@ -0,0 +1,50 @@
+{# ===================== Create new view ===================== #}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE MATERIALIZED VIEW{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if data.default_amname and data.default_amname != data.amname %}
+USING {{data.amname}}
+{% elif not data.default_amname and data.amname %}
+USING {{data.amname}}
+{% endif %}
+{% if(data.fillfactor or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') or data['vacuum_data']|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% for field in data['vacuum_data'] %}
+{% if field.value is defined and field.value != '' and field.value != none %}
+{% if ns.add_comma %},
+{% endif %} {{ field.name }} = {{ field.value|lower }}{% set ns.add_comma = true%}{% endif %}{% endfor %}
+{{ '\n' }})
+{% endif %}
+{% if data.spcname %}TABLESPACE {{ data.spcname }}
+{% endif %}AS
+{{ data.definition.rstrip(';') }}
+{% if data.with_data %}
+WITH DATA;
+{% else %}
+WITH NO DATA;
+{% endif %}
+{% if data.owner %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/get_access_methods.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/get_access_methods.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2a93232bfa64b16dcd90042a49e97b7c7c7d0f83
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/get_access_methods.sql
@@ -0,0 +1,3 @@
+-- Fetches access methods
+SELECT oid, amname
+FROM pg_catalog.pg_am WHERE amtype = 't';
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c69930da1cd5edf4286fcc16ae9f6470f750047c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/properties.sql
@@ -0,0 +1,112 @@
+{# ========================== Fetch Materialized View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ c.relispopulated AS with_data,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ (SELECT st.setting from pg_catalog.pg_settings st
+ WHERE st.name = 'default_table_access_method') as default_amname,
+ c.relacl,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ description AS comment,
+ pg_catalog.pg_get_viewdef(c.oid) AS definition,
+ {# ============= Checks if it is system view ================ #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ c.reloptions AS reloptions, tst.reloptions AS toast_reloptions, am.amname,
+ (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
+FROM
+ pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
+LEFT OUTER JOIN pg_catalog.pg_am am ON am.oid = c.relam
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'm'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..997f27528d4db716645cbe6f299dcc5070c31bfe
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/12_plus/sql/update.sql
@@ -0,0 +1,207 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.amname and data.amname != o_data.amname %}
+USING {{ data.amname }}
+{% endif %}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcoid and o_data.spcoid != data.spcoid -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcoid }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/15_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/15_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6661e105440a47f1bb76d600dead84142c9325dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/15_plus/sql/update.sql
@@ -0,0 +1,214 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.amname and data.amname != o_data.amname%}
+USING {{ data.amname }}
+{% endif %}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcoid and o_data.spcoid != data.spcoid -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcoid }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ======= Change Access Method ========= #}
+{% if data.amname and o_data.amname != data.amname %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET ACCESS Method {{ data.amname }};
+
+{% endif %}
+{# ======= Change Access Method end ========= #}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a658b1764569ccf95c22242e8e9f0824f0b626e0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/acl.sql
@@ -0,0 +1,42 @@
+{#============================Get ACLs=========================#}
+{% if vid %}
+SELECT
+ 'datacl' as deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(privilege_type) as privileges,
+ pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee,
+ d.grantor,
+ d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'TRUNCATE' THEN 'D'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ relacl
+ FROM
+ pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON
+ (cl.oid=descr.objoid AND descr.classoid='pg_class'::regclass)
+ WHERE
+ cl.oid = {{ vid }}::OID AND relkind = 'm'
+ ) acl,
+ pg_catalog.aclexplode(relacl) d
+ ) d
+LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY
+ g.rolname,
+ gt.rolname
+ORDER BY grantee
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..f01bb73c163f9b626740ac59ebfb834f1dab81aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/allowed_privs.json
@@ -0,0 +1,6 @@
+{
+ "datacl": {
+ "type": "MVIEW",
+ "acl": ["a", "r", "w", "d", "D", "x", "t"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/coll_mview_stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/coll_mview_stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c9acdde6135ab5d473aef6af47ad7ce7716ea9e6
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/coll_mview_stats.sql
@@ -0,0 +1,29 @@
+SELECT
+ st.relname AS {{ conn|qtIdent(_('View Name')) }},
+ pg_catalog.pg_relation_size(st.relid)
+ + CASE WHEN cl.reltoastrelid = 0 THEN 0 ELSE pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0) END
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=st.relid)::int8, 0) AS {{ conn|qtIdent(_('Total Size')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ vacuum_count AS {{ conn|qtIdent(_('Vacuum counter')) }},
+ autovacuum_count AS {{ conn|qtIdent(_('Autovacuum counter')) }},
+ analyze_count AS {{ conn|qtIdent(_('Analyze counter')) }},
+ autoanalyze_count AS {{ conn|qtIdent(_('Autoanalyze counter')) }}
+FROM
+ pg_catalog.pg_stat_all_tables st
+JOIN
+ pg_catalog.pg_class cl on cl.oid=st.relid and cl.relkind = 'm'
+WHERE
+ schemaname = {{schema_name|qtLiteral(conn)}}
+ORDER BY st.relname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..02ea09f76d20d82fb4f26eca516f66134039b355
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class c
+WHERE
+ c.relkind = 'm'
+{% if scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..300b5361affa6e71dbfb5b5c012bc8607fdb281f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/create.sql
@@ -0,0 +1,45 @@
+{# ===================== Create new view ===================== #}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE MATERIALIZED VIEW{% if add_not_exists_clause %} IF NOT EXISTS{% endif %} {{ conn|qtIdent(data.schema, data.name) }}
+{% if(data.fillfactor or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') or data['vacuum_data']|length > 0) %}
+{% set ns = namespace(add_comma=false) %}
+WITH (
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% set ns.add_comma = true%}{% endif %}{% if data.autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+{% if ns.add_comma %},
+{% endif %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}TRUE{% else %}FALSE{% endif %}{% set ns.add_comma = true%}{% endif %}
+{% for field in data['vacuum_data'] %}
+{% if field.value is defined and field.value != '' and field.value != none %}
+{% if ns.add_comma %},
+{% endif %} {{ field.name }} = {{ field.value|lower }}{% set ns.add_comma = true%}{% endif %}{% endfor %}
+{{ '\n' }})
+{% endif %}
+{% if data.spcname %}TABLESPACE {{ data.spcname }}
+{% endif %}AS
+{{ data.definition.rstrip(';') }}
+{% if data.with_data %}
+WITH DATA;
+{% else %}
+WITH NO DATA;
+{% endif %}
+{% if data.owner %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2f45fceebfe5c8dcfe472d4f220cc2e1c299435f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/delete.sql
@@ -0,0 +1,13 @@
+{# =================== Drop/Cascade materialized view by name ====================#}
+{% if vid %}
+SELECT
+ c.relname As name,
+ nsp.nspname
+FROM
+ pg_catalog.pg_class c
+LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
+WHERE
+ c.relfilenode = {{ vid }};
+{% elif (name and nspname) %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }} {% if cascade %} CASCADE {% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d56a189bb30f568bef4d3c98ebe8b7d96bfb8332
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_oid.sql
@@ -0,0 +1,9 @@
+{# ===== fetch new assigned schema id ===== #}
+{% if vid %}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{vid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..df31e8e7148470581ad989bc842e13ea04d6c352
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_schema.sql
@@ -0,0 +1,7 @@
+{# ===== fetch schema name =====#}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_view_name.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_view_name.sql
new file mode 100644
index 0000000000000000000000000000000000000000..87bb97cb5ea9989e244eb8b724134a123e55f22b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/get_view_name.sql
@@ -0,0 +1,11 @@
+{# ===== get view name against view id ==== #}
+{% if vid %}
+SELECT
+ c.relname AS name,
+ nsp.nspname AS schema
+FROM
+ pg_catalog.pg_class c
+ LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE
+ c.oid = {{vid}}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c8228cb89e6964ce2ff1dffb7c59d6436fae4ec8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/grant.sql
@@ -0,0 +1,6 @@
+{# ===== Grant Permissions to User Role on Views/Tables ==== #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{# We will generate Security Label SQL using macro #}
+{% if data.seclabels %}{% for r in data.seclabels %}{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}{% endfor %}{% endif %}
+{% if data.datacl %}{% for priv in data.datacl %}{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}{% endfor %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6f919f176352a22a3550167459a805c7d4ffbf9e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/nodes.sql
@@ -0,0 +1,19 @@
+SELECT
+ c.oid,
+ c.relname AS name,
+ description AS comment
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+WHERE
+ c.relkind = 'm'
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ c.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..52117c0443d3e2a1aa3a5164744c4837eda2bfd7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/properties.sql
@@ -0,0 +1,109 @@
+{# ========================== Fetch Materialized View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ c.relispopulated AS with_data,
+ CASE WHEN length(spcname::text) > 0 THEN spcname ELSE
+ (SELECT sp.spcname FROM pg_catalog.pg_database dtb
+ JOIN pg_catalog.pg_tablespace sp ON dtb.dattablespace=sp.oid
+ WHERE dtb.oid = {{ did }}::oid)
+ END as spcname,
+ c.relacl,
+ nsp.nspname as schema,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ description AS comment,
+ pg_catalog.pg_get_viewdef(c.oid) AS definition,
+ {# ============= Checks if it is system view ================ #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ (SELECT pg_catalog.array_agg(provider || '=' || label) FROM pg_catalog.pg_seclabels sl1 WHERE sl1.objoid=c.oid AND sl1.objsubid=0) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'fillfactor=([0-9]*)') AS fillfactor,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS autovacuum_enabled,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS autovacuum_freeze_table_age,
+ (substring(pg_catalog.array_to_string(tst.reloptions, ',') FROM 'autovacuum_enabled=([a-z|0-9]*)'))::BOOL AS toast_autovacuum_enabled,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_threshold=([0-9]*)') AS toast_autovacuum_vacuum_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_vacuum_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_threshold=([0-9]*)') AS toast_autovacuum_analyze_threshold,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_analyze_scale_factor=([0-9]*[.]?[0-9]*)') AS toast_autovacuum_analyze_scale_factor,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_delay=([0-9]*)') AS toast_autovacuum_vacuum_cost_delay,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_vacuum_cost_limit=([0-9]*)') AS toast_autovacuum_vacuum_cost_limit,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_min_age=([0-9]*)') AS toast_autovacuum_freeze_min_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_max_age=([0-9]*)') AS toast_autovacuum_freeze_max_age,
+ substring(pg_catalog.array_to_string(tst.reloptions, ',')
+ FROM 'autovacuum_freeze_table_age=([0-9]*)') AS toast_autovacuum_freeze_table_age,
+ c.reloptions AS reloptions, tst.reloptions AS toast_reloptions,
+ (CASE WHEN c.reltoastrelid = 0 THEN false ELSE true END) AS hastoasttable
+FROM
+ pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+LEFT OUTER JOIN pg_catalog.pg_class tst ON tst.oid = c.reltoastrelid
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'm'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/refresh.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/refresh.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c157036b3751d9ded721d3ddaae9d4a4c00cde27
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/refresh.sql
@@ -0,0 +1,4 @@
+{#=== refresh mat view [concurrenlty] ===#}
+{% if name and nspname %}
+REFRESH MATERIALIZED VIEW {% if is_concurrent %}CONCURRENTLY{% endif %} {{ conn|qtIdent(nspname, name) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d04588d4e936c49c42d229c05cc56599f9836683
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/stats.sql
@@ -0,0 +1,53 @@
+SELECT
+ seq_scan AS {{ conn|qtIdent(_('Sequential scans')) }},
+ seq_tup_read AS {{ conn|qtIdent(_('Sequential tuples read')) }},
+ idx_scan AS {{ conn|qtIdent(_('Index scans')) }},
+ idx_tup_fetch AS {{ conn|qtIdent(_('Index tuples fetched')) }},
+ n_tup_ins AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ n_tup_upd AS {{ conn|qtIdent(_('Tuples updated')) }},
+ n_tup_del AS {{ conn|qtIdent(_('Tuples deleted')) }},
+ n_tup_hot_upd AS {{ conn|qtIdent(_('Tuples HOT updated')) }},
+ n_live_tup AS {{ conn|qtIdent(_('Live tuples')) }},
+ n_dead_tup AS {{ conn|qtIdent(_('Dead tuples')) }},
+ heap_blks_read AS {{ conn|qtIdent(_('Heap blocks read')) }},
+ heap_blks_hit AS {{ conn|qtIdent(_('Heap blocks hit')) }},
+ idx_blks_read AS {{ conn|qtIdent(_('Index blocks read')) }},
+ idx_blks_hit AS {{ conn|qtIdent(_('Index blocks hit')) }},
+ toast_blks_read AS {{ conn|qtIdent(_('Toast blocks read')) }},
+ toast_blks_hit AS {{ conn|qtIdent(_('Toast blocks hit')) }},
+ tidx_blks_read AS {{ conn|qtIdent(_('Toast index blocks read')) }},
+ tidx_blks_hit AS {{ conn|qtIdent(_('Toast index blocks hit')) }},
+ last_vacuum AS {{ conn|qtIdent(_('Last vacuum')) }},
+ last_autovacuum AS {{ conn|qtIdent(_('Last autovacuum')) }},
+ last_analyze AS {{ conn|qtIdent(_('Last analyze')) }},
+ last_autoanalyze AS {{ conn|qtIdent(_('Last autoanalyze')) }},
+ pg_catalog.pg_relation_size(stat.relid) AS {{ conn|qtIdent(_('Table size')) }},
+ CASE WHEN cl.reltoastrelid = 0 THEN NULL ELSE pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(cl.reltoastrelid)
+ + COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=cl.reltoastrelid)::int8, 0))
+ END AS {{ conn|qtIdent(_('Toast table size')) }},
+ COALESCE((SELECT SUM(pg_catalog.pg_relation_size(indexrelid))
+ FROM pg_catalog.pg_index WHERE indrelid=stat.relid)::int8, 0)
+ AS {{ conn|qtIdent(_('Indexes size')) }}
+{% if is_pgstattuple %}
+{#== EXTENDED STATS ==#}
+ ,tuple_count AS {{ conn|qtIdent(_('Tuple count')) }},
+ tuple_len AS {{ conn|qtIdent(_('Tuple length')) }},
+ tuple_percent AS {{ conn|qtIdent(_('Tuple percent')) }},
+ dead_tuple_count AS {{ conn|qtIdent(_('Dead tuple count')) }},
+ dead_tuple_len AS {{ conn|qtIdent(_('Dead tuple length')) }},
+ dead_tuple_percent AS {{ conn|qtIdent(_('Dead tuple percent')) }},
+ free_space AS {{ conn|qtIdent(_('Free space')) }},
+ free_percent AS {{ conn|qtIdent(_('Free percent')) }}
+FROM
+ pgstattuple('{{schema_name}}.{{mview_name}}'), pg_catalog.pg_stat_all_tables stat
+{% else %}
+FROM
+ pg_catalog.pg_stat_all_tables stat
+{% endif %}
+JOIN
+ pg_catalog.pg_statio_all_tables statio ON stat.relid = statio.relid
+JOIN
+ pg_catalog.pg_class cl ON cl.oid=stat.relid
+WHERE
+ stat.relid = {{ vid }}::oid
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a9c742de75ba03af53fc8bb3b0f90f93d5384c5c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/update.sql
@@ -0,0 +1,204 @@
+{# ===================== Update View ===================#}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{%- if data -%}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{# ===== Rename mat view ===== #}
+{% if data.name and data.name != o_data.name %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+{# ===== Alter schema view ===== #}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+
+{% endif %}
+{# ===== Alter Table owner ===== #}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+
+{% endif %}
+{# ===== First Drop and then create mat view ===== #}
+{% if def and def != o_data.definition.rstrip(';') %}
+DROP MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }};
+CREATE MATERIALIZED VIEW IF NOT EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+{% if data.fillfactor or o_data.fillfactor %}
+WITH(
+{% if data.fillfactor %}
+ FILLFACTOR = {{ data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% elif o_data.fillfactor %}
+ FILLFACTOR = {{ o_data.fillfactor }}{% if (data['vacuum_data'] is defined and data['vacuum_data']['changed']|length > 0) %},{% endif %}
+{% endif %}
+
+{% if data['vacuum_data']['changed']|length > 0 %}
+{% for field in data['vacuum_data']['changed'] %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+{% endif %}
+)
+{% endif %}
+ AS
+{{ def }}
+{% if data.with_data is defined %}
+ WITH {{ 'DATA' if data.with_data else 'NO DATA' }};
+{% elif o_data.with_data is defined %}
+ WITH {{ 'DATA' if o_data.with_data else 'NO DATA' }};
+
+{% endif %}
+{% if o_data.owner and not data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+
+{% endif %}
+{% if o_data.comment and not data.comment %}
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ o_data.comment|qtLiteral(conn) }};
+{% endif %}
+{% else %}
+{# ======= Alter Tablespace ========= #}
+{%- if data.spcoid and o_data.spcoid != data.spcoid -%}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET TABLESPACE {{ data.spcoid }};
+
+{% endif %}
+{# ======= SET/RESET Fillfactor ========= #}
+{% if data.fillfactor and o_data.fillfactor != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+SET(
+ FILLFACTOR = {{ data.fillfactor }}
+);
+
+{% elif data.fillfactor == '' and o_data.fillfactor|default('', 'true') != data.fillfactor %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+RESET(
+ FILLFACTOR
+);
+
+{% endif %}
+{# ===== Check for with_data property ===== #}
+{% if data.with_data is defined and o_data.with_data|lower != data.with_data|lower %}
+REFRESH MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }} WITH{{ ' NO' if data.with_data|lower == 'false' else '' }} DATA;
+
+{% endif %}
+{# ===== Check for Autovacuum options ===== #}
+{% if data.autovacuum_custom is defined and data.autovacuum_custom == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ autovacuum_enabled,
+ autovacuum_vacuum_threshold,
+ autovacuum_analyze_threshold,
+ autovacuum_vacuum_scale_factor,
+ autovacuum_analyze_scale_factor,
+ autovacuum_vacuum_cost_delay,
+ autovacuum_vacuum_cost_limit,
+ autovacuum_freeze_min_age,
+ autovacuum_freeze_max_age,
+ autovacuum_freeze_table_age
+);
+
+{% endif %}
+
+{% if data.toast_autovacuum is defined and data.toast_autovacuum == False %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+ toast.autovacuum_enabled,
+ toast.autovacuum_vacuum_threshold,
+ toast.autovacuum_analyze_threshold,
+ toast.autovacuum_vacuum_scale_factor,
+ toast.autovacuum_analyze_scale_factor,
+ toast.autovacuum_vacuum_cost_delay,
+ toast.autovacuum_vacuum_cost_limit,
+ toast.autovacuum_freeze_min_age,
+ toast.autovacuum_freeze_max_age,
+ toast.autovacuum_freeze_table_age
+);
+
+{% endif %}{#-- toast_endif ends --#}
+{% if data['vacuum_data']['changed']|length > 0 or data.autovacuum_enabled in ('t', 'f') or data.toast_autovacuum_enabled in ('t', 'f') %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(data.schema, data.name) }} SET(
+{% if data.autovacuum_enabled in ('t', 'f') %}
+ autovacuum_enabled = {% if data.autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 or data.toast_autovacuum_enabled in ('t', 'f') %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled in ('t', 'f') %}
+ toast.autovacuum_enabled = {% if data.toast_autovacuum_enabled == 't' %}true{% else %}false{% endif %}{% if data['vacuum_data']['changed']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['changed'] %}
+{% if field.value != None %} {{ field.name }} = {{ field.value|lower }}{% if not loop.last %},
+{% endif %}
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{% if data['vacuum_data']['reset']|length > 0 or data.autovacuum_enabled == 'x' or data.toast_autovacuum_enabled == 'x' %}
+ALTER MATERIALIZED VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET(
+{% if data.autovacuum_enabled == 'x' %}
+ autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 or data.toast_autovacuum_enabled == 'x' %},
+{% endif %}
+{% endif %}
+{% if data.toast_autovacuum_enabled == 'x' %}
+ toast.autovacuum_enabled{% if data['vacuum_data']['reset']|length > 0 %},
+{% endif %}
+{% endif %}
+{% for field in data['vacuum_data']['reset'] %} {{ field.name }}{% if not loop.last %},
+{% endif %}
+{% endfor %}
+
+);
+{% endif %}
+{# ===== End check for custom autovacuum ===== #}
+{% endif %}{# ===== End block for check data definition ===== #}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON MATERIALIZED VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{# ============= The SQL generated below will change privileges ============= #}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed -%}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{%- endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# ============== The SQL generated below will change Security Label ========= #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'MATERIALIZED VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'MATERIALIZED VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/view_id.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/view_id.sql
new file mode 100644
index 0000000000000000000000000000000000000000..29a8a8cfa3fea437bed85a9117c13a17f6975ad7
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/mviews/ppas/default/sql/view_id.sql
@@ -0,0 +1,6 @@
+{# ===== Below will provide view id for last created view ==== #}
+{% if data %}
+SELECT c.oid, c.relname FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE c.relname = {{ data.name|qtLiteral(conn) }} and nsp.nspname = {{ data.schema|qtLiteral(conn) }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/css/view.css b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/css/view.css
new file mode 100644
index 0000000000000000000000000000000000000000..153f164b5f19b366369135b3745623ca30bd6b57
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/css/view.css
@@ -0,0 +1,8 @@
+.icon-view{
+ background-image: url('{{ url_for('NODE-view.static', filename='img/view.svg') }}') !important;
+ background-repeat: no-repeat;
+ background-size: 20px !important;
+ align-content: center;
+ vertical-align: middle;
+ height: 1.3em;
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..7a363073ef7f44e06260a040c33f5400922bad6e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/create.sql
@@ -0,0 +1,32 @@
+{#============================Create new view=========================#}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} VIEW {{ conn|qtIdent(data.schema, data.name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or data.security_barrier or data.security_invoker) %}
+WITH (
+{% if data.check_option and data.check_option.lower() != 'no' %}
+ check_option={{ data.check_option }}{% if data.security_barrier or data.security_invoker %},
+{% endif %}{% endif %}
+{% if data.security_barrier %}
+ security_barrier={{ data.security_barrier|lower }}{% if data.security_invoker %},
+{% endif %}{% endif %}
+{% if data.security_invoker %}
+ security_invoker={{ data.security_invoker|lower }}{% endif %}
+
+){% endif %} AS
+{{ data.definition.rstrip(';') }};
+{% if data.owner and data.m_view is undefined %}
+
+ALTER TABLE {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+COMMENT ON VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..1664db2fed01be3004bb94e1f56d207d7c50961e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/properties.sql
@@ -0,0 +1,73 @@
+{# ========================== Fetch View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relkind,
+ description AS comment,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ nsp.nspname AS schema,
+ c.relispopulated AS ispopulated,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
+ {# ===== Checks if it is system view ===== #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabels sl1
+ WHERE
+ sl1.objoid=c.oid AND sl1.objsubid=0
+ ) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'check_option=([a-z]*)') AS check_option,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_invoker=([a-z|0-9]*)'))::boolean AS security_invoker
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'v'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2525166058875fbde85e35e85a054bb4607b38c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/15_plus/sql/update.sql
@@ -0,0 +1,106 @@
+{# ============================ Update View ========================= #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{% if data.name and data.name != o_data.name %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
+{% if def and def != o_data.definition.rstrip(';') %}
+{% if data.del_sql %}
+DROP VIEW {{ conn|qtIdent(view_schema, view_name) }};
+
+{% endif %}
+CREATE OR REPLACE VIEW {{ conn|qtIdent(view_schema, view_name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or (o_data.check_option and o_data.check_option.lower() != 'no') or data.security_barrier or o_data.security_barrier or data.security_invoker or o_data.security_invoker) %}
+ WITH ({% if (data.check_option or o_data.check_option) %}check_option={{ data.check_option if data.check_option else o_data.check_option }}{{', ' }}{% endif %}security_barrier={{ data.security_barrier|lower if data.security_barrier is defined else o_data.security_barrier|default('false', 'true')|lower }}{{', ' }}security_invoker={{ data.security_invoker|lower if data.security_invoker is defined else o_data.security_invoker|default('false', 'true')|lower }})
+{% endif %}
+ AS
+ {{ def }};
+{% if data.del_sql and data.owner is not defined %}
+
+ALTER TABLE {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+{% endif %}
+{% else %}
+{% if (data.security_barrier is defined and data.security_barrier|lower != o_data.security_barrier|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_barrier={{ data.security_barrier|lower }});
+{% endif %}
+{% if (data.security_invoker is defined and data.security_invoker|lower != o_data.security_invoker|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_invoker={{ data.security_invoker|lower }});
+{% endif %}
+{% if (data.check_option and data.check_option != o_data.check_option and data.check_option != 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (check_option={{ data.check_option }});
+{% elif (data.check_option and data.check_option != o_data.check_option and data.check_option == 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET (check_option);
+{% endif %}
+{% endif %}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% elif data.del_sql == True and old_comment != '' %}
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ old_comment|qtLiteral(conn) }};
+{% endif %}
+{# The SQL generated below will change privileges #}
+{% if o_data.acl_sql and o_data.acl_sql != '' %}
+{{o_data['acl_sql']}}
+{% endif %}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c999dabaebffc65521ff1dc3c7c403d5770e110c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/acl.sql
@@ -0,0 +1,40 @@
+{# ============================ Get ACLs ========================= #}
+{% if vid %}
+SELECT
+ 'datacl' as deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(privilege_type) as privileges,
+ pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'TRUNCATE' THEN 'D'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ relacl
+ FROM
+ pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON
+ (cl.oid=descr.objoid AND descr.classoid='pg_class'::regclass)
+ WHERE
+ cl.oid = {{ vid }}::OID AND relkind = 'v'
+ ) acl,
+ pg_catalog.aclexplode(relacl) d
+ ) d
+LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY
+ g.rolname,
+ gt.rolname
+ORDER BY grantee
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..71f317fb26f462ca7717a34d40f3c3621bc3b10e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/allowed_privs.json
@@ -0,0 +1,6 @@
+{
+ "datacl": {
+ "type": "VIEW",
+ "acl": ["a", "r", "w", "d", "D", "x", "t"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fdb5d5e4083411d75a88a73a59304c6aec33334d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class c
+WHERE
+ c.relkind = 'v'
+{% if scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e78c046262696ad9ea3b5bb95c838b04b3773b44
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/create.sql
@@ -0,0 +1,28 @@
+{#============================Create new view=========================#}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} VIEW {{ conn|qtIdent(data.schema, data.name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or data.security_barrier) %}
+WITH ({% if data.check_option and data.check_option.lower() != 'no' %}
+
+ check_option={{ data.check_option }}{% endif %}{{ ',' if data.security_barrier }}
+{% if data.security_barrier %}
+ security_barrier={{ data.security_barrier|lower }}
+{% endif %}
+){% endif %} AS
+{{ data.definition.rstrip(';') }};
+{% if data.owner and data.m_view is undefined %}
+
+ALTER TABLE {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+COMMENT ON VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..40118da9db2a07a7e3b3089280f0f6852432926d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/delete.sql
@@ -0,0 +1,13 @@
+{# ====================== Drop/Cascade view by name ===================== #}
+{% if vid %}
+SELECT
+ c.relname AS name,
+ nsp.nspname
+FROM
+ pg_catalog.pg_class c
+LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
+WHERE
+ c.relfilenode = {{ vid }};
+{% elif (name and nspname) %}
+DROP VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }}{% if cascade %} CASCADE {% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d56a189bb30f568bef4d3c98ebe8b7d96bfb8332
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_oid.sql
@@ -0,0 +1,9 @@
+{# ===== fetch new assigned schema id ===== #}
+{% if vid %}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{vid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..45cf029873235fd215e19af1176bae4cfeac113d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/get_schema.sql
@@ -0,0 +1,7 @@
+{# ===== fetch schema name against schema oid ===== #}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..05702c8c3fe5e10476cc6078cd44b4aa70fe834d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/grant.sql
@@ -0,0 +1,8 @@
+{# ===== Grant Permissions to User Role on Views/Tables ===== #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% import 'columns/macros/privilege.macros' as COLUMN_PRIVILEGE %}
+{# ===== We will generate Security Label SQL using macro ===== #}
+{% if data.seclabels %}{% for r in data.seclabels %}{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}{{'\r'}}{% endfor %}{{'\r'}}{% endif %}{% if data.datacl %}
+{% for priv in data.datacl %}{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}{% endfor %}{% endif %}{% if data.attacl %}
+{% for priv in data.attacl %}{{ COLUMN_PRIVILEGE.APPLY(conn, data.schema, data.table, data.name, priv.grantee, priv.without_grant, priv.with_grant) }}{% endfor %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..87bf34d67a9c4289cac5c9545f90da1914e17b4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/nodes.sql
@@ -0,0 +1,19 @@
+SELECT
+ c.oid,
+ c.relname AS name,
+ description AS comment
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+WHERE
+ c.relkind = 'v'
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ c.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..31f47eb0a4ffd780866ae684c8c90a2e53255baa
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/properties.sql
@@ -0,0 +1,71 @@
+{# ========================== Fetch View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relkind,
+ description AS comment,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ nsp.nspname AS schema,
+ c.relispopulated AS ispopulated,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ pg_catalog.pg_get_viewdef(c.oid, true) AS definition,
+ {# ===== Checks if it is system view ===== #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabels sl1
+ WHERE
+ sl1.objoid=c.oid AND sl1.objsubid=0
+ ) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'check_option=([a-z]*)') AS check_option,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'v'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4da58482ff755453a7ddd3fb1ec3d027bbb52c09
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/update.sql
@@ -0,0 +1,102 @@
+{# ============================ Update View ========================= #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{% if data.name and data.name != o_data.name %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
+{% if def and def != o_data.definition.rstrip(';') %}
+{% if data.del_sql %}
+DROP VIEW {{ conn|qtIdent(view_schema, view_name) }};
+
+{% endif %}
+CREATE OR REPLACE VIEW {{ conn|qtIdent(view_schema, view_name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or (o_data.check_option and o_data.check_option.lower() != 'no') or data.security_barrier or o_data.security_barrier) %}
+ WITH ({% if (data.check_option or o_data.check_option) %}check_option={{ data.check_option if data.check_option else o_data.check_option }}{{', ' }}{% endif %}security_barrier={{ data.security_barrier|lower if data.security_barrier is defined else o_data.security_barrier|default('false', 'true')|lower }})
+{% endif %}
+ AS
+ {{ def }};
+{% if data.del_sql and data.owner is not defined %}
+
+ALTER TABLE {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+{% endif %}
+{% else %}
+{% if (data.security_barrier is defined and data.security_barrier|lower != o_data.security_barrier|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_barrier={{ data.security_barrier|lower }});
+{% endif %}
+{% if (data.check_option and data.check_option != o_data.check_option and data.check_option != 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (check_option={{ data.check_option }});
+{% elif (data.check_option and data.check_option != o_data.check_option and data.check_option == 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET (check_option);
+{% endif %}
+{% endif %}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% elif data.del_sql == True and old_comment != '' %}
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ old_comment|qtLiteral(conn) }};
+{% endif %}
+{# The SQL generated below will change privileges #}
+{% if o_data.acl_sql and o_data.acl_sql != '' %}
+{{o_data['acl_sql']}}
+{% endif %}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/view_id.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/view_id.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a4565a31aa28a19e6369e758c65cac89652e37a8
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/pg/default/sql/view_id.sql
@@ -0,0 +1,6 @@
+{# ===== Below will provide view id for last created view ===== #}
+{% if data %}
+SELECT c.oid, c.relname FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE c.relname = {{ data.name |qtLiteral(conn) }} and nsp.nspname = '{{ data.schema }}';
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..6c53b8c4ae6b7ad0adac96aa88be531871fb8dc3
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/create.sql
@@ -0,0 +1,32 @@
+{#============================Create new view=========================#}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} VIEW {{ conn|qtIdent(data.schema, data.name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or data.security_barrier or data.security_invoker) %}
+WITH (
+{% if data.check_option and data.check_option.lower() != 'no' %}
+ check_option={{ data.check_option }}{% if data.security_barrier or data.security_invoker %},
+{% endif %}{% endif %}
+{% if data.security_barrier %}
+ security_barrier={{ data.security_barrier|lower }}{% if data.security_invoker %},
+{% endif %}{% endif %}
+{% if data.security_invoker %}
+ security_invoker={{ data.security_invoker|lower }}{% endif %}
+
+){% endif %} AS
+{{ data.definition.rstrip(';') }};
+{% if data.owner and data.m_view is undefined %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+COMMENT ON VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ccbf99dee952eeedb1d54401211559aa5fa628bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/properties.sql
@@ -0,0 +1,73 @@
+{# ========================== Fetch View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relkind,
+ description AS comment,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ nsp.nspname AS schema,
+ c.relispopulated AS ispopulated,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ pg_catalog.pg_get_viewdef(c.oid) AS definition,
+ {# ===== Checks if it is system view ===== #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabels sl1
+ WHERE
+ sl1.objoid=c.oid AND sl1.objsubid=0
+ ) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'check_option=([a-z]*)') AS check_option,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_invoker=([a-z|0-9]*)'))::boolean AS security_invoker
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'v'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2525166058875fbde85e35e85a054bb4607b38c9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/15_plus/sql/update.sql
@@ -0,0 +1,106 @@
+{# ============================ Update View ========================= #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{% if data.name and data.name != o_data.name %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
+{% if def and def != o_data.definition.rstrip(';') %}
+{% if data.del_sql %}
+DROP VIEW {{ conn|qtIdent(view_schema, view_name) }};
+
+{% endif %}
+CREATE OR REPLACE VIEW {{ conn|qtIdent(view_schema, view_name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or (o_data.check_option and o_data.check_option.lower() != 'no') or data.security_barrier or o_data.security_barrier or data.security_invoker or o_data.security_invoker) %}
+ WITH ({% if (data.check_option or o_data.check_option) %}check_option={{ data.check_option if data.check_option else o_data.check_option }}{{', ' }}{% endif %}security_barrier={{ data.security_barrier|lower if data.security_barrier is defined else o_data.security_barrier|default('false', 'true')|lower }}{{', ' }}security_invoker={{ data.security_invoker|lower if data.security_invoker is defined else o_data.security_invoker|default('false', 'true')|lower }})
+{% endif %}
+ AS
+ {{ def }};
+{% if data.del_sql and data.owner is not defined %}
+
+ALTER TABLE {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+{% endif %}
+{% else %}
+{% if (data.security_barrier is defined and data.security_barrier|lower != o_data.security_barrier|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_barrier={{ data.security_barrier|lower }});
+{% endif %}
+{% if (data.security_invoker is defined and data.security_invoker|lower != o_data.security_invoker|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_invoker={{ data.security_invoker|lower }});
+{% endif %}
+{% if (data.check_option and data.check_option != o_data.check_option and data.check_option != 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (check_option={{ data.check_option }});
+{% elif (data.check_option and data.check_option != o_data.check_option and data.check_option == 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET (check_option);
+{% endif %}
+{% endif %}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% elif data.del_sql == True and old_comment != '' %}
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ old_comment|qtLiteral(conn) }};
+{% endif %}
+{# The SQL generated below will change privileges #}
+{% if o_data.acl_sql and o_data.acl_sql != '' %}
+{{o_data['acl_sql']}}
+{% endif %}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/acl.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/acl.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c999dabaebffc65521ff1dc3c7c403d5770e110c
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/acl.sql
@@ -0,0 +1,40 @@
+{# ============================ Get ACLs ========================= #}
+{% if vid %}
+SELECT
+ 'datacl' as deftype,
+ COALESCE(gt.rolname, 'PUBLIC') grantee,
+ g.rolname grantor,
+ pg_catalog.array_agg(privilege_type) as privileges,
+ pg_catalog.array_agg(is_grantable) as grantable
+FROM
+ (SELECT
+ d.grantee, d.grantor, d.is_grantable,
+ CASE d.privilege_type
+ WHEN 'DELETE' THEN 'd'
+ WHEN 'INSERT' THEN 'a'
+ WHEN 'REFERENCES' THEN 'x'
+ WHEN 'SELECT' THEN 'r'
+ WHEN 'TRIGGER' THEN 't'
+ WHEN 'UPDATE' THEN 'w'
+ WHEN 'TRUNCATE' THEN 'D'
+ ELSE 'UNKNOWN'
+ END AS privilege_type
+ FROM
+ (SELECT
+ relacl
+ FROM
+ pg_catalog.pg_class cl
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON
+ (cl.oid=descr.objoid AND descr.classoid='pg_class'::regclass)
+ WHERE
+ cl.oid = {{ vid }}::OID AND relkind = 'v'
+ ) acl,
+ pg_catalog.aclexplode(relacl) d
+ ) d
+LEFT JOIN pg_catalog.pg_roles g ON (d.grantor = g.oid)
+LEFT JOIN pg_catalog.pg_roles gt ON (d.grantee = gt.oid)
+GROUP BY
+ g.rolname,
+ gt.rolname
+ORDER BY grantee
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/allowed_privs.json b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/allowed_privs.json
new file mode 100644
index 0000000000000000000000000000000000000000..71f317fb26f462ca7717a34d40f3c3621bc3b10e
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/allowed_privs.json
@@ -0,0 +1,6 @@
+{
+ "datacl": {
+ "type": "VIEW",
+ "acl": ["a", "r", "w", "d", "D", "x", "t"]
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fdb5d5e4083411d75a88a73a59304c6aec33334d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/count.sql
@@ -0,0 +1,7 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_class c
+WHERE
+ c.relkind = 'v'
+{% if scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f6a23af6d3e6b5544ea1a465c691c86a2849db09
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/create.sql
@@ -0,0 +1,28 @@
+{#============================Create new view=========================#}
+{% if display_comments %}
+-- View: {{ data.schema }}.{{ data.name }}
+
+-- DROP VIEW {{ conn|qtIdent(data.schema, data.name) }};
+
+{% endif %}
+{% if data.name and data.schema and data.definition %}
+CREATE{% if add_replace_clause %} OR REPLACE{% endif %} VIEW {{ conn|qtIdent(data.schema, data.name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or data.security_barrier) %}
+WITH ({% if data.check_option and data.check_option.lower() != 'no' %}
+
+ check_option={{ data.check_option }}{% endif %}{{ ',' if data.security_barrier }}
+{% if data.security_barrier %}
+ security_barrier={{ data.security_barrier|lower }}
+{% endif %}
+){% endif %} AS
+{{ data.definition.rstrip(';') }};
+{% if data.owner and data.m_view is undefined %}
+
+ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% if data.comment %}
+COMMENT ON VIEW {{ conn|qtIdent(data.schema, data.name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..987752ac64f1aabc4f463964bbae7688620a6415
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/delete.sql
@@ -0,0 +1,13 @@
+{# ====================== Drop/Cascade view by name ===================== #}
+{% if vid %}
+SELECT
+ c.relname AS name,
+ nsp.nspname
+FROM
+ pg_catalog.pg_class c
+LEFT JOIN pg_catalog.pg_namespace nsp ON c.relnamespace = nsp.oid
+WHERE
+ c.relfilenode = {{ vid }};
+{% elif (name and nspname) %}
+DROP VIEW IF EXISTS {{ conn|qtIdent(nspname, name) }} {% if cascade %} CASCADE {% endif %};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_oid.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_oid.sql
new file mode 100644
index 0000000000000000000000000000000000000000..d56a189bb30f568bef4d3c98ebe8b7d96bfb8332
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_oid.sql
@@ -0,0 +1,9 @@
+{# ===== fetch new assigned schema id ===== #}
+{% if vid %}
+SELECT
+ c.relnamespace as scid
+FROM
+ pg_catalog.pg_class c
+WHERE
+ c.oid = {{vid}}::oid;
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_schema.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_schema.sql
new file mode 100644
index 0000000000000000000000000000000000000000..45cf029873235fd215e19af1176bae4cfeac113d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/get_schema.sql
@@ -0,0 +1,7 @@
+{# ===== fetch schema name against schema oid ===== #}
+SELECT
+ nspname
+FROM
+ pg_catalog.pg_namespace
+WHERE
+ oid = {{ scid }}::oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a7e1585bdb8cea49ac245eaf7c24c81940402509
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/grant.sql
@@ -0,0 +1,6 @@
+{# ===== Grant Permissions to User Role on Views/Tables ===== #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{# ===== We will generate Security Label SQL using macro ===== #}
+{% if data.seclabels %}{% for r in data.seclabels %}{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}{{'\r'}}{% endfor %}{{'\r'}}{% endif %}{% if data.datacl %}
+{% for priv in data.datacl %}{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}{% endfor %}{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..87bf34d67a9c4289cac5c9545f90da1914e17b4f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/nodes.sql
@@ -0,0 +1,19 @@
+SELECT
+ c.oid,
+ c.relname AS name,
+ description AS comment
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+WHERE
+ c.relkind = 'v'
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = c.oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
+ORDER BY
+ c.relname
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..db0dacd0ca7b8e48cdb3d34aa91ce66f19ca553d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/properties.sql
@@ -0,0 +1,71 @@
+{# ========================== Fetch View Properties ========================= #}
+{% if (vid and datlastsysoid) or scid %}
+SELECT
+ c.oid,
+ c.xmin,
+ c.relkind,
+ description AS comment,
+ (CASE WHEN length(spc.spcname::text) > 0 THEN spc.spcname ELSE 'pg_default' END) as spcname,
+ c.relname AS name,
+ c.reltablespace AS spcoid,
+ nsp.nspname AS schema,
+ c.relispopulated AS ispopulated,
+ pg_catalog.pg_get_userbyid(c.relowner) AS owner,
+ pg_catalog.array_to_string(c.relacl::text[], ', ') AS acl,
+ pg_catalog.pg_get_viewdef(c.oid) AS definition,
+ {# ===== Checks if it is system view ===== #}
+ {% if vid and datlastsysoid %}
+ CASE WHEN {{vid}} <= {{datlastsysoid}} THEN True ELSE False END AS system_view,
+ {% endif %}
+ (SELECT
+ pg_catalog.array_agg(provider || '=' || label)
+ FROM
+ pg_catalog.pg_seclabels sl1
+ WHERE
+ sl1.objoid=c.oid AND sl1.objsubid=0
+ ) AS seclabels,
+ substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'check_option=([a-z]*)') AS check_option,
+ (substring(pg_catalog.array_to_string(c.reloptions, ',')
+ FROM 'security_barrier=([a-z|0-9]*)'))::boolean AS security_barrier
+FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+LEFT OUTER JOIN pg_catalog.pg_tablespace spc on spc.oid=c.reltablespace
+LEFT OUTER JOIN pg_catalog.pg_description des ON (des.objoid=c.oid and des.objsubid=0 AND des.classoid='pg_class'::regclass)
+ WHERE ((c.relhasrules AND (EXISTS (
+ SELECT
+ r.rulename
+ FROM
+ pg_catalog.pg_rewrite r
+ WHERE
+ ((r.ev_class = c.oid)
+ AND (pg_catalog.bpchar(r.ev_type) = '1'::bpchar)) )))
+ AND (c.relkind = 'v'::char)
+ )
+{% if (vid and datlastsysoid) %}
+ AND c.oid = {{vid}}::oid
+{% elif scid %}
+ AND c.relnamespace = {{scid}}::oid
+ORDER BY
+ c.relname
+{% endif %}
+
+{% elif type == 'roles' %}
+SELECT
+ pr.rolname
+FROM
+ pg_catalog.pg_roles pr
+WHERE
+ pr.rolcanlogin
+ORDER BY
+ pr.rolname
+
+{% elif type == 'schemas' %}
+SELECT
+ nsp.nspname
+FROM
+ pg_catalog.pg_namespace nsp
+WHERE
+ (nsp.nspname NOT LIKE E'pg\\_%'
+ AND nsp.nspname != 'information_schema')
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4da58482ff755453a7ddd3fb1ec3d027bbb52c09
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/update.sql
@@ -0,0 +1,102 @@
+{# ============================ Update View ========================= #}
+{% import 'macros/schemas/security.macros' as SECLABEL %}
+{% import 'macros/schemas/privilege.macros' as PRIVILEGE %}
+{% if data %}
+{% set view_name = data.name if data.name else o_data.name %}
+{% set view_schema = data.schema if data.schema else o_data.schema %}
+{% set def = data.definition.rstrip(';') if data.definition %}
+{% if data.name and data.name != o_data.name %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+{% endif %}
+{% if data.schema and data.schema != o_data.schema %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(o_data.schema, view_name ) }}
+ SET SCHEMA {{ conn|qtIdent(data.schema) }};
+{% endif %}
+{% if def and def != o_data.definition.rstrip(';') %}
+{% if data.del_sql %}
+DROP VIEW {{ conn|qtIdent(view_schema, view_name) }};
+
+{% endif %}
+CREATE OR REPLACE VIEW {{ conn|qtIdent(view_schema, view_name) }}
+{% if ((data.check_option and data.check_option.lower() != 'no') or (o_data.check_option and o_data.check_option.lower() != 'no') or data.security_barrier or o_data.security_barrier) %}
+ WITH ({% if (data.check_option or o_data.check_option) %}check_option={{ data.check_option if data.check_option else o_data.check_option }}{{', ' }}{% endif %}security_barrier={{ data.security_barrier|lower if data.security_barrier is defined else o_data.security_barrier|default('false', 'true')|lower }})
+{% endif %}
+ AS
+ {{ def }};
+{% if data.del_sql and data.owner is not defined %}
+
+ALTER TABLE {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(o_data.owner) }};
+{% endif %}
+{% else %}
+{% if (data.security_barrier is defined and data.security_barrier|lower != o_data.security_barrier|lower) %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (security_barrier={{ data.security_barrier|lower }});
+{% endif %}
+{% if (data.check_option and data.check_option != o_data.check_option and data.check_option != 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ SET (check_option={{ data.check_option }});
+{% elif (data.check_option and data.check_option != o_data.check_option and data.check_option == 'no') %}
+ALTER VIEW IF EXISTS {{ conn|qtIdent(view_schema, view_name) }} RESET (check_option);
+{% endif %}
+{% endif %}
+{% if data.owner and data.owner != o_data.owner %}
+ALTER TABLE IF EXISTS {{ conn|qtIdent(view_schema, view_name) }}
+ OWNER TO {{ conn|qtIdent(data.owner) }};
+{% endif %}
+{% set old_comment = o_data.comment|default('', true) %}
+{% if (data.comment is defined and (data.comment != old_comment)) %}
+
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ data.comment|qtLiteral(conn) }};
+{% elif data.del_sql == True and old_comment != '' %}
+COMMENT ON VIEW {{ conn|qtIdent(view_schema, view_name) }}
+ IS {{ old_comment|qtLiteral(conn) }};
+{% endif %}
+{# The SQL generated below will change privileges #}
+{% if o_data.acl_sql and o_data.acl_sql != '' %}
+{{o_data['acl_sql']}}
+{% endif %}
+{% if data.datacl %}
+{% if 'deleted' in data.datacl %}
+{% for priv in data.datacl.deleted %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in data.datacl %}
+{% for priv in data.datacl.changed %}
+{% if priv.grantee != priv.old_grantee %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.old_grantee, data.name, data.schema) }}
+{% else %}
+{{ PRIVILEGE.UNSETALL(conn, 'TABLE', priv.grantee, data.name, data.schema) }}
+{% endif %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in data.datacl %}
+{% for priv in data.datacl.added %}
+{{ PRIVILEGE.SET(conn, 'TABLE', priv.grantee, data.name, priv.without_grant, priv.with_grant, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{# The SQL generated below will change Security Label #}
+{% if data.seclabels is not none and data.seclabels|length > 0 %}
+{% set seclabels = data.seclabels %}
+{% if 'deleted' in seclabels and seclabels.deleted|length > 0 %}
+{% for r in seclabels.deleted %}
+{{ SECLABEL.UNSET(conn, 'VIEW', data.name, r.provider, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'added' in seclabels and seclabels.added|length > 0 %}
+{% for r in seclabels.added %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% if 'changed' in seclabels and seclabels.changed|length > 0 %}
+{% for r in seclabels.changed %}
+{{ SECLABEL.SET(conn, 'VIEW', data.name, r.provider, r.label, data.schema) }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/view_id.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/view_id.sql
new file mode 100644
index 0000000000000000000000000000000000000000..c38976ff7a030c2e3aa9f7b712b214d2cb879648
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/schemas/views/templates/views/ppas/default/sql/view_id.sql
@@ -0,0 +1,6 @@
+{# ===== Below will provide view id for last created view ===== #}
+{% if data %}
+SELECT c.oid, c.relname FROM pg_catalog.pg_class c
+LEFT OUTER JOIN pg_catalog.pg_namespace nsp on nsp.oid = c.relnamespace
+WHERE c.relname = {{ data.name|qtLiteral(conn) }} and nsp.nspname = '{{ data.schema}}';
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/coll-database.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/coll-database.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d831d773a8b3a94067585b8539b3d50a600310d9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/coll-database.svg
@@ -0,0 +1 @@
+coll-database
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/database.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/database.svg
new file mode 100644
index 0000000000000000000000000000000000000000..44f9e847cae320dcf09b01ff415f17c8447316b4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/database.svg
@@ -0,0 +1 @@
+database
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/databasebad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/databasebad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b3454ffe39a9b1b35f9f55af652b4f8f8de20851
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/databasebad.svg
@@ -0,0 +1 @@
+databasebad
\ No newline at end of file
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database.svg
new file mode 100644
index 0000000000000000000000000000000000000000..998c073a4e309e602a6b6ead01fc0b644b953bd0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database_bad.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database_bad.svg
new file mode 100644
index 0000000000000000000000000000000000000000..5bc006a2af344348433ff03718ad83ddee141fee
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/img/template_database_bad.svg
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.js
new file mode 100644
index 0000000000000000000000000000000000000000..fbc1387ccd6ac685afb73e02c8020d39b5812991
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.js
@@ -0,0 +1,509 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import { getNodeAjaxOptions, getNodeListByName } from '../../../../../static/js/node_ajax';
+import { getNodePrivilegeRoleSchema } from '../../../static/js/privilege.ui';
+import { getNodeVariableSchema } from '../../../static/js/variable.ui';
+import DatabaseSchema from './database.ui';
+import { showServerPassword } from '../../../../../../static/js/Dialogs/index';
+import _ from 'lodash';
+import getApiInstance, { parseApiError } from '../../../../../../static/js/api_instance';
+
+define('pgadmin.node.database', [
+ 'sources/gettext', 'sources/url_for',
+ 'sources/pgadmin', 'pgadmin.browser.utils',
+ 'pgadmin.authenticate.kerberos', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgAdmin, pgBrowser, Kerberos) {
+
+ function canDeleteWithForce(itemNodeData, item) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'],
+ canDisconnect = !_.isUndefined(itemNodeData?.canDisconn) ? itemNodeData.canDisconn : true;
+
+ return (canDisconnect && server && server.version >= 130000);
+ }
+
+ if (!pgBrowser.Nodes['coll-database']) {
+ pgBrowser.Nodes['coll-database'] =
+ pgBrowser.Collection.extend({
+ node: 'database',
+ label: gettext('Databases'),
+ type: 'coll-database',
+ columns: ['name', 'datowner', 'comments'],
+ hasStatistics: true,
+ canDrop: true,
+ selectParentNodeOnDelete: true,
+ canDropCascade: false,
+ canDropForce: canDeleteWithForce,
+ statsPrettifyFields: [gettext('Size'), gettext('Size of temporary files')],
+ });
+ }
+
+ if (!pgBrowser.Nodes['database']) {
+ pgBrowser.Nodes['database'] = pgBrowser.Node.extend({
+ parent_type: 'server',
+ type: 'database',
+ sqlAlterHelp: 'sql-alterdatabase.html',
+ sqlCreateHelp: 'sql-createdatabase.html',
+ dialogHelp: url_for('help.static', {'filename': 'database_dialog.html'}),
+ hasSQL: true,
+ hasDepends: true,
+ hasStatistics: true,
+ statsPrettifyFields: [gettext('Size'), gettext('Size of temporary files')],
+ canDrop: function(node) {
+ return node.canDrop;
+ },
+ selectParentNodeOnDelete: true,
+ label: gettext('Database'),
+ node_image: function() {
+ return 'pg-icon-database';
+ },
+ width: '700px',
+ Init: function() {
+ /* Avoid mulitple registration of menus */
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+ pgBrowser.add_menus([{
+ name: 'create_database_on_server', node: 'server', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Database...'),
+ data: {action: 'create'},
+ enable: 'can_create_database',
+ },{
+ name: 'create_database_on_coll', node: 'coll-database', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Database...'),
+ data: {action: 'create'},
+ enable: 'can_create_database',
+ },{
+ name: 'create_database', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Database...'),
+ data: {action: 'create'},
+ enable: 'can_create_database',
+ },{
+ name: 'connect_database', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'connect_database',
+ category: 'connect', priority: 4, label: gettext('Connect Database'),
+ enable : 'is_not_connected', data: {
+ data_disabled: gettext('Selected database is already connected.'),
+ },
+ },{
+ name: 'delete_database_force', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'delete_database_force',
+ category: 'delete', priority: 2, label: gettext('Delete (Force)'),
+ enable : canDeleteWithForce,
+ }, {
+ name: 'disconnect_database', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'disconnect_database',
+ category: 'disconnect', priority: 5, label: gettext('Disconnect from database'),
+ enable : 'is_connected',data: {
+ data_disabled: gettext('Selected database is already disconnected.'),
+ },
+ },{
+ name: 'generate_erd', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'generate_erd',
+ category: 'erd', priority: 5, label: gettext('ERD For Database'),
+ enable: (node) => {
+ return node.allowConn;
+ }
+ }]);
+
+ _.bindAll(this, 'connection_lost');
+ pgBrowser.Events.on(
+ 'pgadmin:database:connection:lost', this.connection_lost
+ );
+ },
+ can_create_database: function(node, item) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ return server.connected && server.user.can_create_db;
+ },
+ canCreate: function(itemData, item) {
+ let treeData = pgBrowser.tree.getTreeNodeHierarchy(item),
+ server = treeData['server'];
+
+ // If server is less than 10 then do not allow 'create' menu
+ return server && server.version >= 100000;
+ },
+ is_not_connected: function(node) {
+ return (node && !node.connected && node.allowConn);
+ },
+ is_connected: function(node) {
+ return (node?.connected && node?.canDisconn);
+ },
+ is_psql_enabled: function(node) {
+ return node?.connected && pgAdmin['enable_psql'];
+ },
+ is_conn_allow: function(node) {
+ return (node?.allowConn);
+ },
+ connection_lost: function(i, resp, server_connected) {
+ if (pgBrowser.tree) {
+ let t = pgBrowser.tree,
+ d = i && t.itemData(i),
+ self = this;
+
+ while (d?._type != 'database') {
+ i = t.parent(i);
+ d = i && t.itemData(i);
+ }
+
+ if (i && d) {
+ if (!d.allowConn) return false;
+ if (_.isUndefined(d.is_connecting) || !d.is_connecting) {
+ d.is_connecting = true;
+
+ let disconnect = function(_i, _d) {
+ if (_d._id == this._id) {
+ d.is_connecting = false;
+ pgBrowser.Events.off(
+ 'pgadmin:database:connect:cancelled', disconnect
+ );
+ _i = _i && t.parent(_i);
+ _d = _i && t.itemData(_i);
+ if (_i && _d) {
+ pgBrowser.Events.trigger(
+ 'pgadmin:server:disconnect',
+ {item: _i, data: _d}, false
+ );
+ }
+ }
+ };
+
+ pgBrowser.Events.on(
+ 'pgadmin:database:connect:cancelled', disconnect
+ );
+ if (server_connected) {
+ connect(self, d, t, i, true);
+ return;
+ }
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Connection lost'),
+ gettext('Would you like to reconnect to the database?'),
+ function() {
+ connect(self, d, t, i, true);
+ },
+ function() {
+ d.is_connecting = false;
+ let dbIcon = d.isTemplate ? 'icon-database-template-not-connected':'icon-database-not-connected';
+ t.addIcon(i, {icon: dbIcon});
+ t.updateAndReselectNode(i, d);
+ pgBrowser.Events.trigger(
+ 'pgadmin:database:connect:cancelled', i, d, self
+ );
+ });
+ }
+ }
+ }
+ },
+ callbacks: {
+ /* Connect the database */
+ connect_database: function(args){
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (d?.label != 'template0') {
+ connect_to_database(obj, d, t, i, true);
+ }
+ return false;
+ },
+ /* Disconnect the database */
+ disconnect_database: function(args) {
+ let input = args || {},
+ obj = this,
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+
+ if (d) {
+ pgAdmin.Browser.notifier.confirm(
+ gettext('Disconnect from database'),
+ gettext('Are you sure you want to disconnect from database - %s?', d.label),
+ function() {
+ let data = d;
+ getApiInstance().delete(
+ obj.generate_url(i, 'connect', d, true),
+ ).then(({data: res})=> {
+ if (res.success == 1) {
+ let prv_i = t.parent(i);
+ if(res.data.info_prefix) {
+ res.info = `${_.escape(res.data.info_prefix)} - ${res.info}`;
+ }
+ pgAdmin.Browser.notifier.success(res.info);
+ t.removeIcon(i);
+ data.connected = false;
+ data.icon = data.isTemplate ? 'icon-database-template-not-connected':'icon-database-not-connected';
+
+ t.addIcon(i, {icon: data.icon});
+ t.unload(i);
+ pgBrowser.Events.trigger('pgadmin:browser:tree:update-tree-state', i);
+ setTimeout(function() {
+ t.select(prv_i);
+ }, 10);
+
+ } else {
+ try {
+ pgAdmin.Browser.notifier.error(res.errormsg);
+ } catch (e) {
+ console.warn(e.stack || e);
+ }
+ t.unload(i);
+ }
+ }).catch(function(error) {
+ pgAdmin.Browser.notifier.pgRespErrorNotify(error);
+ t.unload(i);
+ });
+ },
+ function() { return true; }
+ );
+ }
+
+ return false;
+ },
+
+ /* Generate the ERD */
+ generate_erd: function(args) {
+ let input = args || {},
+ t = pgBrowser.tree,
+ i = input.item || t.selected(),
+ d = i ? t.itemData(i) : undefined;
+ pgAdmin.Tools.ERD.showErdTool(d, i, true);
+ },
+
+ /* Connect the database (if not connected), before opening this node */
+ beforeopen: function(item, data) {
+ if(!data || data._type != 'database' || data.label == 'template0') {
+ return false;
+ }
+
+ pgBrowser.tree.addIcon(item, {icon: data.icon});
+ if (!data.connected && data.allowConn && !data.is_connecting) {
+ data.is_connecting = true;
+ connect_to_database(this, data, pgBrowser.tree, item, true);
+ return false;
+ }
+ return true;
+ },
+
+ selected: function(item, data) {
+ if(!data || data._type != 'database') {
+ return false;
+ }
+ pgBrowser.tree.addIcon(item, {icon: data.icon});
+ if (!data.connected && data.allowConn && !data.is_connecting) {
+ data.is_connecting = true;
+ connect_to_database(this, data, pgBrowser.tree, item, false);
+ }
+ if(data.connected){
+ return pgBrowser.Node.callbacks.selected.apply(this, arguments);
+ }
+ },
+
+ refresh: function(cmd, i) {
+ let t = pgBrowser.tree,
+ item = i || t.selected(),
+ d = t.itemData(item);
+
+ if (!d.allowConn) return;
+ pgBrowser.Node.callbacks.refresh.apply(this, arguments);
+ },
+
+ delete_database_force: function(args, item) {
+ pgBrowser.Node.callbacks.delete_obj.apply(this, [{'url': 'delete'}, item]);
+ }
+ },
+ getSchema: function(treeNodeInfo, itemNodeData) {
+ let c_types = ()=>getNodeAjaxOptions('get_ctypes', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'server',
+ });
+
+ let icu_locale = ()=>getNodeAjaxOptions('get_icu_locale', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'server',
+ });
+
+ return new DatabaseSchema(
+ ()=>getNodeVariableSchema(this, treeNodeInfo, itemNodeData, false, true),
+ (privileges)=>getNodePrivilegeRoleSchema(this, treeNodeInfo, itemNodeData, privileges),
+ {
+ role: ()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ encoding:
+ ()=>getNodeAjaxOptions('get_encodings', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'server',
+ }),
+ template:
+ ()=>getNodeAjaxOptions('get_databases', this, treeNodeInfo, itemNodeData, {
+ cacheLevel: 'server',
+ }, (data)=>{
+ let res = [];
+ if (data && _.isArray(data)) {
+ _.each(data, function(d) {
+ res.push({label: d, value: d,
+ image: 'pg-icon-database'});
+ });
+ }
+ return res;
+ }),
+ spcname:
+ ()=>getNodeListByName('tablespace', treeNodeInfo, itemNodeData, {}, (m)=>{
+ return (m.label != 'pg_global');
+ }),
+ datcollate: c_types,
+ datctype: c_types,
+ daticulocale: icu_locale,
+ },
+ {
+ datowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ }
+ );
+ },
+ });
+
+ pgBrowser.SecurityGroupSchema = {
+ id: 'security', label: gettext('Security'), type: 'group',
+ // Show/Hide security group for nodes under the catalog
+ visible: function(args) {
+ if (args && 'node_info' in args) {
+ // If node_info is not present in current object then it might in its
+ // parent in case if we used sub node control
+ let node_info = args.node_info || args.handler.node_info;
+ return !('catalog' in node_info);
+ }
+ return true;
+ },
+ };
+
+ let api = getApiInstance();
+ let connect_to_database = function(obj, data, tree, item, _wasConnected) {
+ connect(obj, data, tree, item, _wasConnected);
+ },
+ connect = function (obj, data, tree, item, _wasConnected) {
+ let wasConnected = _wasConnected || data.connected,
+ onFailure = function(
+ error, _model, _data, _tree, _item, _status
+ ) {
+ data.is_connecting = false;
+ if (error.response?.status != 200 && error.response?.request?.responseText?.search('Ticket expired') !== -1) {
+ tree.addIcon(_item, {icon: 'icon-server-connecting'});
+ let fetchTicket = Kerberos.fetch_ticket();
+ fetchTicket.then(
+ function() {
+ connect_to_database(_model, _data, _tree, _item, _wasConnected);
+ },
+ function(fun_error) {
+ tree.setInode(_item);
+ let dbIcon = data.isTemplate ? 'icon-database-template-not-connected':'icon-database-not-connected';
+ tree.addIcon(_item, {icon: dbIcon});
+ pgAdmin.Browser.notifier.pgNotifier(fun_error, error, gettext('Connect to database.'));
+ }
+ );
+ } else {
+ if (!_status) {
+ tree.setInode(_item);
+ let dbIcon = data.isTemplate ? 'icon-database-template-not-connected':'icon-database-not-connected';
+ tree.addIcon(_item, {icon: dbIcon});
+ }
+
+ pgAdmin.Browser.notifier.pgNotifier('error', error, 'Error', function(msg) {
+ setTimeout(function() {
+ if (msg == 'CRYPTKEY_SET') {
+ connect_to_database(_model, _data, _tree, _item, _wasConnected);
+ } else if (msg != 'ALERT_CALLED') {
+ showServerPassword(
+ gettext('Connect to database'),
+ msg, _model, _data, _tree, _item, _status,
+ onSuccess, onFailure, onCancel
+ );
+ }
+ }, 100);
+ });
+ }
+ },
+ onSuccess = function(
+ res, model, _data, _tree, _item, _connected
+ ) {
+ _data.is_connecting = false;
+ if (res?.data) {
+ if(typeof res.data.connected == 'boolean') {
+ _data.connected = res.data.connected;
+ }
+ if (typeof res.data.icon == 'string') {
+ _tree.removeIcon(_item);
+ _data.icon = res.data.icon;
+ let dbIcon = _data.isTemplate ? 'icon-database-template-connected':_data.icon;
+ _tree.addIcon(_item, {icon: dbIcon});
+ }
+ if(res.data.already_connected) {
+ res.info = gettext('Database already connected.');
+ }
+ if(res.data.info_prefix) {
+ res.info = `${_.escape(res.data.info_prefix)} - ${res.info}`;
+ }
+ if(res.data.already_connected) {
+ pgAdmin.Browser.notifier.info(res.info);
+ } else {
+ pgAdmin.Browser.notifier.success(res.info);
+ }
+ pgBrowser.Events.trigger(
+ 'pgadmin:database:connected', _item, _data
+ );
+ /* Call enable/disable menu function after database is connected.
+ To make sure all the menus for database is in the right state */
+ pgBrowser.enable_disable_menus(_item);
+ pgBrowser.Nodes['database'].callbacks.selected(_item, _data);
+
+ if (!_connected) {
+ setTimeout(function() {
+ _tree.select(_item);
+ _tree.open(_item);
+ }, 10);
+ }
+ }
+ },
+ onCancel = function(_tree, _item, _data) {
+ _data.is_connecting = false;
+ let server = _tree.parent(_item);
+ _tree.removeIcon(_item);
+ let dbIcon = data.isTemplate ? 'icon-database-template-not-connected':'icon-database-not-connected';
+ _tree.addIcon(_item, {icon: dbIcon});
+ _tree.updateAndReselectNode(_item, _data);
+ obj.trigger('connect:cancelled', obj, _item, _data);
+ pgBrowser.Events.trigger(
+ 'pgadmin:database:connect:cancelled', _item, _data, obj
+ );
+ _tree.select(server);
+ };
+
+ api.post(obj.generate_url(item, 'connect', data, true))
+ .then(({data: res})=>{
+ if (res.success == 1) {
+ return onSuccess(res, obj, data, tree, item, wasConnected);
+ }
+ })
+ .catch((error)=>{
+ if (error.response?.status === 410) {
+ error = gettext('Error: Object not found - %s.', parseApiError(error));
+ }
+
+ return onFailure(
+ error, obj, data, tree, item, wasConnected
+ );
+ });
+ };
+ }
+
+ return pgBrowser.Nodes['coll-database'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..f13c4d7c4386a01c03081d0f7765ac267bf85b0d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/static/js/database.ui.js
@@ -0,0 +1,298 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+
+import _ from 'lodash';
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import SecLabelSchema from '../../../static/js/sec_label.ui';
+
+export class DefaultPrivSchema extends BaseUISchema {
+ constructor(getPrivilegeRoleSchema) {
+ super();
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ }
+
+ get baseFields() {
+ return [
+ {
+ id: 'deftblacl', type: 'collection', group: gettext('Tables'),
+ schema: this.getPrivilegeRoleSchema(['a', 'r', 'w', 'd', 'D', 'x', 't']),
+ mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ uniqueCol : ['grantee', 'grantor'],
+ },{
+ id: 'defseqacl', type: 'collection', group: gettext('Sequences'),
+ schema: this.getPrivilegeRoleSchema(['r', 'w', 'U']),
+ mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ uniqueCol : ['grantee', 'grantor'],
+ },{
+ id: 'deffuncacl', type: 'collection', group: gettext('Functions'),
+ schema: this.getPrivilegeRoleSchema(['X']),
+ mode: ['edit', 'create'],
+ canAdd: true, canDelete: true, uniqueCol : ['grantee', 'grantor'],
+ },{
+ id: 'deftypeacl', type: 'collection', group: gettext('Types'),
+ schema: this.getPrivilegeRoleSchema(['U']), min_version: 90200,
+ mode: ['edit', 'create'],
+ canAdd: true, canDelete: true, uniqueCol : ['grantee', 'grantor'],
+ },
+ ];
+ }
+}
+
+export default class DatabaseSchema extends BaseUISchema {
+ constructor(getVariableSchema, getPrivilegeRoleSchema, fieldOptions={}, initValues={}) {
+ super({
+ name: undefined,
+ owner: undefined,
+ is_sys_obj: false,
+ comment: undefined,
+ encoding: 'UTF8',
+ template: undefined,
+ tablespace: undefined,
+ collation: undefined,
+ char_type: undefined,
+ datconnlimit: -1,
+ datallowconn: undefined,
+ datlocaleprovider: 'libc',
+ variables: [],
+ privileges: [],
+ securities: [],
+ datacl: [],
+ deftblacl: [],
+ deffuncacl: [],
+ defseqacl: [],
+ is_template: false,
+ deftypeacl: [],
+ schema_res: [],
+ ...initValues,
+ });
+ this.getVariableSchema = getVariableSchema;
+ this.getPrivilegeRoleSchema = getPrivilegeRoleSchema;
+ this.fieldOptions = {
+ role: [],
+ encoding: [],
+ template: [],
+ spcname: [],
+ datcollate: [],
+ datctype: [],
+ daticulocale: [],
+ ...fieldOptions,
+ };
+ }
+
+ get idAttribute() {
+ return 'did';
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [
+ {
+ id: 'name', label: gettext('Database'), cell: 'text',
+ editable: false, type: 'text', noEmpty: true, isCollectionProperty: true,
+ },{
+ id: 'did', label: gettext('OID'), cell: 'text', mode: ['properties'],
+ editable: false, type: 'text',
+ },{
+ id: 'datoid', label: gettext('OID'), mode: ['create'], type: 'int',
+ min: 16384, min_version: 150000
+ }, {
+ id: 'datowner', label: gettext('Owner'),
+ editable: false, type: 'select', options: this.fieldOptions.role,
+ controlProps: { allowClear: false }, isCollectionProperty: true,
+ },{
+ id: 'is_sys_obj', label: gettext('System database?'),
+ cell: 'switch', type: 'switch', mode: ['properties'],
+ },{
+ id: 'comments', label: gettext('Comment'),
+ editable: false, type: 'multiline', isCollectionProperty: true,
+ },{
+ id: 'encoding', label: gettext('Encoding'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ options: this.fieldOptions.encoding,
+ },{
+ id: 'template', label: gettext('Template'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ options: this.fieldOptions.template,
+ controlProps: { allowClear: false }, mode: ['create'],
+ },{
+ id: 'spcname', label: gettext('Tablespace'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ options: this.fieldOptions.spcname,
+ controlProps: { allowClear: false },
+ },{
+ id: 'datstrategy', label: gettext('Strategy'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ mode: ['create'],
+ options: [{
+ label: gettext('WAL Log'),
+ value: 'wal_log',
+ }, {
+ label: gettext('File Copy'),
+ value: 'file_copy',
+ }],
+ min_version: 150000
+ }, {
+ id: 'datlocaleprovider', label: gettext('Locale Provider'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ controlProps: { allowClear: false },
+ options: [{
+ label: gettext('icu'),
+ value: 'icu',
+ }, {
+ label: gettext('libc'),
+ value: 'libc',
+ }],
+ min_version: 150000
+ },{
+ id: 'datcollate', label: gettext('Collation'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ options: this.fieldOptions.datcollate,
+ deps: ['datlocaleprovider'],
+ depChange: (state)=>{
+ if (state.datlocaleprovider !== 'libc')
+ return { datcollate: '' };
+ },
+ disabled: function(state) {
+ return state.datlocaleprovider !== 'libc';
+ },
+ },{
+ id: 'datctype', label: gettext('Character type'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ options: this.fieldOptions.datctype,
+ deps: ['datlocaleprovider'],
+ depChange: (state)=>{
+ if (state.datlocaleprovider !== 'libc')
+ return { datctype: '' };
+ },
+ disabled: function(state) {
+ return state.datlocaleprovider !== 'libc';
+ },
+ },{
+ id: 'daticulocale', label: gettext('ICU Locale'),
+ editable: false, type: 'select', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ options: this.fieldOptions.daticulocale,
+ deps: ['datlocaleprovider'],
+ depChange: (state)=>{
+ if (state.datlocaleprovider !== 'icu')
+ return { daticulocale: '' };
+ },
+ disabled: function(state) {
+ return state.datlocaleprovider !== 'icu';
+ },
+ min_version: 150000
+ }, {
+ id: 'datcollversion', label: gettext('Collation Version'),
+ editable: false, type: 'text', group: gettext('Definition'),
+ mode: ['properties'], min_version: 150000
+ }, {
+ id: 'daticurules', label: gettext('ICU Rules'),
+ editable: false, type: 'text', group: gettext('Definition'),
+ readonly: function(state) {return !obj.isNew(state); },
+ deps: ['datlocaleprovider'],
+ depChange: (state)=>{
+ if (state.datlocaleprovider !== 'icu')
+ return { daticurules: '' };
+ },
+ disabled: function(state) {
+ return state.datlocaleprovider !== 'icu';
+ },
+ min_version: 160000
+ }, {
+ id: 'datconnlimit', label: gettext('Connection limit'),
+ editable: false, type: 'int', group: gettext('Definition'),
+ min: -1,
+ },{
+ id: 'is_template', label: gettext('Template?'),
+ type: 'switch', group: gettext('Definition'),
+ mode: ['properties', 'edit', 'create'], readonly: function(state) {return (state.is_sys_obj); },
+ helpMessage: gettext('Note: When the preferences setting \'show template databases\' is set to false, then template databases won\'t be displayed in the object explorer.'),
+ helpMessageMode: ['edit', 'create'],
+ },{
+ id: 'datallowconn', label: gettext('Allow connections?'),
+ editable: false, type: 'switch', group: gettext('Definition'),
+ mode: ['properties'],
+ },{
+ id: 'acl', label: gettext('Privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'tblacl', label: gettext('Default TABLE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'seqacl', label: gettext('Default SEQUENCE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'funcacl', label: gettext('Default FUNCTION privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'],
+ },{
+ id: 'typeacl', label: gettext('Default TYPE privileges'), type: 'text',
+ group: gettext('Security'), mode: ['properties'], min_version: 90200,
+ },
+ {
+ id: 'datacl', label: gettext('Privileges'), type: 'collection',
+ schema: this.getPrivilegeRoleSchema(['C', 'T', 'c']),
+ uniqueCol : ['grantee', 'grantor'],
+ editable: false,
+ group: gettext('Security'), mode: ['edit', 'create'],
+ canAdd: true, canDelete: true,
+ },
+ {
+ id: 'variables', label: '', type: 'collection',
+ schema: this.getVariableSchema(),
+ editable: false,
+ group: gettext('Parameters'), mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true, hasRole: true,
+ node: 'role',
+ },{
+ id: 'seclabels', label: gettext('Security labels'), type: 'collection',
+ schema: new SecLabelSchema(),
+ editable: false, group: gettext('Security'),
+ mode: ['edit', 'create'],
+ canAdd: true, canEdit: false, canDelete: true,
+ uniqueCol : ['provider'],
+ min_version: 90200,
+ },{
+ type: 'nested-tab', group: gettext('Default Privileges'),
+ mode: ['edit'],
+ schema: new DefaultPrivSchema(this.getPrivilegeRoleSchema),
+ },
+ {
+ id: 'schema_res', label: gettext('Schema restriction'),
+ type: 'select', group: gettext('Advanced'),
+ mode: ['properties', 'edit', 'create'],
+ helpMessage: gettext('Note: Changes to the schema restriction will require the Schemas node in the browser to be refreshed before they will be shown.'),
+ helpMessageMode: ['edit', 'create'],
+ controlProps: {
+ multiple: true, allowClear: false, creatable: true, noDropdown: true, placeholder: 'Specify the schemas to be restrict...'
+ }, depChange: (state)=>{
+ if(!_.isUndefined(state.oid)) {
+ obj.informText = undefined;
+ }
+
+ if(!_.isEqual(obj.origData.schema_res, state.schema_res)) {
+ obj.informText = gettext(
+ 'Please refresh the Schemas node to make changes to the schema restriction take effect.'
+ );
+ } else {
+ obj.informText = undefined;
+ }
+ },
+ },
+ ];
+ }
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-publication.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-publication.svg
new file mode 100644
index 0000000000000000000000000000000000000000..cc946919b2f2fb48df2f629d62eacd89c906c3ef
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-publication.svg
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-subscription.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-subscription.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d14adfd394648360316156eed293cd77a7d76d50
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/coll-subscription.svg
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/publication.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/publication.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3b582cf51c670e7d11a2c14de9d82fc6debaa59a
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/publication.svg
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/subscription.svg b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/subscription.svg
new file mode 100644
index 0000000000000000000000000000000000000000..63a153c6d58debc60099a085f28858de4b7035d4
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/img/subscription.svg
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.js
new file mode 100644
index 0000000000000000000000000000000000000000..269c1c723d6f18ddbf7f31c9d20475ca70f1f6f0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.js
@@ -0,0 +1,131 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import { getNodeListByName } from '../../../../../../static/js/node_ajax';
+import SubscriptionSchema from './subscription.ui';
+import getApiInstance from '../../../../../../../static/js/api_instance';
+import _ from 'lodash';
+import pgAdmin from 'sources/pgadmin';
+
+define('pgadmin.node.subscription', [
+ 'sources/gettext', 'sources/url_for',
+ 'pgadmin.browser', 'pgadmin.browser.collection',
+], function(gettext, url_for, pgBrowser) {
+
+ // Extend the browser's collection class for subscriptions collection
+ if (!pgBrowser.Nodes['coll-subscription']) {
+ pgBrowser.Nodes['coll-subscription'] =
+ pgBrowser.Collection.extend({
+ node: 'subscription',
+ label: gettext('Subscriptions'),
+ type: 'coll-subscription',
+ columns: ['name', 'subowner', 'proppub', 'enabled'],
+ hasStatistics: true,
+ });
+ }
+
+ // Extend the browser's node class for subscription node
+ if (!pgBrowser.Nodes['subscription']) {
+ pgBrowser.Nodes['subscription'] = pgBrowser.Node.extend({
+ parent_type: 'database',
+ type: 'subscription',
+ sqlAlterHelp: 'sql-altersubscription.html',
+ sqlCreateHelp: 'sql-createsubscription.html',
+ dialogHelp: url_for('help.static', {'filename': 'subscription_dialog.html'}),
+ label: gettext('Subscription'),
+ hasSQL: true,
+ canDrop: true,
+ canDropCascade: true,
+ hasDepends: true,
+ hasStatistics: true,
+ width: '501px',
+ Init: function() {
+
+ // Avoid multiple registration of menus
+ if (this.initialized)
+ return;
+
+ this.initialized = true;
+
+
+ // Add context menus for subscription
+ pgBrowser.add_menus([{
+ name: 'create_subscription_on_database', node: 'database', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Subscription...'),
+ data: {action: 'create'},
+ enable: pgBrowser.Nodes['database'].canCreate,
+ },{
+ name: 'create_subscription_on_coll', node: 'coll-subscription', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Subscription...'),
+ data: {action: 'create'},
+ enable: 'canCreate',
+ },{
+ name: 'create_subscription', node: 'subscription', module: this,
+ applies: ['object', 'context'], callback: 'show_obj_properties',
+ category: 'create', priority: 4, label: gettext('Subscription...'),
+ data: {action: 'create'},
+ enable: 'canCreate',
+ }]);
+ },
+ getSchema: function(treeNodeInfo, itemNodeData){
+ return new SubscriptionSchema(
+ {
+ role:()=>getNodeListByName('role', treeNodeInfo, itemNodeData),
+ getPublication: (host, password, port, username, db,
+ connectTimeout, passfile, sslmode,
+ sslcompression, sslcert, sslkey,
+ sslrootcert, sslcrl) =>
+ {
+ return new Promise((resolve, reject)=>{
+ const api = getApiInstance();
+ if(host != undefined && port!= undefined && username!= undefined && db != undefined){
+ let _url = pgBrowser.Nodes['cast'].generate_url.apply(
+ pgBrowser.Nodes['subscription'], [
+ null, 'get_publications', itemNodeData, false,
+ treeNodeInfo,
+ ]);
+ api.get(_url, {
+ params: {host, password, port, username, db,
+ connectTimeout, passfile, sslmode,
+ sslcompression, sslcert, sslkey,
+ sslrootcert, sslcrl},
+ })
+ .then(res=>{
+ if ((res.data.errormsg === '') && !_.isNull(res.data.data)){
+ resolve(res.data.data);
+ pgAdmin.Browser.notifier.info(
+ gettext('Publication fetched successfully.')
+ );
+ }else if(!_.isNull(res.data.errormsg) && _.isNull(res.data.data)){
+ reject(res.data.errormsg);
+ pgAdmin.Browser.notifier.alert(
+ gettext('Check connection?'),
+ gettext(res.data.errormsg)
+ );
+ }
+ })
+ .catch((err)=>{
+ reject(err);
+ });
+ }
+ });
+ },
+ },{
+ node_info: treeNodeInfo.server,
+ },
+ {
+ subowner: pgBrowser.serverInfo[treeNodeInfo.server._id].user.name,
+ },
+ );
+ },
+ });
+ }
+ return pgBrowser.Nodes['coll-subscription'];
+});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..f6775c187df4416525ddc547195e9affb42c9794
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js
@@ -0,0 +1,501 @@
+/////////////////////////////////////////////////////////////
+//
+// pgAdmin 4 - PostgreSQL Tools
+//
+// Copyright (C) 2013 - 2024, The pgAdmin Development Team
+// This software is released under the PostgreSQL Licence
+//
+//////////////////////////////////////////////////////////////
+import gettext from 'sources/gettext';
+import BaseUISchema from 'sources/SchemaView/base_schema.ui';
+import { isEmptyString } from 'sources/validators';
+import _ from 'lodash';
+
+export default class SubscriptionSchema extends BaseUISchema{
+ constructor(fieldOptions={}, node_info={}, initValues={}) {
+ super({
+ name: undefined,
+ subowner: undefined,
+ pubtable: undefined,
+ connect_timeout: 10,
+ pub:[],
+ enabled:true,
+ create_slot: true,
+ copy_data:true,
+ connect:true,
+ binary:false,
+ two_phase:false,
+ disable_on_error:false,
+ streaming:false,
+ password_required:true,
+ run_as_owner:false,
+ origin:'any',
+ copy_data_after_refresh:false,
+ sync:'off',
+ refresh_pub: false,
+ password: '',
+ sslmode: 'prefer',
+ sslcompression: false,
+ sslcert: '',
+ sslkey: '',
+ sslrootcert: '',
+ sslcrl: '',
+ host: '',
+ port: 5432,
+ db: 'postgres',
+ ...initValues,
+ });
+
+ this.fieldOptions = {
+ role: [],
+ publicationTable: [],
+ ...fieldOptions,
+ };
+ this.node_info = node_info;
+ this.version=!_.isUndefined(this.node_info['node_info']) && !_.isUndefined(this.node_info['node_info'].version) && this.node_info['node_info'].version;
+
+ }
+ get idAttribute() {
+ return 'oid';
+ }
+
+ get SSL_MODES() { return ['prefer', 'require', 'verify-ca', 'verify-full']; }
+
+ isDisable(){
+ return !this.isNew();
+ }
+ isSameDB(state){
+ let host = state.host,
+ port = state.port;
+
+ if ((state.host == 'localhost' || state.host == '127.0.0.1') &&
+ (this.node_info['node_info'].host == 'localhost' || this.node_info['node_info'].host == '127.0.0.1')){
+ host = this.node_info['node_info'].host;
+ }
+ if (host == this.node_info['node_info'].host && port == this.node_info['node_info'].port){
+ state.create_slot = false;
+ return true;
+ } else {
+ state.create_slot = true;
+ }
+ return false;
+ }
+ isAllConnectionDataEnter(state){
+ let host = state.host,
+ db = state.db,
+ port = state.port,
+ username = state.username;
+ return !((!_.isUndefined(host) && host) && (!_.isUndefined(db) && db) && (!_.isUndefined(port) && port) && (!_.isUndefined(username) && username));
+ }
+ isConnect(state){
+ if(!_.isUndefined(state.connect) && !state.connect){
+ state.copy_data = false;
+ state.create_slot = false;
+ state.enabled = false;
+ return true;
+ }
+ return false;
+ }
+ isRefresh(state){
+ return !state.refresh_pub || _.isUndefined(state.refresh_pub);
+ }
+ isSSL(state) {
+ return this.SSL_MODES.indexOf(state.sslmode) == -1;
+ }
+
+ get baseFields() {
+ let obj = this;
+ return [{
+ id: 'name', label: gettext('Name'), type: 'text',
+ mode: ['properties', 'create', 'edit'], noEmpty: true,
+ min_version: 100000
+ },{
+ id: 'oid', label: gettext('OID'), cell: 'string', mode: ['properties'],
+ type: 'text',
+ },
+ {
+ id: 'subowner', label: gettext('Owner'),
+ options: this.fieldOptions.role,
+ type: 'select',
+ mode: ['edit', 'properties', 'create'], controlProps: { allowClear: false},
+ disabled: function(){
+ return obj.isNew();
+ },
+ },{
+ id: 'host', label: gettext('Host name/address'), type: 'text', group: gettext('Connection'),
+ mode: ['properties', 'edit', 'create'],
+ },
+ {
+ id: 'port', label: gettext('Port'), type: 'int', group: gettext('Connection'),
+ mode: ['properties', 'edit', 'create'], min: 1, max: 65535,
+ depChange: (state)=>{
+ if(obj.origData.port != state.port && !obj.isNew(state) && state.connected){
+ obj.informText = gettext(
+ 'To apply changes to the connection configuration, please disconnect from the server and then reconnect.'
+ );
+ } else {
+ obj.informText = undefined;
+ }
+ }
+ },{
+ id: 'db', label: gettext('Database'), type: 'text', group: gettext('Connection'),
+ mode: ['properties', 'edit', 'create'], readonly: obj.isConnected, disabled: obj.isShared,
+ noEmpty: true,
+ },{
+ id: 'username', label: gettext('Username'), type: 'text', group: gettext('Connection'),
+ mode: ['properties', 'edit', 'create'],
+ depChange: (state)=>{
+ if(obj.origData.username != state.username && !obj.isNew(state) && state.connected){
+ obj.informText = gettext(
+ 'To apply changes to the connection configuration, please disconnect from the server and then reconnect.'
+ );
+ } else {
+ obj.informText = undefined;
+ }
+ }
+ },
+ {
+ id: 'password', label: gettext('Password'), type: 'password',
+ controlProps: { maxLength: null, autoComplete: 'new-password' },
+ group: gettext('Connection'),
+ mode: ['create', 'edit'], skipChange: true,
+ deps: ['connect_now'],
+ },
+ {
+ id: 'connect_timeout', label: gettext('Connection timeout'), type: 'text',
+ mode: ['properties', 'edit', 'create'],
+ group: gettext('Connection'),
+ },
+ {
+ id: 'passfile', label: gettext('Passfile'), type: 'text', group: gettext('Connection'),
+ mode: ['properties', 'edit', 'create'],
+ },
+ {
+ id: 'proppub', label: gettext('Publication'), type: 'text', group: gettext('Connection'),
+ mode: ['properties'],
+ },
+ {
+ id: 'pub', label: gettext('Publication'),
+ group: gettext('Connection'), mode: ['create', 'edit'],
+ deps: ['all_table', 'host', 'port', 'username', 'db', 'password'], disabled: obj.isAllConnectionDataEnter,
+ helpMessage: gettext('Click the refresh button to get the publications'),
+ helpMessageMode: ['edit', 'create'],
+ type: (state)=>{
+ return {
+ type: 'select-refresh',
+ controlProps: { allowClear: true, multiple: true, creatable: true, getOptionsOnRefresh: ()=>{
+ return obj.fieldOptions.getPublication(state.host, state.password, state.port, state.username, state.db,
+ state.connect_timeout, state.passfile, state.sslmode,
+ state.sslcompression, state.sslcert, state.sslkey,
+ state.sslrootcert, state.sslcrl);
+ }},
+ };
+ },
+ },
+
+ {
+ id: 'sslmode', label: gettext('SSL mode'), type: 'select', group: gettext('SSL'),
+ controlProps: {
+ allowClear: false,
+ },
+ mode: ['properties', 'edit', 'create'],
+ options: [
+ {label: gettext('Allow'), value: 'allow'},
+ {label: gettext('Prefer'), value: 'prefer'},
+ {label: gettext('Require'), value: 'require'},
+ {label: gettext('Disable'), value: 'disable'},
+ {label: gettext('Verify-CA'), value: 'verify-ca'},
+ {label: gettext('Verify-Full'), value: 'verify-full'},
+ ],
+ },{
+ id: 'sslcert', label: gettext('Client certificate'), type: 'file',
+ group: gettext('SSL'), mode: ['edit', 'create'],
+ disabled: obj.isSSL,
+ controlProps: {
+ dialogType: 'select_file', supportedTypes: ['*'],
+ },
+ deps: ['sslmode'],
+ },
+ {
+ id: 'sslkey', label: gettext('Client certificate key'), type: 'file',
+ group: gettext('SSL'), mode: ['edit', 'create'],
+ disabled: obj.isSSL,
+ controlProps: {
+ dialogType: 'select_file', supportedTypes: ['*'],
+ },
+ deps: ['sslmode'],
+ },{
+ id: 'sslrootcert', label: gettext('Root certificate'), type: 'file',
+ group: gettext('SSL'), mode: ['edit', 'create'],
+ disabled: obj.isSSL,
+ controlProps: {
+ dialogType: 'select_file', supportedTypes: ['*'],
+ },
+ deps: ['sslmode'],
+ },{
+ id: 'sslcrl', label: gettext('Certificate revocation list'), type: 'file',
+ group: gettext('SSL'), mode: ['edit', 'create'],
+ disabled: obj.isSSL,
+ controlProps: {
+ dialogType: 'select_file', supportedTypes: ['*'],
+ },
+ deps: ['sslmode'],
+ },
+ {
+ id: 'sslcompression', label: gettext('SSL compression?'), type: 'switch',
+ mode: ['edit', 'create'], group: gettext('SSL'),
+ disabled: obj.isSSL,
+ deps: ['sslmode'],
+ },
+ {
+ id: 'sslcert', label: gettext('Client certificate'), type: 'text',
+ group: gettext('SSL'), mode: ['properties'],
+ deps: ['sslmode'],
+ visible: function(state) {
+ let sslcert = state.sslcert;
+ return !_.isUndefined(sslcert) && !_.isNull(sslcert);
+ },
+ },{
+ id: 'sslkey', label: gettext('Client certificate key'), type: 'text',
+ group: gettext('SSL'), mode: ['properties'],
+ deps: ['sslmode'],
+ visible: function(state) {
+ let sslkey = state.sslkey;
+ return !_.isUndefined(sslkey) && !_.isNull(sslkey);
+ },
+ },{
+ id: 'sslrootcert', label: gettext('Root certificate'), type: 'text',
+ group: gettext('SSL'), mode: ['properties'],
+ deps: ['sslmode'],
+ visible: function(state) {
+ let sslrootcert = state.sslrootcert;
+ return !_.isUndefined(sslrootcert) && !_.isNull(sslrootcert);
+ },
+ },{
+ id: 'sslcrl', label: gettext('Certificate revocation list'), type: 'text',
+ group: gettext('SSL'), mode: ['properties'],
+ deps: ['sslmode'],
+ visible: function(state) {
+ let sslcrl = state.sslcrl;
+ return !_.isUndefined(sslcrl) && !_.isNull(sslcrl);
+ },
+ },{
+ id: 'sslcompression', label: gettext('SSL compression?'), type: 'switch',
+ mode: ['properties'], group: gettext('SSL'),
+ deps: ['sslmode'],
+ visible: function(state) {
+ return _.indexOf(obj.SSL_MODES, state.sslmode) != -1;
+ },
+ },
+ {
+ id: 'copy_data_after_refresh', label: gettext('Copy data?'),
+ type: 'switch', mode: ['edit'],
+ group: gettext('With'),
+ readonly: obj.isRefresh, deps :['refresh_pub'],
+ helpMessage: gettext('Specifies whether the existing data in the publications that are being subscribed to should be copied once the replication starts.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'copy_data', label: gettext('Copy data?'),
+ type: 'switch', mode: ['create'],
+ group: gettext('With'),
+ readonly: obj.isConnect, deps :['connect'],
+ helpMessage: gettext('Specifies whether the existing data in the publications that are being subscribed to should be copied once the replication starts.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'create_slot', label: gettext('Create slot?'),
+ type: 'switch', mode: ['create'],
+ group: gettext('With'),
+ disabled: obj.isSameDB,
+ readonly: obj.isConnect, deps :['connect', 'host', 'port'],
+ helpMessage: gettext('Specifies whether the command should create the replication slot on the publisher.This field will be disabled and set to false if subscription connects to same database.Otherwise, the CREATE SUBSCRIPTION call will hang.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'enabled', label: gettext('Enabled?'),
+ type: 'switch', mode: ['create','edit', 'properties'],
+ group: gettext('With'),
+ readonly: obj.isConnect, deps :['connect'],
+ helpMessage: gettext('Specifies whether the subscription should be actively replicating, or whether it should be just setup but not started yet.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'refresh_pub', label: gettext('Refresh publication?'),
+ type: 'switch', mode: ['edit'],
+ group: gettext('With'),
+ helpMessage: gettext('Fetch missing table information from publisher.'),
+ helpMessageMode: ['edit', 'create'],
+ deps:['enabled'], disabled: function(state){
+ if (state.enabled)
+ return false;
+ state.refresh_pub = false;
+ state.copy_data_after_refresh = false;
+ return true;
+ }, depChange: (state)=>{
+ let copy_data_after_refresh = false;
+ if (state.refresh_pub && !state.copy_data_after_refresh) {
+ copy_data_after_refresh = true;
+ }
+ state.copy_data_after_refresh = copy_data_after_refresh;
+ },
+ },{
+ id: 'connect', label: gettext('Connect?'),
+ type: 'switch', mode: ['create'],
+ group: gettext('With'),
+ disabled: obj.isDisable, deps:['enabled', 'create_slot', 'copy_data'],
+ helpMessage: gettext('Specifies whether the CREATE SUBSCRIPTION should connect to the publisher at all. Setting this to false will change default values of enabled, create_slot and copy_data to false.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'slot_name', label: gettext('Slot name'),
+ type: 'text', mode: ['create','edit', 'properties'],
+ group: gettext('With'),
+ helpMessage: gettext('Name of the replication slot to use. The default behavior is to use the name of the subscription for the slot name.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'sync', label: gettext('Synchronous commit'), control: 'select2', deps:['event'],
+ group: gettext('With'), type: 'select',
+ helpMessage: gettext('The value of this parameter overrides the synchronous_commit setting. The default value is off.'),
+ helpMessageMode: ['edit', 'create'],
+ controlProps: {
+ width: '100%',
+ allowClear: false,
+ },
+ options:[
+ {label: 'local', value: 'local'},
+ {label: 'remote_write', value: 'remote_write'},
+ {label: 'remote_apply', value: 'remote_apply'},
+ {label: 'on', value: 'on'},
+ {label: 'off', value: 'off'},
+ ],
+ },
+ {
+ id: 'streaming',
+ label: gettext('Streaming'),
+ cell: 'text',
+ group: gettext('With'), mode: ['create', 'edit', 'properties'],
+ type: ()=>{
+ let options = [
+ {
+ 'label': gettext('On'),
+ value: true,
+ },
+ {
+ 'label': gettext('Off'),
+ value: false,
+ }
+ ];
+
+ if (obj.version >= 160000) {
+ options.push({
+ 'label': gettext('Parallel'),
+ value: 'parallel',
+ });
+ }
+
+ return {
+ type: 'toggle',
+ options: options,
+ };
+ },
+ min_version: 140000,
+ helpMessage: gettext('Specifies whether to enable streaming of in-progress transactions for this subscription. By default, all transactions are fully decoded on the publisher and only then sent to the subscriber as a whole.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'binary', label: gettext('Binary?'),
+ type: 'switch', mode: ['create', 'edit', 'properties'],
+ group: gettext('With'),
+ min_version: 140000,
+ helpMessage: gettext('Specifies whether the subscription will request the publisher to send the data in binary format (as opposed to text). Even when this option is enabled, only data types having binary send and receive functions will be transferred in binary.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'two_phase', label: gettext('Two phase?'),
+ type: 'switch', mode: ['create', 'properties'],
+ group: gettext('With'),
+ min_version: 150000,
+ helpMessage: gettext('Specifies whether two-phase commit is enabled for this subscription.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'disable_on_error', label: gettext('Disable on error?'),
+ type: 'switch', mode: ['create', 'edit', 'properties'],
+ group: gettext('With'),
+ min_version: 150000,
+ helpMessage: gettext('Specifies whether the subscription should be automatically disabled if any errors are detected by subscription workers during data replication from the publisher.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'run_as_owner', label: gettext('Run as owner?'),
+ type: 'switch', mode: ['create', 'properties'],
+ group: gettext('With'),
+ min_version: 160000,
+ helpMessage: gettext('If true, all replication actions are performed as the subscription owner. If false, replication workers will perform actions on each table as the owner of that table.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'password_required', label: gettext('Password required?'),
+ type: 'switch', mode: ['create', 'edit', 'properties'],
+ group: gettext('With'),
+ min_version: 160000,
+ helpMessage: gettext('Specifies whether connections to the publisher made as a result of this subscription must use password authentication. Only superusers can set this value to false.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ {
+ id: 'origin', label: gettext('Origin'),
+ type: 'select', mode: ['create', 'edit', 'properties'],
+ group: gettext('With'),
+ controlProps: {
+ allowClear: false,
+ },
+ options: [
+ {label: gettext('none'), value: 'none'},
+ {label: gettext('any'), value: 'any'},
+ ],
+ min_version: 160000,
+ helpMessage: gettext('Specifies whether the subscription will request the publisher to only send changes that do not have an origin or send changes regardless of origin. Setting origin to none means that the subscription will request the publisher to only send changes that do not have an origin. Setting origin to any means that the publisher sends changes regardless of their origin.'),
+ helpMessageMode: ['edit', 'create'],
+ },
+ ];
+ }
+
+ validate(state, setError) {
+ let errmsg = null;
+ errmsg = gettext('Either Host name, Address must be specified.');
+ if(isEmptyString(state.host)) {
+ setError('host', errmsg);
+ return true;
+ } else {
+ setError('host', null);
+ }
+ if(isEmptyString(state.username)) {
+ errmsg = gettext('Username must be specified.');
+ setError('username', errmsg);
+ return true;
+ } else {
+ setError('username', null);
+ }
+
+ if(isEmptyString(state.port)) {
+ errmsg = gettext('Port must be specified.');
+ setError('port', errmsg);
+ return true;
+ } else {
+ setError('port', null);
+ }
+
+ if(isEmptyString(state.pub)) {
+ errmsg = gettext('Publication must be specified.');
+ setError('pub', errmsg);
+ return true;
+ } else {
+ setError('pub', null);
+ }
+
+ return false;
+ }
+
+}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..154d602df58b89c417dda3ba2a5cc935f21a5eba
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/create.sql
@@ -0,0 +1,24 @@
+{% if data.copy_data is defined or data.create_slot is defined or data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_enabled = 'enabled' %}
+{% endif %}
+{% if data.create_slot is defined or data.slot_name is defined %}
+{% set add_semicolon_after_copy_data = 'copy_data' %}
+{% endif %}
+{% if data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_create_slot = 'create_slot' %}
+{% endif %}
+{% if data.sync is defined %}
+{% set add_semicolon_after_slot_name = 'slot_name' %}
+{% endif %}
+
+CREATE SUBSCRIPTION {{ conn|qtIdent(data.name) }}
+{% if data.host or data.port or data.username or data.password or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl%}
+ CONNECTION '{% if data.host %}host={{data.host}}{% endif %}{% if data.port %} port={{ data.port }}{% endif %}{% if data.username %} user={{ data.username }}{% endif %}{% if data.db %} dbname={{ data.db }}{% endif %}{% if data.connect_timeout %} connect_timeout={{ data.connect_timeout }}{% endif %}{% if data.passfile %} passfile={{ data.passfile }}{% endif %}{% if data.password %} {% if dummy %}password=xxxxxx{% else %}password={{ data.password}}{% endif %}{% endif %}{% if data.sslmode %} sslmode={{ data.sslmode }}{% endif %}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}'
+{% endif %}
+{% if data.pub %}
+ PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %}
+{% endif %}
+
+ WITH ({% if data.connect is defined %}connect = {{ data.connect|lower}}, {% endif %}enabled = {{ data.enabled|lower}}, {% if data.copy_data is defined %}copy_data = {{ data.copy_data|lower}}{% if add_semicolon_after_copy_data == 'copy_data' %}, {% endif %}{% endif %}
+{% if data.create_slot is defined %}create_slot = {{ data.create_slot|lower }}{% if add_semicolon_after_create_slot == 'create_slot' %}, {% endif %}{% endif %}
+{% if data.slot_name is defined and data.slot_name != ''%}slot_name = {{ data.slot_name }}{% if add_semicolon_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync %}synchronous_commit = '{{ data.sync }}', {% endif %}binary = {{ data.binary|lower}}, streaming = '{{ data.streaming}}');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..e78722cd0a415a6775aa1ef436bddd84d1e3efc1
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/properties.sql
@@ -0,0 +1,29 @@
+SELECT sub.oid as oid,
+ subname as name,
+ subpublications as pub,
+ subpublications as proppub,
+ sub.subsynccommit as sync,
+ pga.rolname as subowner,
+ subslotname as slot_name,
+ subenabled as enabled,
+ subbinary as binary,
+ substream as streaming,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,' port',1), '=',2) as host,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'port=',2), ' ',1) as port,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'user=',2), ' ',1) as username,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'dbname=',2), ' ',1) as db,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'connect_timeout=',2), ' ',1) as connect_timeout,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'passfile=',2), ' ',1) as passfile,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslmode=',2), ' ',1) as sslmode,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcompression=',2), ' ',1) as sslcompression,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcert=',2), ' ',1) as sslcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslkey=',2), ' ',1) as sslkey,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslrootcert=',2), ' ',1) as sslrootcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcrl=',2), ' ',1) as sslcrl
+FROM pg_catalog.pg_subscription sub join pg_catalog.pg_roles pga on sub.subowner= pga.oid
+WHERE
+{% if subid %}
+ sub.oid = {{ subid }};
+{% else %}
+ sub.subdbid = {{ did }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..fbc647cfb36b7a0a39280b3f979743bb9691d438
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/14_plus/update.sql
@@ -0,0 +1,65 @@
+{% if data.sync is defined %}
+{% set add_comma_after_slot_name = 'slot_name' %}
+{% endif %}
+{% if data.binary is defined or data.streaming is defined %}
+{% set add_comma_after_sync = 'sync' %}
+{% endif %}
+{% if data.streaming is defined %}
+{% set add_comma_after_binary = 'binary' %}
+{% endif %}
+{#####################################################}
+{## Change owner of subscription ##}
+{#####################################################}
+{% if data.subowner and data.subowner != o_data.subowner %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ OWNER TO {{ data.subowner }};
+
+{% endif %}
+{### Disable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} DISABLE;
+{% endif %}
+
+{% endif %}
+{### Alter parameters of subscription ###}
+{% if (data.slot_name is defined and data.slot_name != o_data.slot_name) or (data.sync is defined and data.sync != o_data.sync) or (data.binary is defined and data.binary!=o_data.binary) or (data.streaming is defined and data.streaming!=o_data.streaming) %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET ({% if data.slot_name is defined and data.slot_name != o_data.slot_name %}slot_name = {{ data.slot_name }}{% if add_comma_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync is defined and data.sync != o_data.sync %}synchronous_commit = '{{ data.sync }}'{% if add_comma_after_sync == 'sync' %}, {% endif %}{% endif %}{% if data.binary is defined and data.binary!=o_data.binary %}binary = {{ data.binary|lower}}{% if add_comma_after_binary == 'binary' %}, {% endif %}{% endif %}{% if data.streaming is defined and data.streaming!=o_data.streaming %}streaming = '{{ data.streaming}}'{% endif %});
+
+{% endif %}
+{### Enable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} ENABLE;
+{% endif %}
+
+{% endif %}
+{### Refresh publication ###}
+{% if data.refresh_pub %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ REFRESH PUBLICATION{% if not data.copy_data_after_refresh %} WITH (copy_data = false){% else %} WITH (copy_data = true){% endif %};
+
+{% endif %}
+{### Alter publication of subscription ###}
+{% if data.pub%}
+{% if data.pub and not data.refresh_pub and not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %} WITH (refresh = false);
+{% else %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %};
+{% endif %}
+
+{% endif %}
+{### Alter subscription connection info ###}
+{% if data.host or data.port or data.username or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ CONNECTION 'host={{ o_data.host}} port={{ o_data.port }} user={{ o_data.username }} dbname={{ o_data.db }} connect_timeout={{ o_data.connect_timeout }} {% if data.passfile %} passfile={{ o_data.passfile }}{% endif %} sslmode={{ o_data.sslmode }}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}';
+{% endif %}
+{### Alter subscription name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4e419370935e2cad28d180d66bd287117c116d3d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/create.sql
@@ -0,0 +1,24 @@
+{% if data.copy_data is defined or data.create_slot is defined or data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_enabled = 'enabled' %}
+{% endif %}
+{% if data.create_slot is defined or data.slot_name is defined %}
+{% set add_semicolon_after_copy_data = 'copy_data' %}
+{% endif %}
+{% if data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_create_slot = 'create_slot' %}
+{% endif %}
+{% if data.sync is defined %}
+{% set add_semicolon_after_slot_name = 'slot_name' %}
+{% endif %}
+
+CREATE SUBSCRIPTION {{ conn|qtIdent(data.name) }}
+{% if data.host or data.port or data.username or data.password or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl%}
+ CONNECTION '{% if data.host %}host={{data.host}}{% endif %}{% if data.port %} port={{ data.port }}{% endif %}{% if data.username %} user={{ data.username }}{% endif %}{% if data.db %} dbname={{ data.db }}{% endif %}{% if data.connect_timeout %} connect_timeout={{ data.connect_timeout }}{% endif %}{% if data.passfile %} passfile={{ data.passfile }}{% endif %}{% if data.password %} {% if dummy %}password=xxxxxx{% else %}password={{ data.password}}{% endif %}{% endif %}{% if data.sslmode %} sslmode={{ data.sslmode }}{% endif %}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}'
+{% endif %}
+{% if data.pub %}
+ PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %}
+{% endif %}
+
+ WITH ({% if data.connect is defined %}connect = {{ data.connect|lower}}, {% endif %}enabled = {{ data.enabled|lower}}, {% if data.copy_data is defined %}copy_data = {{ data.copy_data|lower}}{% if add_semicolon_after_copy_data == 'copy_data' %}, {% endif %}{% endif %}
+{% if data.create_slot is defined %}create_slot = {{ data.create_slot|lower }}{% if add_semicolon_after_create_slot == 'create_slot' %}, {% endif %}{% endif %}
+{% if data.slot_name is defined and data.slot_name != ''%}slot_name = {{ data.slot_name }}{% if add_semicolon_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync %}synchronous_commit = '{{ data.sync }}', {% endif %}binary = {{ data.binary|lower}}, streaming = '{{ data.streaming}}', two_phase = {{ data.two_phase|lower}}, disable_on_error = {{ data.disable_on_error|lower}});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..82e82731ef1ed2a932c6d4227e954f0a68c0c9c0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/properties.sql
@@ -0,0 +1,31 @@
+SELECT sub.oid as oid,
+ subname as name,
+ subpublications as pub,
+ subpublications as proppub,
+ sub.subsynccommit as sync,
+ pga.rolname as subowner,
+ subslotname as slot_name,
+ subenabled as enabled,
+ subbinary as binary,
+ substream as streaming,
+ subtwophasestate as two_phase,
+ subdisableonerr as disable_on_error,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,' port',1), '=',2) as host,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'port=',2), ' ',1) as port,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'user=',2), ' ',1) as username,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'dbname=',2), ' ',1) as db,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'connect_timeout=',2), ' ',1) as connect_timeout,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'passfile=',2), ' ',1) as passfile,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslmode=',2), ' ',1) as sslmode,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcompression=',2), ' ',1) as sslcompression,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcert=',2), ' ',1) as sslcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslkey=',2), ' ',1) as sslkey,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslrootcert=',2), ' ',1) as sslrootcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcrl=',2), ' ',1) as sslcrl
+FROM pg_catalog.pg_subscription sub join pg_catalog.pg_roles pga on sub.subowner= pga.oid
+WHERE
+{% if subid %}
+ sub.oid = {{ subid }};
+{% else %}
+ sub.subdbid = {{ did }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ced4aa84138d129818f85cb0a0e460dbf0942b8b
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/15_plus/update.sql
@@ -0,0 +1,68 @@
+{% if data.sync is defined %}
+{% set add_comma_after_slot_name = 'slot_name' %}
+{% endif %}
+{% if data.binary is defined or data.streaming is defined or data.disable_on_error is defined %}
+{% set add_comma_after_sync = 'sync' %}
+{% endif %}
+{% if data.streaming is defined or data.disable_on_error is defined %}
+{% set add_comma_after_binary = 'binary' %}
+{% endif %}
+{% if data.disable_on_error is defined %}
+{% set add_comma_after_streaming = 'streaming' %}
+{% endif %}
+{#####################################################}
+{## Change owner of subscription ##}
+{#####################################################}
+{% if data.subowner and data.subowner != o_data.subowner %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ OWNER TO {{ data.subowner }};
+
+{% endif %}
+{### Disable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} DISABLE;
+{% endif %}
+
+{% endif %}
+{### Alter parameters of subscription ###}
+{% if (data.slot_name is defined and data.slot_name != o_data.slot_name) or (data.sync is defined and data.sync != o_data.sync) or (data.binary is defined and data.binary!=o_data.binary) or (data.streaming is defined and data.streaming!=o_data.streaming) or (data.disable_on_error is defined and data.disable_on_error!=o_data.disable_on_error) %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET ({% if data.slot_name is defined and data.slot_name != o_data.slot_name %}slot_name = {{ data.slot_name }}{% if add_comma_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync is defined and data.sync != o_data.sync %}synchronous_commit = '{{ data.sync }}'{% if add_comma_after_sync == 'sync' %}, {% endif %}{% endif %}{% if data.binary is defined and data.binary!=o_data.binary %}binary = {{ data.binary|lower}}{% if add_comma_after_binary == 'binary' %}, {% endif %}{% endif %}{% if data.streaming is defined and data.streaming!=o_data.streaming %}streaming = '{{ data.streaming}}'{% if add_comma_after_streaming == 'streaming' %}, {% endif %}{% endif %}{% if data.disable_on_error is defined and data.disable_on_error!=o_data.disable_on_error %}disable_on_error = {{ data.disable_on_error|lower}}{% endif %});
+
+{% endif %}
+{### Enable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} ENABLE;
+{% endif %}
+
+{% endif %}
+{### Refresh publication ###}
+{% if data.refresh_pub %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ REFRESH PUBLICATION{% if not data.copy_data_after_refresh %} WITH (copy_data = false){% else %} WITH (copy_data = true){% endif %};
+
+{% endif %}
+{### Alter publication of subscription ###}
+{% if data.pub%}
+{% if data.pub and not data.refresh_pub and not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %} WITH (refresh = false);
+{% else %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %};
+{% endif %}
+
+{% endif %}
+{### Alter subscription connection info ###}
+{% if data.host or data.port or data.username or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ CONNECTION 'host={{ o_data.host}} port={{ o_data.port }} user={{ o_data.username }} dbname={{ o_data.db }} connect_timeout={{ o_data.connect_timeout }} {% if data.passfile %} passfile={{ o_data.passfile }}{% endif %} sslmode={{ o_data.sslmode }}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}';
+{% endif %}
+{### Alter subscription name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..10694aa992bac3ab40351c5c1cde2dacae4d2658
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/create.sql
@@ -0,0 +1,24 @@
+{% if data.copy_data is defined or data.create_slot is defined or data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_enabled = 'enabled' %}
+{% endif %}
+{% if data.create_slot is defined or data.slot_name is defined %}
+{% set add_semicolon_after_copy_data = 'copy_data' %}
+{% endif %}
+{% if data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_create_slot = 'create_slot' %}
+{% endif %}
+{% if data.sync is defined %}
+{% set add_semicolon_after_slot_name = 'slot_name' %}
+{% endif %}
+
+CREATE SUBSCRIPTION {{ conn|qtIdent(data.name) }}
+{% if data.host or data.port or data.username or data.password or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl%}
+ CONNECTION '{% if data.host %}host={{data.host}}{% endif %}{% if data.port %} port={{ data.port }}{% endif %}{% if data.username %} user={{ data.username }}{% endif %}{% if data.db %} dbname={{ data.db }}{% endif %}{% if data.connect_timeout %} connect_timeout={{ data.connect_timeout }}{% endif %}{% if data.passfile %} passfile={{ data.passfile }}{% endif %}{% if data.password %} {% if dummy %}password=xxxxxx{% else %}password={{ data.password}}{% endif %}{% endif %}{% if data.sslmode %} sslmode={{ data.sslmode }}{% endif %}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}'
+{% endif %}
+{% if data.pub %}
+ PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %}
+{% endif %}
+
+ WITH ({% if data.connect is defined %}connect = {{ data.connect|lower}}, {% endif %}enabled = {{ data.enabled|lower}}, {% if data.copy_data is defined %}copy_data = {{ data.copy_data|lower}}{% if add_semicolon_after_copy_data == 'copy_data' %}, {% endif %}{% endif %}
+{% if data.create_slot is defined %}create_slot = {{ data.create_slot|lower }}{% if add_semicolon_after_create_slot == 'create_slot' %}, {% endif %}{% endif %}
+{% if data.slot_name is defined and data.slot_name != ''%}slot_name = {{ data.slot_name }}{% if add_semicolon_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync %}synchronous_commit = '{{ data.sync }}', {% endif %}binary = {{ data.binary|lower}}, streaming = '{{ data.streaming}}', two_phase = {{ data.two_phase|lower}}, disable_on_error = {{ data.disable_on_error|lower}}, run_as_owner = {{ data.run_as_owner|lower}}, password_required = {{ data.password_required|lower}}, origin = '{{ data.origin}}');
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0be739d48c2402b97be883c3ae8cffe0b09bd607
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/properties.sql
@@ -0,0 +1,34 @@
+SELECT sub.oid as oid,
+ subname as name,
+ subpublications as pub,
+ subpublications as proppub,
+ sub.subsynccommit as sync,
+ pga.rolname as subowner,
+ subslotname as slot_name,
+ subenabled as enabled,
+ subbinary as binary,
+ substream as streaming,
+ subtwophasestate as two_phase,
+ subdisableonerr as disable_on_error,
+ subpasswordrequired as password_required,
+ subrunasowner as run_as_owner,
+ suborigin as origin,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,' port',1), '=',2) as host,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'port=',2), ' ',1) as port,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'user=',2), ' ',1) as username,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'dbname=',2), ' ',1) as db,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'connect_timeout=',2), ' ',1) as connect_timeout,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'passfile=',2), ' ',1) as passfile,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslmode=',2), ' ',1) as sslmode,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcompression=',2), ' ',1) as sslcompression,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcert=',2), ' ',1) as sslcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslkey=',2), ' ',1) as sslkey,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslrootcert=',2), ' ',1) as sslrootcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcrl=',2), ' ',1) as sslcrl
+FROM pg_catalog.pg_subscription sub join pg_catalog.pg_roles pga on sub.subowner= pga.oid
+WHERE
+{% if subid %}
+ sub.oid = {{ subid }};
+{% else %}
+ sub.subdbid = {{ did }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5fa8b0416dac728094f78ff7c9f931d58e96359f
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/16_plus/update.sql
@@ -0,0 +1,77 @@
+{% if data.sync is defined %}
+{% set add_comma_after_slot_name = 'slot_name' %}
+{% endif %}
+{% if data.binary is defined or data.streaming is defined or data.disable_on_error is defined or data.run_as_owner is defined or data.password_required is defined or data.origin is defined %}
+{% set add_comma_after_sync = 'sync' %}
+{% endif %}
+{% if data.streaming is defined or data.disable_on_error is defined or data.run_as_owner is defined or data.password_required is defined or data.origin is defined %}
+{% set add_comma_after_binary = 'binary' %}
+{% endif %}
+{% if data.disable_on_error is defined or data.run_as_owner is defined or data.password_required is defined or data.origin is defined %}
+{% set add_comma_after_streaming = 'streaming' %}
+{% endif %}
+{% if data.run_as_owner is defined or data.password_required is defined or data.origin is defined %}
+{% set add_comma_after_disable_on_error = 'disable_on_error' %}
+{% endif %}
+{% if data.password_required is defined or data.origin is defined %}
+{% set add_comma_after_run_as_owner = 'run_as_owner' %}
+{% endif %}
+{% if data.origin is defined %}
+{% set add_comma_after_password_required = 'password_required' %}
+{% endif %}
+{#####################################################}
+{## Change owner of subscription ##}
+{#####################################################}
+{% if data.subowner and data.subowner != o_data.subowner %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ OWNER TO {{ data.subowner }};
+
+{% endif %}
+{### Disable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} DISABLE;
+{% endif %}
+
+{% endif %}
+{### Alter parameters of subscription ###}
+{% if (data.slot_name is defined and data.slot_name != o_data.slot_name) or (data.sync is defined and data.sync != o_data.sync) or (data.binary is defined and data.binary!=o_data.binary) or (data.streaming is defined and data.streaming!=o_data.streaming) or (data.disable_on_error is defined and data.disable_on_error!=o_data.disable_on_error) or (data.run_as_owner is defined and data.run_as_owner!=o_data.run_as_owner) or (data.password_required is defined and data.password_required!=o_data.password_required) or (data.origin is defined and data.origin!=o_data.origin) %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET ({% if data.slot_name is defined and data.slot_name != o_data.slot_name %}slot_name = {{ data.slot_name }}{% if add_comma_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync is defined and data.sync != o_data.sync %}synchronous_commit = '{{ data.sync }}'{% if add_comma_after_sync == 'sync' %}, {% endif %}{% endif %}{% if data.binary is defined and data.binary!=o_data.binary %}binary = {{ data.binary|lower}}{% if add_comma_after_binary == 'binary' %}, {% endif %}{% endif %}{% if data.streaming is defined and data.streaming!=o_data.streaming %}streaming = '{{ data.streaming }}'{% if add_comma_after_streaming == 'streaming' %}, {% endif %}{% endif %}{% if data.disable_on_error is defined and data.disable_on_error!=o_data.disable_on_error %}disable_on_error = {{ data.disable_on_error|lower}}{% if add_comma_after_disable_on_error == 'disable_on_error' %}, {% endif %}{% endif %}{% if data.run_as_owner is defined and data.run_as_owner!=o_data.run_as_owner %}run_as_owner = {{ data.run_as_owner|lower}}{% if add_comma_after_run_as_owner == 'run_as_owner' %}, {% endif %}{% endif %}{% if data.password_required is defined and data.password_required!=o_data.password_required %}password_required = {{ data.password_required|lower}}{% if add_comma_after_password_required == 'password_required' %}, {% endif %}{% endif %}{% if data.origin is defined and data.origin!=o_data.origin %}origin = '{{ data.origin }}'{% endif %});
+
+{% endif %}
+{### Enable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} ENABLE;
+{% endif %}
+
+{% endif %}
+{### Refresh publication ###}
+{% if data.refresh_pub %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ REFRESH PUBLICATION{% if not data.copy_data_after_refresh %} WITH (copy_data = false){% else %} WITH (copy_data = true){% endif %};
+
+{% endif %}
+{### Alter publication of subscription ###}
+{% if data.pub%}
+{% if data.pub and not data.refresh_pub and not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %} WITH (refresh = false);
+{% else %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %};
+{% endif %}
+
+{% endif %}
+{### Alter subscription connection info ###}
+{% if data.host or data.port or data.username or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ CONNECTION 'host={{ o_data.host}} port={{ o_data.port }} user={{ o_data.username }} dbname={{ o_data.db }} connect_timeout={{ o_data.connect_timeout }} {% if data.passfile %} passfile={{ o_data.passfile }}{% endif %} sslmode={{ o_data.sslmode }}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}';
+{% endif %}
+{### Alter subscription name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/count.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/count.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4bac35de1206364bcab516a4f286e00820a47dda
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/count.sql
@@ -0,0 +1,3 @@
+SELECT COUNT(*)
+FROM pg_catalog.pg_subscription sub
+WHERE sub.subdbid = {{ did }}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/create.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/create.sql
new file mode 100644
index 0000000000000000000000000000000000000000..46029421a767f11a9a75dd56244044cf93813dd5
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/create.sql
@@ -0,0 +1,24 @@
+{% if data.copy_data is defined or data.create_slot is defined or data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_enabled = 'enabled' %}
+{% endif %}
+{% if data.create_slot is defined or data.slot_name is defined %}
+{% set add_semicolon_after_copy_data = 'copy_data' %}
+{% endif %}
+{% if data.slot_name is defined or data.sync is defined %}
+{% set add_semicolon_after_create_slot = 'create_slot' %}
+{% endif %}
+{% if data.sync is defined %}
+{% set add_semicolon_after_slot_name = 'slot_name' %}
+{% endif %}
+
+CREATE SUBSCRIPTION {{ conn|qtIdent(data.name) }}
+{% if data.host or data.port or data.username or data.password or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl%}
+ CONNECTION '{% if data.host %}host={{data.host}}{% endif %}{% if data.port %} port={{ data.port }}{% endif %}{% if data.username %} user={{ data.username }}{% endif %}{% if data.db %} dbname={{ data.db }}{% endif %}{% if data.connect_timeout %} connect_timeout={{ data.connect_timeout }}{% endif %}{% if data.passfile %} passfile={{ data.passfile }}{% endif %}{% if data.password %} {% if dummy %}password=xxxxxx{% else %}password={{ data.password}}{% endif %}{% endif %}{% if data.sslmode %} sslmode={{ data.sslmode }}{% endif %}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}'
+{% endif %}
+{% if data.pub %}
+ PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %}
+{% endif %}
+
+ WITH ({% if data.connect is defined %}connect = {{ data.connect|lower}}, {% endif %}enabled = {{ data.enabled|lower}}, {% if data.copy_data is defined %}copy_data = {{ data.copy_data|lower}}{% if add_semicolon_after_copy_data == 'copy_data' %}, {% endif %}{% endif %}
+{% if data.create_slot is defined %}create_slot = {{ data.create_slot|lower }}{% if add_semicolon_after_create_slot == 'create_slot' %}, {% endif %}{% endif %}
+{% if data.slot_name is defined and data.slot_name != ''%}slot_name = {{ data.slot_name }}{% if add_semicolon_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync %}synchronous_commit = '{{ data.sync }}'{% endif %});
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/delete.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/delete.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0259fa019a310705dea9fa887b192f5dd351bfc0
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/delete.sql
@@ -0,0 +1,8 @@
+{# ============= Get the subscription name using oid ============= #}
+{% if subid %}
+ SELECT subname FROM pg_catalog.pg_subscription WHERE oid = {{subid}}::oid;
+{% endif %}
+{# ============= Drop the language ============= #}
+{% if subname %}
+DROP SUBSCRIPTION IF EXISTS {{ conn|qtIdent(subname) }}{% if cascade %} CASCADE{% endif%};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/dependencies.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/dependencies.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5ea81d9c28d6d4be83eaaf3b96037ee8e90ce926
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/dependencies.sql
@@ -0,0 +1,2 @@
+SELECT subpublications AS pub FROM pg_catalog.pg_subscription
+WHERE subname = '{{subname}}';
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/get_position.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/get_position.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5ddf72a3f9d3e3ce340f829f366d5fd02668568d
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/get_position.sql
@@ -0,0 +1 @@
+SELECT oid, subname AS name FROM pg_catalog.pg_subscription WHERE subname = '{{ subname }}' and subdbid={{did}} :: oid;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ccda2158efd5eec68eeaa3e7c866cc3bcd5fc0df
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/nodes.sql
@@ -0,0 +1,11 @@
+SELECT oid, sub.subname AS name FROM pg_catalog.pg_subscription sub
+WHERE
+{% if subid %}
+ sub.oid = {{ subid }};
+{% else %}
+ sub.subdbid = {{ did }}
+{% endif %}
+{% if schema_diff %}
+ AND CASE WHEN (SELECT COUNT(*) FROM pg_catalog.pg_depend
+ WHERE objid = oid AND deptype = 'e') > 0 THEN FALSE ELSE TRUE END
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a416821da18d837b7661c2f82d4fbef6f76e13a9
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/properties.sql
@@ -0,0 +1,27 @@
+SELECT sub.oid as oid,
+ subname as name,
+ subpublications as pub,
+ subpublications as proppub,
+ sub.subsynccommit as sync,
+ pga.rolname as subowner,
+ subslotname as slot_name,
+ subenabled as enabled,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,' port',1), '=',2) as host,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'port=',2), ' ',1) as port,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'user=',2), ' ',1) as username,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'dbname=',2), ' ',1) as db,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'connect_timeout=',2), ' ',1) as connect_timeout,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'passfile=',2), ' ',1) as passfile,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslmode=',2), ' ',1) as sslmode,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcompression=',2), ' ',1) as sslcompression,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcert=',2), ' ',1) as sslcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslkey=',2), ' ',1) as sslkey,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslrootcert=',2), ' ',1) as sslrootcert,
+ pg_catalog.SPLIT_PART(pg_catalog.SPLIT_PART(subconninfo,'sslcrl=',2), ' ',1) as sslcrl
+FROM pg_catalog.pg_subscription sub join pg_catalog.pg_roles pga on sub.subowner= pga.oid
+WHERE
+{% if subid %}
+ sub.oid = {{ subid }};
+{% else %}
+ sub.subdbid = {{ did }};
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..0289aee4ad190374a330248dc57396ef0ccf4d24
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/stats.sql
@@ -0,0 +1,14 @@
+SELECT
+ stat.subname AS {{ conn|qtIdent(_('Subscription name')) }},
+ stat.latest_end_time AS {{ conn|qtIdent(_('Latest end time')) }},
+ stat.latest_end_lsn AS {{ conn|qtIdent(_('Latest end lsn')) }},
+ stat.last_msg_receipt_time AS {{ conn|qtIdent(_('Last message receipt')) }},
+ stat.last_msg_send_time AS {{ conn|qtIdent(_('Last message send time'))}}
+FROM pg_catalog.pg_stat_subscription stat
+LEFT JOIN pg_subscription sub ON sub.subname = stat.subname
+{% if subid %}
+ WHERE stat.subid = {{ subid }};
+{% else %}
+ WHERE sub.subdbid = {{ did }}
+{% endif %}
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/update.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/update.sql
new file mode 100644
index 0000000000000000000000000000000000000000..cbd2c43ca7895de9f542ff0efc50deb934e32afd
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/subscriptions/templates/subscriptions/sql/default/update.sql
@@ -0,0 +1,65 @@
+{% if data.sync is defined %}
+{% set add_semicolon_after_slot_name = 'slot_name' %}
+{% endif %}
+{#####################################################}
+{## Change owner of subscription ##}
+{#####################################################}
+{% if data.subowner and data.subowner != o_data.subowner %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ OWNER TO {{ data.subowner }};
+
+{% endif %}
+{### Disable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} DISABLE;
+{% endif %}
+
+{% endif %}
+{### Alter slot name of subscription ###}
+{% if data.slot_name is defined or data.sync %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET ({% if data.slot_name is defined and data.slot_name != o_data.slot_name %}slot_name = {{ data.slot_name }}{% if add_semicolon_after_slot_name == 'slot_name' %}, {% endif %}{% endif %}{% if data.sync %}synchronous_commit = '{{ data.sync }}'{% endif %});
+
+{% endif %}
+{### Enable subscription ###}
+{% if data.enabled is defined and data.enabled != o_data.enabled %}
+{% if data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }} ENABLE;
+{% endif %}
+
+{% endif %}
+{### Refresh publication ###}
+{% if data.refresh_pub %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ REFRESH PUBLICATION{% if not data.copy_data_after_refresh %} WITH (copy_data = false){% else %} WITH (copy_data = true){% endif %};
+
+{% endif %}
+{### Alter publication of subscription ###}
+{% if data.pub%}
+{% if data.pub and not data.refresh_pub and not data.enabled %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %} WITH (refresh = false);
+{% else %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ SET PUBLICATION {% for pub in data.pub %}{% if loop.index != 1 %},{% endif %}{{ conn|qtIdent(pub) }}{% endfor %};
+{% endif %}
+
+{% endif %}
+{### Alter subscription connection info ###}
+{% if data.host or data.port or data.username or data.db or data.connect_timeout or data.passfile or data.sslmode or data.sslcompression or data.sslcert or data.sslkey or data.sslrootcert or data.sslcrl %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ CONNECTION 'host={{ o_data.host}} port={{ o_data.port }} user={{ o_data.username }} dbname={{ o_data.db }} connect_timeout={{ o_data.connect_timeout }} {% if data.passfile %} passfile={{ o_data.passfile }}{% endif %} sslmode={{ o_data.sslmode }}{% if data.sslcompression %} sslcompression={{ data.sslcompression }}{% endif %}{% if data.sslcert %} sslcert={{ data.sslcert }}{% endif %}{% if data.sslkey %} sslkey={{ data.sslkey }}{% endif %}{% if data.sslrootcert %} sslrootcert={{ data.sslrootcert }}{% endif %}{% if data.sslcrl %} sslcrl={{ data.sslcrl }}{% endif %}';
+{% endif %}
+{### Alter subscription name ###}
+{% if data.name and data.name != o_data.name %}
+ALTER SUBSCRIPTION {{ conn|qtIdent(o_data.name) }}
+ RENAME TO {{ conn|qtIdent(data.name) }};
+
+{% endif %}
+
+
+
+
+
+
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/get_variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/get_variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..468e1ddd2c570cc4b376df6ba0ed0839c9d6d696
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/get_variables.sql
@@ -0,0 +1,6 @@
+SELECT
+ rl.*, r.rolname AS user_name, db.datname as db_name
+FROM pg_catalog.pg_db_role_setting AS rl
+ LEFT JOIN pg_catalog.pg_roles AS r ON rl.setrole = r.oid
+ LEFT JOIN pg_catalog.pg_database AS db ON rl.setdatabase = db.oid
+WHERE setdatabase = {{did}}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/grant.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/grant.sql
new file mode 100644
index 0000000000000000000000000000000000000000..edb867a44d03cf0cfbf7e2cc47cb103793c4b2e2
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/grant.sql
@@ -0,0 +1,83 @@
+{#
+# CREATE DATABASE does not allow us to run any
+# other sql statements along with it, so we wrote
+# separate sql for rest alter sql statements here
+#}
+{% import 'macros/security.macros' as SECLABEL %}
+{% import 'macros/variable.macros' as VARIABLE %}
+{% import 'macros/privilege.macros' as PRIVILEGE %}
+{% import 'macros/default_privilege.macros' as DEFAULT_PRIVILEGE %}
+{% if data.comments %}
+COMMENT ON DATABASE {{ conn|qtIdent(data.name) }}
+ IS {{ data.comments|qtLiteral(conn) }};
+{% endif %}
+
+{# Change the security labels #}
+{% if data.seclabels %}
+{% for r in data.seclabels %}
+{{ SECLABEL.APPLY(conn, 'DATABASE', data.name, r.provider, r.label) }}
+{% endfor %}
+{% endif %}
+{# Variables/options #}
+{% if data.variables %}
+{% for var in data.variables %}
+{% if var.value == True %}
+{{ VARIABLE.APPLY(conn, data.name, var.role, var.name, 'on') }}
+{% elif var.value == False %}
+{{ VARIABLE.APPLY(conn, data.name, var.role, var.name, 'off') }}
+{% else %}
+{{ VARIABLE.APPLY(conn, data.name, var.role, var.name, var.value) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{# Privileges/ACLs #}
+{% if data.datacl %}
+{% for priv in data.datacl %}
+{{ PRIVILEGE.APPLY(conn, 'DATABASE', priv.grantee, data.name, priv.without_grant, priv.with_grant) }}
+{% endfor %}
+{% endif %}
+
+{# Default privileges/ACLs for tables #}
+{% if data.deftblacl %}
+{% for priv in data.deftblacl %}
+{% if priv.acltype == 'grant' %}
+{{ DEFAULT_PRIVILEGE.APPLY(conn, 'TABLES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.REMOVE(conn, 'TABLES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endif %}
+{% endfor %}
+
+{% endif %}
+{# Default privileges/ACLs for sequences #}
+{% if data.defseqacl %}
+{% for priv in data.defseqacl %}
+{% if priv.acltype == 'grant' %}
+{{ DEFAULT_PRIVILEGE.APPLY(conn, 'SEQUENCES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.REMOVE(conn, 'SEQUENCES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{# Default privileges/ACLs for functions #}
+{% if data.deffuncacl %}
+{% for priv in data.deffuncacl %}
+{% if priv.acltype == 'grant' %}
+{{ DEFAULT_PRIVILEGE.APPLY(conn, 'FUNCTIONS', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.REMOVE(conn, 'FUNCTIONS', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endif %}
+{% endfor %}
+{% endif %}
+
+{# Default privileges/ACLs for types #}
+{% if data.deftypeacl %}
+{% for priv in data.deftypeacl %}
+{% if priv.acltype == 'grant' %}
+{{ DEFAULT_PRIVILEGE.APPLY(conn, 'TYPES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% else %}
+{{ DEFAULT_PRIVILEGE.REMOVE(conn, 'TYPES', priv.grantee, priv.without_grant, priv.with_grant, priv.grantor) }}
+{% endif %}
+{% endfor %}
+{% endif %}
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/nodes.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/nodes.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4b751d4694f37a0971a2706f3c29555a8390e923
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/nodes.sql
@@ -0,0 +1,24 @@
+SELECT
+ db.oid as did, db.datname as name, ta.spcname as spcname, db.datallowconn,
+ db.datistemplate AS is_template,
+ pg_catalog.has_database_privilege(db.oid, 'CREATE') as cancreate, datdba as owner,
+ descr.description
+FROM
+ pg_catalog.pg_database db
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta ON db.dattablespace = ta.oid
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON (
+ db.oid=descr.objoid AND descr.classoid='pg_database'::regclass
+ )
+WHERE {% if did %}
+db.oid = {{ did|qtLiteral(conn) }}::OID
+{% endif %}
+{% if db_restrictions %}
+
+{% if did %}AND{% endif %}
+db.datname in ({{db_restrictions}})
+{% elif not did%}
+ {% if db_restrictions %} AND {%endif%}
+ db.oid > {{ last_system_oid }}::OID OR db.datname IN ('postgres', 'edb')
+{% endif %}
+
+ORDER BY datname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/properties.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/properties.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ef01388d020388d21e3310b064091575c36df748
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/properties.sql
@@ -0,0 +1,42 @@
+SELECT
+ db.oid AS did, db.oid, db.datname AS name, db.dattablespace AS spcoid,
+ spcname, datallowconn, pg_catalog.pg_encoding_to_char(encoding) AS encoding,
+ pg_catalog.pg_get_userbyid(datdba) AS datowner,
+ (select pg_catalog.current_setting('lc_collate')) as datcollate,
+ (select pg_catalog.current_setting('lc_ctype')) as datctype,
+ datconnlimit,
+ pg_catalog.has_database_privilege(db.oid, 'CREATE') AS cancreate,
+ pg_catalog.current_setting('default_tablespace') AS default_tablespace,
+ descr.description AS comments, db.datistemplate AS is_template,
+ {### Default ACL for Tables ###}
+ '' AS tblacl,
+ {### Default ACL for Sequnces ###}
+ '' AS seqacl,
+ {### Default ACL for Functions ###}
+ '' AS funcacl,
+ pg_catalog.array_to_string(datacl::text[], ', ') AS acl
+FROM pg_catalog.pg_database db
+ LEFT OUTER JOIN pg_catalog.pg_tablespace ta ON db.dattablespace=ta.OID
+ LEFT OUTER JOIN pg_catalog.pg_shdescription descr ON (
+ db.oid=descr.objoid AND descr.classoid='pg_database'::regclass
+ )
+WHERE
+{% if show_user_defined_templates is defined %}
+ db.datistemplate = {{show_user_defined_templates}} AND
+{% endif %}
+{% if did %}
+ db.oid = {{ did|qtLiteral(conn) }}::OID
+{% else %}
+ {% if name %}
+ db.datname = {{ name|qtLiteral(conn) }}::text
+ {% endif %}
+{% endif %}
+
+{% if db_restrictions %}
+ {% if did or name %}AND{% endif %}
+ db.datname in ({{db_restrictions}})
+{% elif not did and not name%}
+ db.oid > {{ last_system_oid }}::OID OR db.datname IN ('postgres', 'edb')
+{% endif %}
+
+ORDER BY datname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/stats.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/stats.sql
new file mode 100644
index 0000000000000000000000000000000000000000..287ebd94352fa9e61275cf7fb5745e0671ead0af
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/stats.sql
@@ -0,0 +1,26 @@
+SELECT
+ {% if not did %}db.datname AS {{ conn|qtIdent(_('Database')) }}, {% endif %}
+ pg_catalog.pg_database_size(db.datid) AS {{ conn|qtIdent(_('Size')) }},
+ numbackends AS {{ conn|qtIdent(_('Backends')) }},
+ xact_commit AS {{ conn|qtIdent(_('Xact committed')) }},
+ xact_rollback AS {{ conn|qtIdent(_('Xact rolled back')) }},
+ blks_read AS {{ conn|qtIdent(_('Blocks read')) }},
+ blks_hit AS {{ conn|qtIdent(_('Blocks hit')) }},
+ tup_returned AS {{ conn|qtIdent(_('Tuples returned')) }},
+ tup_fetched AS {{ conn|qtIdent(_('Tuples fetched')) }},
+ tup_inserted AS {{ conn|qtIdent(_('Tuples inserted')) }},
+ tup_updated AS {{ conn|qtIdent(_('Tuples updated')) }},
+ tup_deleted AS {{ conn|qtIdent(_('Tuples deleted')) }}
+FROM
+ pg_catalog.pg_stat_database db
+WHERE {% if did %}
+db.datid = {{ did|qtLiteral(conn) }}::OID{% else %}
+db.datid > {{ last_system_oid|qtLiteral(conn) }}::OID
+{% endif %}
+{% if db_restrictions %}
+
+AND
+db.datname in ({{db_restrictions}})
+{% endif %}
+
+ORDER BY db.datname;
diff --git a/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/variables.sql b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/variables.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ff30cb7055753a4587e8cd5e339c51611bf2ab74
--- /dev/null
+++ b/pgsql/pgAdmin 4/web/pgadmin/browser/server_groups/servers/databases/templates/databases/sql/default/variables.sql
@@ -0,0 +1,2 @@
+SELECT name, vartype, min_val, max_val, enumvals
+FROM pg_catalog.pg_settings WHERE context in ('user', 'superuser')