diff --git a/web/pgadmin/__init__.py b/web/pgadmin/__init__.py
index a1dc33c..74a3124 100644
--- a/web/pgadmin/__init__.py
+++ b/web/pgadmin/__init__.py
@@ -26,7 +26,7 @@ from flask_paranoid import Paranoid
 
 from pgadmin.utils import PgAdminModule, driver
 from pgadmin.utils.versioned_template_loader import VersionedTemplateLoader
-from pgadmin.utils.session import create_session_interface
+from pgadmin.utils.session import create_session_interface, pga_unauthorised
 from werkzeug.local import LocalProxy
 from werkzeug.utils import find_modules
 
@@ -352,6 +352,9 @@ def create_app(app_name=None):
 
     security.init_app(app, user_datastore)
 
+    # register custom unauthorised handler.
+    app.login_manager.unauthorized_handler(pga_unauthorised)
+
     app.session_interface = create_session_interface(app)
 
     # Make the Session more secure against XSS & CSRF when running in web mode
diff --git a/web/pgadmin/browser/server_groups/servers/__init__.py b/web/pgadmin/browser/server_groups/servers/__init__.py
index 89ae779..08d139e 100644
--- a/web/pgadmin/browser/server_groups/servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/__init__.py
@@ -202,6 +202,9 @@ class ServerModule(sg.ServerGroupPluginModule):
         """
         ServerType.register_preferences()
 
+    def get_exposed_url_endpoints(self):
+        return ['NODE-server.connect_id']
+
 
 class ServerMenuItem(MenuItem):
     def __init__(self, **kwargs):
diff --git a/web/pgadmin/static/js/sqleditor_utils.js b/web/pgadmin/static/js/sqleditor_utils.js
index 6e2ae4e..d62a8e5 100644
--- a/web/pgadmin/static/js/sqleditor_utils.js
+++ b/web/pgadmin/static/js/sqleditor_utils.js
@@ -8,8 +8,8 @@
 //////////////////////////////////////////////////////////////////////////
 // This file contains common utilities functions used in sqleditor modules
 
-define(['jquery', 'sources/gettext'],
-  function ($, gettext) {
+define(['jquery', 'sources/gettext', 'sources/url_for'],
+  function ($, gettext, url_for) {
     var sqlEditorUtils = {
       /* Reference link http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
        * Modified as per requirement.
@@ -61,9 +61,13 @@ define(['jquery', 'sources/gettext'],
       previousStatus: null,
 
       // This function will fetch the connection status via ajax
-      fetchConnectionStatus: function(url, $el, $status_el) {
+      fetchConnectionStatus: function(target, $el, $status_el) {
         // If user has switch the browser Tab or Minimized window or
         // if wcDocker panel is not in focus then don't fire AJAX
+        var url = url_for('sqleditor.connection_status', {
+          'trans_id': target.transId,
+        });
+
         if (document.visibilityState !== 'visible' ||
               $el.data('panel-visible') !== 'visible' ) {
           return;
@@ -169,19 +173,19 @@ define(['jquery', 'sources/gettext'],
       },
 
       // This function will update the connection status
-      updateConnectionStatus: function(url, poll_time) {
-        var $el = $('.connection_status'),
-          $status_el = $($($el).find('.fa-custom'));
+      updateConnectionStatus: function(target, poll_time) {
+        var $el = $(target.gridView.$el.find('.connection_status')),
+          $status_el = $($el.find('.fa-custom'));
 
         // Apply popover on element
         $el.popover();
 
-        // To set initial connection status
-        sqlEditorUtils.fetchConnectionStatus(url, $el, $status_el);
+        // To set initial connection statussource$el.popover()
+        sqlEditorUtils.fetchConnectionStatus(target, $el, $status_el);
 
         // Calling it again in specified interval
         setInterval(
-          sqlEditorUtils.fetchConnectionStatus.bind(null, url, $el, $status_el),
+          sqlEditorUtils.fetchConnectionStatus.bind(null, target, $el, $status_el),
           poll_time * 1000
         );
       },
diff --git a/web/pgadmin/tools/datagrid/__init__.py b/web/pgadmin/tools/datagrid/__init__.py
index f16ecc6..a935bfa 100644
--- a/web/pgadmin/tools/datagrid/__init__.py
+++ b/web/pgadmin/tools/datagrid/__init__.py
@@ -17,7 +17,6 @@ import random
 from flask import Response, url_for, session, request, make_response
 from werkzeug.useragents import UserAgent
 from flask import current_app as app
-from flask_babel import gettext
 from flask_security import login_required
 from pgadmin.tools.sqleditor.command import *
 from pgadmin.utils import PgAdminModule
@@ -27,6 +26,8 @@ from pgadmin.utils.ajax import make_json_response, bad_request, \
 from config import PG_DEFAULT_DRIVER
 from pgadmin.utils.preferences import Preferences
 from pgadmin.model import Server
+from pgadmin.utils.driver import get_driver
+from pgadmin.utils.exception import ConnectionLost
 
 
 class DataGridModule(PgAdminModule):
@@ -93,13 +94,13 @@ def show_filter():
 
 
 @blueprint.route(
-    '/initialize/datagrid/<int:cmd_type>/<obj_type>/<int:sid>/<int:did>/'
-    '<int:obj_id>',
+    '/initialize/datagrid/<int:cmd_type>/<obj_type>/<int:sgid>/<int:sid>/'
+    '<int:did>/<int:obj_id>',
     methods=["PUT", "POST"],
     endpoint="initialize_datagrid"
 )
 @login_required
-def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
+def initialize_datagrid(cmd_type, obj_type, sgid, sid, did, obj_id):
     """
     This method is responsible for creating an asynchronous connection.
     After creating the connection it will instantiate and initialize
@@ -110,7 +111,7 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
         cmd_type: Contains value for which menu item is clicked.
         obj_type: Contains type of selected object for which data grid to
         be render
-
+        sgid: Server group Id
         sid: Server Id
         did: Database Id
         obj_id: Id of currently selected object
@@ -125,15 +126,27 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
     conn_id = str(random.randint(1, 9999999))
     try:
         manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+        # default_conn is same connection which is created when user connect to
+        # database from tree
+        default_conn = manager.connection(did=did)
         conn = manager.connection(did=did, conn_id=conn_id,
+                                  auto_reconnect=False,
                                   use_binary_placeholder=True,
                                   array_to_string=True)
+    except ConnectionLost as e:
+        raise
     except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
-    # Connect the Server
+    status, msg = default_conn.connect()
+    if not status:
+        app.logger.error(msg)
+        return internal_server_error(errormsg=str(msg))
+
     status, msg = conn.connect()
     if not status:
+        app.logger.error(msg)
         return internal_server_error(errormsg=str(msg))
 
     try:
@@ -143,11 +156,12 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
 
         # Get the object as per the object type
         command_obj = ObjectRegistry.get_object(
-            obj_type, conn_id=conn_id, sid=sid,
+            obj_type, conn_id=conn_id, sgid=sgid, sid=sid,
             did=did, obj_id=obj_id, cmd_type=cmd_type,
             sql_filter=filter_sql
         )
     except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
     # Create a unique id for the transaction
@@ -236,17 +250,6 @@ def panel(trans_id, is_query_tool, editor_title):
     else:
         new_browser_tab = 'false'
 
-    if is_query_tool == 'true':
-        prompt_save_changes = pref.preference(
-            'prompt_save_query_changes'
-        ).get()
-    else:
-        prompt_save_changes = pref.preference(
-            'prompt_save_data_changes'
-        ).get()
-
-    display_connection_status = pref.preference('connection_status').get()
-
     # Fetch the server details
     bgcolor = None
     fgcolor = None
@@ -264,6 +267,27 @@ def panel(trans_id, is_query_tool, editor_title):
                 bgcolor = s.bgcolor
             fgcolor = s.fgcolor or 'black'
 
+    url_params = dict()
+    if is_query_tool == 'true':
+        prompt_save_changes = pref.preference(
+            'prompt_save_query_changes'
+        ).get()
+        url_params['sgid'] = trans_obj.sgid
+        url_params['sid'] = trans_obj.sid
+        url_params['did'] = trans_obj.did
+    else:
+        prompt_save_changes = pref.preference(
+            'prompt_save_data_changes'
+        ).get()
+        url_params['cmd_type'] = trans_obj.cmd_type
+        url_params['obj_type'] = trans_obj.object_type
+        url_params['sgid'] = trans_obj.sgid
+        url_params['sid'] = trans_obj.sid
+        url_params['did'] = trans_obj.did
+        url_params['obj_id'] = trans_obj.obj_id
+
+    display_connection_status = pref.preference('connection_status').get()
+
     return render_template(
         "datagrid/index.html",
         _=gettext,
@@ -281,50 +305,62 @@ def panel(trans_id, is_query_tool, editor_title):
         # convert python boolean value to equivalent js boolean literal
         # before passing it to html template.
         prompt_save_changes='true' if prompt_save_changes else 'false',
-        display_connection_status=display_connection_status
+        display_connection_status=display_connection_status,
+        url_params=json.dumps(url_params)
     )
 
 
 @blueprint.route(
-    '/initialize/query_tool/<int:sid>/<int:did>',
+    '/initialize/query_tool/<int:sgid>/<int:sid>/<int:did>',
     methods=["POST"], endpoint='initialize_query_tool_with_did'
 )
 @blueprint.route(
-    '/initialize/query_tool/<int:sid>',
+    '/initialize/query_tool/<int:sgid>/<int:sid>',
     methods=["POST"], endpoint='initialize_query_tool'
 )
 @login_required
-def initialize_query_tool(sid, did=None):
+def initialize_query_tool(sgid, sid, did=None):
     """
     This method is responsible for instantiating and initializing
     the query tool object. It will also create a unique
     transaction id and store the information into session variable.
 
     Args:
+        sgid: Server group Id
         sid: Server Id
         did: Database Id
     """
+    connect = True
+    if 'recreate' in request.args and \
+        request.args['recreate'] == '1':
+        connect = False
+    # Create asynchronous connection using random connection id.
+    conn_id = str(random.randint(1, 9999999))
 
-    if did is None:
-        # Use Maintenance database OID
-        from pgadmin.utils.driver import get_driver
-        driver = get_driver(PG_DEFAULT_DRIVER)
-        manager = driver.connection_manager(sid)
-        conn = manager.connection()
-        if conn.connected():
-            did = manager.did
-        else:
-            internal_server_error(
-                errormsg=gettext(
-                    'Server disconnected. Please connect and try again.'
-                )
-            )
+    # Use Maintenance database OID
+    manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
 
+    if did is None:
+        did = manager.did
     try:
         command_obj = ObjectRegistry.get_object(
-            'query_tool', sid=sid, did=did
+            'query_tool', conn_id=conn_id, sgid=sgid, sid=sid, did=did
         )
     except Exception as e:
+        app.logger.error(e)
+        return internal_server_error(errormsg=str(e))
+
+    try:
+        conn = manager.connection(did=did, conn_id=conn_id,
+                                  auto_reconnect=False,
+                                  use_binary_placeholder=True,
+                                  array_to_string=True)
+        if connect:
+            conn.connect()
+    except ConnectionLost as e:
+        raise
+    except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
     # Create a unique id for the transaction
@@ -366,6 +402,8 @@ def close(trans_id):
     Args:
         trans_id: unique transaction id
     """
+    if 'gridData' not in session:
+        return make_json_response(data={'status': True})
 
     grid_data = session['gridData']
     # Return from the function if transaction id not found
@@ -384,6 +422,7 @@ def close(trans_id):
             conn = manager.connection(
                 did=cmd_obj.did, conn_id=cmd_obj.conn_id)
         except Exception as e:
+            app.logger.error(e)
             return internal_server_error(errormsg=str(e))
 
         # Release the connection
@@ -424,6 +463,7 @@ def validate_filter(sid, did, obj_id):
         # Call validate_filter method to validate the SQL.
         status, res = sql_filter_obj.validate_filter(filter_sql)
     except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
     return make_json_response(data={'status': status, 'result': res})
diff --git a/web/pgadmin/tools/datagrid/static/js/datagrid.js b/web/pgadmin/tools/datagrid/static/js/datagrid.js
index e7329c3..21034d4 100644
--- a/web/pgadmin/tools/datagrid/static/js/datagrid.js
+++ b/web/pgadmin/tools/datagrid/static/js/datagrid.js
@@ -1,9 +1,10 @@
 define('pgadmin.datagrid', [
   'sources/gettext', 'sources/url_for', 'jquery', 'underscore',
   'pgadmin.alertifyjs', 'sources/pgadmin', 'bundled_codemirror',
-  'sources/sqleditor_utils', 'wcdocker',
+  'sources/sqleditor_utils', 'backbone', 'wcdocker',
 ], function(
-  gettext, url_for, $, _, Alertify, pgAdmin, codemirror, sqlEditorUtils
+  gettext, url_for, $, _, alertify, pgAdmin, codemirror, sqlEditorUtils,
+  Backbone
 ) {
   // Some scripts do export their object in the window only.
   // Generally the one, which do no have AMD support.
@@ -15,519 +16,478 @@ define('pgadmin.datagrid', [
   if (pgAdmin.DataGrid)
     return pgAdmin.DataGrid;
 
-  pgAdmin.DataGrid = {
-    init: function() {
-      if (this.initialized)
-        return;
-      this.initialized = true;
-      this.title_index = 1;
-
-      this.spinner_el = '<div class="wcLoadingContainer">' +
-        '<div class="wcLoadingBackground"></div>' +
-        '<div class="wcLoadingIconContainer">' +
-        '<i class="wcLoadingIcon fa fa-spinner fa-pulse"></i>' +
-        '</div>' +
-        '</div>';
-      // Define list of nodes on which view data option appears
-      var supported_nodes = [
-          'table', 'view', 'mview',
-          'foreign_table', 'catalog_object', 'partition',
-        ],
+  pgAdmin.DataGrid =
+  _.extend(
+    {
+      init: function() {
+        if (this.initialized)
+          return;
+        this.initialized = true;
+        this.title_index = 1;
+
+        this.spinner_el = '<div class="wcLoadingContainer">'+
+              '<div class="wcLoadingBackground"></div>'+
+                '<div class="wcLoadingIconContainer">'+
+                  '<i class="wcLoadingIcon fa fa-spinner fa-pulse"></i>'+
+                '</div>'+
+              '</div>';
+        // Define list of nodes on which view data option appears
+        var supported_nodes = [
+            'table', 'view', 'mview',
+            'foreign_table', 'catalog_object', 'partition',
+          ],
 
         /* Enable/disable View data menu in tools based
          * on node selected. if selected node is present
          * in supported_nodes, menu will be enabled
          * otherwise disabled.
          */
-        view_menu_enabled = function(obj) {
-          if (!_.isUndefined(obj) && !_.isNull(obj))
-            return (_.indexOf(supported_nodes, obj._type) !== -1 ? true : false);
-          else
-            return false;
-        },
+          view_menu_enabled = function(obj) {
+            if (!_.isUndefined(obj) && !_.isNull(obj))
+              return (_.indexOf(supported_nodes, obj._type) !== -1 ? true : false);
+            else
+              return false;
+          },
 
         /* Enable/disable Query tool menu in tools based
          * on node selected. if selected node is present
          * in unsupported_nodes, menu will be disabled
          * otherwise enabled.
          */
-        query_tool_menu_enabled = function(obj) {
-          if (!_.isUndefined(obj) && !_.isNull(obj)) {
-            if (_.indexOf(pgAdmin.unsupported_nodes, obj._type) == -1) {
-              if (obj._type == 'database' && obj.allowConn)
-                return true;
-              else if (obj._type != 'database')
-                return true;
-              else
+          query_tool_menu_enabled = function(obj) {
+            if (!_.isUndefined(obj) && !_.isNull(obj)) {
+              if (_.indexOf(pgAdmin.unsupported_nodes, obj._type) == -1) {
+                if (obj._type == 'database' && obj.allowConn)
+                  return true;
+                else if (obj._type != 'database')
+                  return true;
+                else
+                  return false;
+              } else {
                 return false;
+              }
             } else {
               return false;
             }
-          } else {
-            return false;
-          }
-        };
+          };
 
-      // Define the nodes on which the menus to be appear
-      var menus = [{
-        name: 'query_tool',
-        module: this,
-        applies: ['tools'],
-        callback: 'show_query_tool',
-        enable: query_tool_menu_enabled,
-        priority: 1,
-        label: gettext('Query Tool'),
-        icon: 'fa fa-bolt',
-      }];
-
-      // Create context menu
-      for (var idx = 0; idx < supported_nodes.length; idx++) {
-        menus.push({
-          name: 'view_all_rows_context_' + supported_nodes[idx],
-          node: supported_nodes[idx],
+        // Define the nodes on which the menus to be appear
+        var menus = [{
+          name: 'query_tool',
           module: this,
-          data: {
-            mnuid: 3,
-          },
-          applies: ['context', 'object'],
-          callback: 'show_data_grid',
-          enable: view_menu_enabled,
-          category: 'view_data',
-          priority: 101,
-          label: gettext('All Rows'),
-        }, {
-          name: 'view_first_100_rows_context_' + supported_nodes[idx],
-          node: supported_nodes[idx],
-          module: this,
-          data: {
-            mnuid: 1,
-          },
-          applies: ['context', 'object'],
-          callback: 'show_data_grid',
-          enable: view_menu_enabled,
-          category: 'view_data',
-          priority: 102,
-          label: gettext('First 100 Rows'),
-        }, {
-          name: 'view_last_100_rows_context_' + supported_nodes[idx],
-          node: supported_nodes[idx],
-          module: this,
-          data: {
-            mnuid: 2,
-          },
-          applies: ['context', 'object'],
-          callback: 'show_data_grid',
-          enable: view_menu_enabled,
-          category: 'view_data',
-          priority: 103,
-          label: gettext('Last 100 Rows'),
-        }, {
-          name: 'view_filtered_rows_context_' + supported_nodes[idx],
-          node: supported_nodes[idx],
-          module: this,
-          data: {
-            mnuid: 4,
-          },
-          applies: ['context', 'object'],
-          callback: 'show_filtered_row',
-          enable: view_menu_enabled,
-          category: 'view_data',
-          priority: 104,
-          label: gettext('Filtered Rows...'),
-        });
-      }
-
-      pgAdmin.Browser.add_menu_category('view_data', gettext('View/Edit Data'), 100, '');
-      pgAdmin.Browser.add_menus(menus);
-
-      // Creating a new pgAdmin.Browser frame to show the data.
-      var dataGridFrameType = new pgAdmin.Browser.Frame({
-        name: 'frm_datagrid',
-        showTitle: true,
-        isCloseable: true,
-        isPrivate: true,
-        url: 'about:blank',
-      });
-
-      // Load the newly created frame
-      dataGridFrameType.load(pgBrowser.docker);
-    },
-
-    // This is a callback function to show data when user click on menu item.
-    show_data_grid: function(data, i) {
-      var self = this,
-        d = pgAdmin.Browser.tree.itemData(i);
-      if (d === undefined) {
-        Alertify.alert(
-          gettext('Data Grid Error'),
-          gettext('No object selected.')
-        );
-        return;
-      }
-
-      // Get the parent data from the tree node hierarchy.
-      var node = pgBrowser.Nodes[d._type],
-        parentData = node.getTreeNodeHierarchy(i);
-
-      // If server, database or schema is undefined then return from the function.
-      if (parentData.server === undefined || parentData.database === undefined) {
-        return;
-      }
-      // If schema, view, catalog object all are undefined then return from the function.
-      if (parentData.schema === undefined && parentData.view === undefined &&
-        parentData.catalog === undefined) {
-        return;
-      }
-
-      var nsp_name = '';
-
-      if (parentData.schema != undefined) {
-        nsp_name = parentData.schema.label;
-      } else if (parentData.view != undefined) {
-        nsp_name = parentData.view.label;
-      } else if (parentData.catalog != undefined) {
-        nsp_name = parentData.catalog.label;
-      }
-      var url_params = {
-        'cmd_type': data.mnuid,
-        'obj_type': d._type,
-        'sid': parentData.server._id,
-        'did': parentData.database._id,
-        'obj_id': d._id,
-      };
-
-      var baseUrl = url_for('datagrid.initialize_datagrid', url_params);
-      var grid_title = parentData.server.label + ' - ' + parentData.database.label + ' - ' +
-        nsp_name + '.' + d.label;
-
-      // Initialize the data grid.
-      self.initialize_data_grid(baseUrl, grid_title, '', parentData.server.server_type);
-    },
-
-    // This is a callback function to show filtered data when user click on menu item.
-    show_filtered_row: function(data, i) {
-      var self = this,
-        d = pgAdmin.Browser.tree.itemData(i);
-      if (d === undefined) {
-        Alertify.alert(
-          gettext('Data Grid Error'),
-          gettext('No object selected.')
-        );
-        return;
-      }
-
-      // Get the parent data from the tree node hierarchy.
-      var node = pgBrowser.Nodes[d._type],
-        parentData = node.getTreeNodeHierarchy(i);
-
-      // If server or database is undefined then return from the function.
-      if (parentData.server === undefined || parentData.database === undefined) {
-        return;
-      }
-
-      // If schema, view, catalog object all are undefined then return from the function.
-      if (parentData.schema === undefined && parentData.view === undefined &&
-        parentData.catalog === undefined) {
-        return;
-      }
-
-      var nsp_name = '';
-
-      if (parentData.schema != undefined) {
-        nsp_name = parentData.schema.label;
-      } else if (parentData.view != undefined) {
-        nsp_name = parentData.view.label;
-      } else if (parentData.catalog != undefined) {
-        nsp_name = parentData.catalog.label;
-      }
-
-      var url_params = {
-        'cmd_type': data.mnuid,
-        'obj_type': d._type,
-        'sid': parentData.server._id,
-        'did': parentData.database._id,
-        'obj_id': d._id,
-
-      };
-
-      var baseUrl = url_for('datagrid.initialize_datagrid', url_params);
-
-      // Create url to validate the SQL filter
-      var validateUrl = url_for('datagrid.filter_validate', {
-        'sid': url_params['sid'],
-        'did': url_params['did'],
-        'obj_id': url_params['obj_id'],
-      });
-      var grid_title = parentData.server.label + '-' + parentData.database.label + '-' +
-        nsp_name + '.' + d.label;
-
-      // Create filter dialog using alertify
-      if (!Alertify.filterDialog) {
-        Alertify.dialog('filterDialog', function factory() {
-          return {
-            main: function(title, message, baseUrl, validateUrl) {
-              this.set('title', title);
-              this.message = message;
-              this.baseUrl = baseUrl;
-              this.validateUrl = validateUrl;
+          applies: ['tools'],
+          callback: 'show_query_tool',
+          enable: query_tool_menu_enabled,
+          priority: 1,
+          label: gettext('Query Tool'),
+          icon: 'fa fa-bolt',
+        }];
+
+        // Create context menu
+        for (var idx = 0; idx < supported_nodes.length; idx++) {
+          menus.push({
+            name: 'view_all_rows_context_' + supported_nodes[idx],
+            node: supported_nodes[idx],
+            module: this,
+            data: {
+              mnuid: 3,
             },
-
-            setup: function() {
-              return {
-                buttons: [{
-                  text: 'OK',
-                  className: 'btn btn-primary',
-                },
-                {
-                  text: 'Cancel',
-                  className: 'btn btn-danger',
-                },
-                ],
-                options: {
-                  modal: 0,
-                  resizable: true,
-                  maximizable: false,
-                  pinnable: false,
-                },
-              };
+            applies: ['context', 'object'],
+            callback: 'show_data_grid',
+            enable: view_menu_enabled,
+            category: 'view_data',
+            priority: 101,
+            label: gettext('All Rows'),
+          }, {
+            name: 'view_first_100_rows_context_' + supported_nodes[idx],
+            node: supported_nodes[idx],
+            module: this,
+            data: {
+              mnuid: 1,
+            },
+            applies: ['context', 'object'],
+            callback: 'show_data_grid',
+            enable: view_menu_enabled,
+            category: 'view_data',
+            priority: 102,
+            label: gettext('First 100 Rows'),
+          }, {
+            name: 'view_last_100_rows_context_' + supported_nodes[idx],
+            node: supported_nodes[idx],
+            module: this,
+            data: {
+              mnuid: 2,
             },
-            build: function() {
-              Alertify.pgDialogBuild.apply(this);
+            applies: ['context', 'object'],
+            callback: 'show_data_grid',
+            enable: view_menu_enabled,
+            category: 'view_data',
+            priority: 103,
+            label: gettext('Last 100 Rows'),
+          }, {
+            name: 'view_filtered_rows_context_' + supported_nodes[idx],
+            node: supported_nodes[idx],
+            module: this,
+            data: {
+              mnuid: 4,
             },
-            prepare: function() {
-              var self = this,
-                $content = $(this.message),
-                $sql_filter = $content.find('#sql_filter');
+            applies: ['context', 'object'],
+            callback: 'show_filtered_row',
+            enable: view_menu_enabled,
+            category: 'view_data',
+            priority: 104,
+            label: gettext('Filtered Rows...'),
+          });
+        }
 
-              $(this.elements.body.childNodes[0]).addClass(
-                'dataview_filter_dialog'
-              );
+        pgAdmin.Browser.add_menu_category('view_data', gettext('View/Edit Data'), 100, '');
+        pgAdmin.Browser.add_menus(menus);
 
-              this.setContent($content.get(0));
-
-              // Apply CodeMirror to filter text area.
-              this.filter_obj = CodeMirror.fromTextArea($sql_filter.get(0), {
-                tabindex: 0,
-                lineNumbers: true,
-                mode: 'text/x-pgsql',
-                extraKeys: pgBrowser.editor_shortcut_keys,
-                indentWithTabs: pgAdmin.Browser.editor_options.indent_with_tabs,
-                indentUnit: pgAdmin.Browser.editor_options.tabSize,
-                tabSize: pgBrowser.editor_options.tabSize,
-                lineWrapping: pgAdmin.Browser.editor_options.wrapCode,
-                autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets,
-                matchBrackets: pgAdmin.Browser.editor_options.brace_matching,
-              });
-
-              setTimeout(function() {
-                // Set focus on editor
-                self.filter_obj.focus();
-              }, 500);
-            },
+        // Creating a new pgAdmin.Browser frame to show the data.
+        var dataGridFrameType = new pgAdmin.Browser.Frame({
+          name: 'frm_datagrid',
+          showTitle: true,
+          isCloseable: true,
+          isPrivate: true,
+          url: 'about:blank',
+        });
 
-            callback: function(closeEvent) {
-
-              if (closeEvent.button.text == gettext('OK')) {
-                var sql = this.filter_obj.getValue();
-                var that = this;
-
-                // Make ajax call to include the filter by selection
-                $.ajax({
-                  url: that.validateUrl,
-                  method: 'POST',
-                  async: false,
-                  contentType: 'application/json',
-                  data: JSON.stringify(sql),
-                  success: function(res) {
-                    if (res.data.status) {
-                      // Initialize the data grid.
-                      self.initialize_data_grid(that.baseUrl, grid_title, sql, parentData.server.server_type);
-                    } else {
-                      Alertify.alert(
-                        gettext('Validation Error'),
-                        res.data.result
-                      );
-                    }
-                  },
-                  error: function(e) {
-                    Alertify.alert(
-                      gettext('Validation Error'),
-                      e
-                    );
-                  },
-                });
-              }
-            },
-          };
+        // Load the newly created frame
+        dataGridFrameType.load(pgBrowser.docker);
+        this.on('pgadmin-datagrid:transaction:created', function(trans_obj) {
+          this.launch_grid(trans_obj);
         });
-      }
+      },
+
+      // This is a callback function to show data when user click on menu item.
+      show_data_grid: function(data, i) {
+        var self = this,
+          d = pgAdmin.Browser.tree.itemData(i);
+        if (d === undefined) {
+          alertify.alert(
+            gettext('Data Grid Error'),
+            gettext('No object selected.')
+          );
+          return;
+        }
+
+        // Get the parent data from the tree node hierarchy.
+        var node = pgBrowser.Nodes[d._type],
+          parentData = node.getTreeNodeHierarchy(i);
 
-      $.get(url_for('datagrid.filter'),
-        function(data) {
-          Alertify.filterDialog('Data Filter', data, baseUrl, validateUrl)
-            .resizeTo(300, 200);
+        // If server, database or schema is undefined then return from the function.
+        if (parentData.server === undefined || parentData.database === undefined) {
+          return;
+        }
+        // If schema, view, catalog object all are undefined then return from the function.
+        if (parentData.schema === undefined && parentData.view === undefined &&
+             parentData.catalog === undefined) {
+          return;
         }
-      );
-    },
 
-    get_panel_title: function() {
-      // Get the parent data from the tree node hierarchy.
-      var tree = pgAdmin.Browser.tree,
-        selected_item = tree.selected(),
-        item_data = tree.itemData(selected_item),
-        node = pgBrowser.Nodes[item_data._type],
-        parentData = node.getTreeNodeHierarchy(selected_item);
-
-      // If server, database is undefined then return from the function.
-      if (parentData.server === undefined) {
-        return;
-      }
-      // If Database is not available then use default db
-      var db_label = parentData.database ? parentData.database.label :
-        parentData.server.db;
-
-      var grid_title = db_label + ' on ' + parentData.server.user.name + '@' +
-        parentData.server.label;
-      return grid_title;
-    },
+        var nsp_name = '';
 
-    initialize_data_grid: function(baseUrl, grid_title, sql_filter, server_type) {
-      var self = this;
-      self.grid_title = grid_title;
-
-      /* Ajax call to initialize the edit grid, which creates
-       * an asynchronous connection and create appropriate query
-       * for the selected node.
-       */
-      $.ajax({
-        url: baseUrl,
-        method: 'POST',
-        dataType: 'json',
-        contentType: 'application/json',
-        data: JSON.stringify(sql_filter),
-        success: function(res) {
+        if (parentData.schema != undefined) {
+          nsp_name = parentData.schema.label;
+        }
+        else if (parentData.view != undefined) {
+          nsp_name = parentData.view.label;
+        }
+        else if (parentData.catalog != undefined) {
+          nsp_name = parentData.catalog.label;
+        }
+        var url_params = {
+          'cmd_type': data.mnuid,
+          'obj_type': d._type,
+          'sgid': parentData.server_group._id,
+          'sid': parentData.server._id,
+          'did': parentData.database._id,
+          'obj_id': d._id,
+        };
 
-          /* On successfully initialization find the dashboard panel,
-           * create new panel and add it to the dashboard panel.
-           */
-          var url_params = {
-            'trans_id': res.data.gridTransId,
-            'is_query_tool': 'false',
-            'editor_title': encodeURIComponent(self.grid_title),
-          };
+        var baseUrl = url_for('datagrid.initialize_datagrid', url_params);
+        var grid_title = parentData.server.label + ' - ' + parentData.database.label + ' - '
+                        + nsp_name + '.' + d.label;
+
+        self.create_transaction(baseUrl, null, 'false', parentData.server.server_type, '', grid_title, '');
+      },
+
+      // This is a callback function to show filtered data when user click on menu item.
+      show_filtered_row: function(data, i) {
+        var self = this,
+          d = pgAdmin.Browser.tree.itemData(i);
+        if (d === undefined) {
+          alertify.alert(
+            gettext('Data Grid Error'),
+            gettext('No object selected.')
+          );
+          return;
+        }
 
-          var baseUrl = url_for('datagrid.panel', url_params) +
-            '?query_url=&server_type=' + encodeURIComponent(server_type);
-          var grid_title = gettext('Edit Data - ') + self.grid_title;
-          if (res.data.newBrowserTab) {
-            var newWin = window.open(baseUrl, '_blank');
+        // Get the parent data from the tree node hierarchy.
+        var node = pgBrowser.Nodes[d._type],
+          parentData = node.getTreeNodeHierarchy(i);
 
-            // add a load listener to the window so that the title gets changed on page load
-            newWin.addEventListener('load', function() {
-              newWin.document.title = grid_title;
-            });
-          } else {
-            var propertiesPanel = pgBrowser.docker.findPanels('properties');
-            var dataGridPanel = pgBrowser.docker.addPanel('frm_datagrid', wcDocker.DOCK.STACKED, propertiesPanel[0]);
-
-            // Set panel title and icon
-            dataGridPanel.title('<span title="' + grid_title + '">' + grid_title + '</span>');
-            dataGridPanel.icon('fa fa-bolt');
-            dataGridPanel.focus();
-
-            // Listen on the panel closed event.
-            dataGridPanel.on(wcDocker.EVENT.CLOSED, function() {
-              $.ajax({
-                url: url_for('datagrid.close', {
-                  'trans_id': res.data.gridTransId,
-                }),
-                method: 'GET',
-              });
-            });
+        // If server or database is undefined then return from the function.
+        if (parentData.server === undefined || parentData.database === undefined) {
+          return;
+        }
 
-            var openDataGridURL = function(j) {
-              // add spinner element
-              $(j).data('embeddedFrame').$container.append(self.spinner_el);
-              setTimeout(function() {
-                var frameInitialized = $(j).data('frameInitialized');
-                if (frameInitialized) {
-                  var frame = $(j).data('embeddedFrame');
-                  if (frame) {
-                    frame.openURL(baseUrl);
-                    frame.$container.find('.wcLoadingContainer').hide(1);
-                  }
-                } else {
-                  openDataGridURL(j);
+        // If schema, view, catalog object all are undefined then return from the function.
+        if (parentData.schema === undefined && parentData.view === undefined &&
+             parentData.catalog === undefined) {
+          return;
+        }
+
+        var nsp_name = '';
+
+        if (parentData.schema != undefined) {
+          nsp_name = parentData.schema.label;
+        }
+        else if (parentData.view != undefined) {
+          nsp_name = parentData.view.label;
+        }
+        else if (parentData.catalog != undefined) {
+          nsp_name = parentData.catalog.label;
+        }
+
+        var url_params = {
+          'cmd_type': data.mnuid,
+          'obj_type': d._type,
+          'sgid': parentData.server_group._id,
+          'sid': parentData.server._id,
+          'did': parentData.database._id,
+          'obj_id': d._id,
+        };
+
+        var baseUrl = url_for('datagrid.initialize_datagrid', url_params);
+
+        // Create url to validate the SQL filter
+        var validateUrl = url_for('datagrid.filter_validate', {
+          'sid': url_params['sid'],
+          'did': url_params['did'],
+          'obj_id': url_params['obj_id'],
+        });
+        var grid_title = parentData.server.label + '-' + parentData.database.label + '-'
+                        + nsp_name + '.' + d.label;
+
+        // Create filter dialog using alertify
+        if (!alertify.filterDialog) {
+          alertify.dialog('filterDialog', function factory() {
+            return {
+              main: function(title, message, baseUrl, validateUrl) {
+                this.set('title', title);
+                this.message = message;
+                this.baseUrl = baseUrl;
+                this.validateUrl = validateUrl;
+              },
+
+              setup:function() {
+                return {
+                  buttons:[
+                    { text: 'OK', className: 'btn btn-primary' },
+                    { text: 'Cancel', className: 'btn btn-danger' },
+                  ],
+                  options: { modal: 0, resizable: true, maximizable: false, pinnable: false},
+                };
+              },
+              build: function() {
+                alertify.pgDialogBuild.apply(this);
+              },
+              prepare:function() {
+                var self = this,
+                  $content = $(this.message),
+                  $sql_filter = $content.find('#sql_filter');
+
+                $(this.elements.body.childNodes[0]).addClass(
+                  'dataview_filter_dialog'
+                );
+
+                this.setContent($content.get(0));
+
+                // Apply CodeMirror to filter text area.
+                this.filter_obj = CodeMirror.fromTextArea($sql_filter.get(0), {
+                  lineNumbers: true,
+                  mode: 'text/x-pgsql',
+                  extraKeys: pgBrowser.editor_shortcut_keys,
+                  indentWithTabs: pgAdmin.Browser.editor_options.indent_with_tabs,
+                  indentUnit: pgAdmin.Browser.editor_options.tabSize,
+                  tabSize: pgBrowser.editor_options.tabSize,
+                  lineWrapping: pgAdmin.Browser.editor_options.wrapCode,
+                  autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets,
+                  matchBrackets: pgAdmin.Browser.editor_options.brace_matching,
+                });
+
+                setTimeout(function() {
+                  // Set focus on editor
+                  self.filter_obj.focus();
+                }, 500);
+              },
+
+              callback: function(closeEvent) {
+
+                if (closeEvent.button.text == gettext('OK')) {
+                  var sql = this.filter_obj.getValue();
+                  var that = this;
+
+                  // Make ajax call to include the filter by selection
+                  $.ajax({
+                    url: that.validateUrl,
+                    method: 'POST',
+                    async: false,
+                    contentType: 'application/json',
+                    data: JSON.stringify(sql),
+                    success: function(res) {
+                      if (res.data.status) {
+                        // Initialize the data grid.
+                        self.create_transaction(that.baseUrl, null, 'false', parentData.server.server_type, '', grid_title, sql, false);
+                      }
+                      else {
+                        alertify.alert(
+                          gettext('Validation Error'),
+                            res.data.result
+                        );
+                      }
+                    },
+                    error: function(e) {
+                      alertify.alert(
+                        gettext('Validation Error'),
+                        e
+                      );
+                    },
+                  });
                 }
-              }, 100);
+              },
             };
+          });
+        }
 
-            openDataGridURL(dataGridPanel);
+        $.get(url_for('datagrid.filter'),
+          function(data) {
+            alertify.filterDialog('Data Filter', data, baseUrl, validateUrl)
+                    .resizeTo(300, 200);
           }
-        },
-        error: function() {
-          Alertify.alert(
-            gettext('Error'),
-            gettext('Query Tool Initialization Error')
+        );
+      },
+
+      get_panel_title: function() {
+        // Get the parent data from the tree node hierarchy.
+        var tree = pgAdmin.Browser.tree,
+          selected_item = tree.selected(),
+          item_data = tree.itemData(selected_item);
+
+        var node = pgBrowser.Nodes[item_data._type],
+          parentData = node.getTreeNodeHierarchy(selected_item);
+
+        // If server, database is undefined then return from the function.
+        if (parentData.server === undefined) {
+          return;
+        }
+        // If Database is not available then use default db
+        var db_label = parentData.database ? parentData.database.label
+                                           : parentData.server.db;
+
+        var grid_title = db_label + ' on ' + parentData.server.user.name + '@' +
+                parentData.server.label;
+        return grid_title;
+      },
+      // This is a callback function to show query tool when user click on menu item.
+      show_query_tool: function(url, i, panel_title) {
+        var sURL = url || '',
+          d = pgAdmin.Browser.tree.itemData(i);
+
+        panel_title = panel_title || '';
+        if (d === undefined) {
+          alertify.alert(
+            gettext('Query Tool Error'),
+            gettext('No object selected.')
           );
-        },
-      });
-    },
+          return;
+        }
 
-    // This is a callback function to show query tool when user click on menu item.
-    show_query_tool: function(url, i, panel_title) {
-      var self = this,
-        sURL = url || '',
-        d = pgAdmin.Browser.tree.itemData(i);
+        // Get the parent data from the tree node hierarchy.
+        var node = pgBrowser.Nodes[d._type],
+          parentData = node.getTreeNodeHierarchy(i);
 
-      panel_title = panel_title || '';
+        // If server, database is undefined then return from the function.
+        if (parentData.server === undefined) {
+          return;
+        }
 
-      if (d === undefined) {
-        Alertify.alert(
-          gettext('Query Tool Error'),
-          gettext('No object selected.')
-        );
-        return;
-      }
-
-      // Get the parent data from the tree node hierarchy.
-      var node = pgBrowser.Nodes[d._type],
-        parentData = node.getTreeNodeHierarchy(i);
-
-      // If server, database is undefined then return from the function.
-      if (parentData.server === undefined) {
-        return;
-      }
-
-      var url_params = {
-        'sid': parentData.server._id,
-      };
-      var url_endpoint = 'datagrid.initialize_query_tool';
-      // If database not present then use Maintenance database
-      // We will handle this at server side
-      if (parentData.database) {
-        url_params['did'] = parentData.database._id;
-        url_endpoint = 'datagrid.initialize_query_tool_with_did';
-      }
-      var baseUrl = url_for(url_endpoint, url_params);
-
-      $.ajax({
-        url: baseUrl,
-        method: 'POST',
-        dataType: 'json',
-        contentType: 'application/json',
-        success: function(res) {
-          var grid_title = self.get_panel_title();
+        var url_params = {
+            'sgid': parentData.server_group._id,
+            'sid': parentData.server._id,
+          },
+          url_endpoint = 'datagrid.initialize_query_tool';
+        // If database not present then use Maintenance database
+        // We will handle this at server side
+        if (parentData.database) {
+          url_params['did'] = parentData.database._id;
+          url_endpoint = 'datagrid.initialize_query_tool_with_did';
+        }
+        var baseUrl = url_for(url_endpoint, url_params);
+
+        this.create_transaction(baseUrl, null, 'true', parentData.server.server_type, sURL, panel_title, '', false);
+      },
+      create_transaction: function(baseUrl, target, is_query_tool, server_type, sURL, panel_title, sql_filter, recreate) {
+        var self = this;
+        target =  target || self;
+        if (recreate) {
+          baseUrl += '?recreate=1';
+        }
+        $.ajax({
+          url: baseUrl,
+          method: 'POST',
+          dataType: 'json',
+          data: JSON.stringify(sql_filter),
+          contentType: 'application/json',
+          success: function(res) {
+            res.data.is_query_tool = is_query_tool;
+            res.data.server_type = server_type;
+            res.data.sURL = sURL;
+            res.data.panel_title = panel_title;
+            target.trigger('pgadmin-datagrid:transaction:created', res.data);
+          },
+          error: function(xhr) {
+            if (target !== self) {
+              if(xhr.status == 503 && xhr.responseJSON.info != undefined &&
+                  xhr.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  target.handle_connection_lost(true, xhr);
+                });
+                return;
+              }
+            }
+
+            try {
+              var err = $.parseJSON(xhr.responseText);
+              alertify.alert(gettext('Query Tool Initialize Error'),
+                err.errormsg
+              );
+            } catch (e) {
+              alertify.alert(
+                e.statusText, gettext('Query Tool Initialize Error')
+              );
+            }
+          },
+        });
+      },
+      launch_grid: function(trans_obj) {
+        var self = this,
+          panel_title = trans_obj.panel_title,
+          grid_title = self.get_panel_title(),
           // Open the panel if frame is initialized
-          var url_params = {
-            'trans_id': res.data.gridTransId,
-            'is_query_tool': 'true',
+          url_params = {
+            'trans_id': trans_obj.gridTransId,
+            'is_query_tool': trans_obj.is_query_tool,
             'editor_title': encodeURIComponent(grid_title),
-          };
-
-          var baseUrl = url_for('datagrid.panel', url_params) +
-            '?' + 'query_url=' + encodeURI(sURL) + '&server_type=' + encodeURIComponent(parentData.server.server_type);
+          },
+          baseUrl = url_for('datagrid.panel', url_params) +
+            '?' + 'query_url=' + encodeURI(trans_obj.sURL) + '&server_type=' + encodeURIComponent(trans_obj.server_type);
 
+        if(trans_obj.is_query_tool == 'false') {
+          panel_title = gettext('Edit Data - ') + grid_title;
+        } else {
           // Create title for CREATE/DELETE scripts
           if (panel_title) {
             panel_title =
@@ -535,64 +495,57 @@ define('pgadmin.datagrid', [
           } else {
             panel_title = gettext('Query - ') + grid_title;
           }
+        }
 
-          if (res.data.newBrowserTab) {
-            var newWin = window.open(baseUrl, '_blank');
+        if (trans_obj.newBrowserTab) {
+          var newWin = window.open(baseUrl, '_blank');
 
-            // add a load listener to the window so that the title gets changed on page load
-            newWin.addEventListener('load', function() {
-              newWin.document.title = panel_title;
-            });
-          } else {
-            /* On successfully initialization find the dashboard panel,
-             * create new panel and add it to the dashboard panel.
-             */
-            var propertiesPanel = pgBrowser.docker.findPanels('properties');
-            var queryToolPanel = pgBrowser.docker.addPanel('frm_datagrid', wcDocker.DOCK.STACKED, propertiesPanel[0]);
-
-            // Set panel title and icon
-            queryToolPanel.title('<span title="' + panel_title + '">' + panel_title + '</span>');
-            queryToolPanel.icon('fa fa-bolt');
-            queryToolPanel.focus();
-
-            // Listen on the panel closed event.
-            queryToolPanel.on(wcDocker.EVENT.CLOSED, function() {
-              $.ajax({
-                url: url_for('datagrid.close', {
-                  'trans_id': res.data.gridTransId,
-                }),
-                method: 'GET',
-              });
+          // add a load listener to the window so that the title gets changed on page load
+          newWin.addEventListener('load', function() {
+            newWin.document.title = panel_title;
+          });
+        } else {
+          /* On successfully initialization find the dashboard panel,
+           * create new panel and add it to the dashboard panel.
+           */
+          var propertiesPanel = pgBrowser.docker.findPanels('properties');
+          var queryToolPanel = pgBrowser.docker.addPanel('frm_datagrid', wcDocker.DOCK.STACKED, propertiesPanel[0]);
+
+          // Set panel title and icon
+          queryToolPanel.title('<span title="'+panel_title+'">'+panel_title+'</span>');
+          queryToolPanel.icon('fa fa-bolt');
+          queryToolPanel.focus();
+
+          // Listen on the panel closed event.
+          queryToolPanel.on(wcDocker.EVENT.CLOSED, function() {
+            $.ajax({
+              url: url_for('datagrid.close', {'trans_id': trans_obj.gridTransId}),
+              method: 'GET',
             });
-
-            var openQueryToolURL = function(j) {
-              // add spinner element
-              $(j).data('embeddedFrame').$container.append(pgAdmin.DataGrid.spinner_el);
-              setTimeout(function() {
-                var frameInitialized = $(j).data('frameInitialized');
-                if (frameInitialized) {
-                  var frame = $(j).data('embeddedFrame');
-                  if (frame) {
-                    frame.openURL(baseUrl);
-                    frame.$container.find('.wcLoadingContainer').delay(1000).hide(1);
-                  }
-                } else {
-                  openQueryToolURL(j);
+          });
+
+          var openQueryToolURL = function(j) {
+            // add spinner element
+            $(j).data('embeddedFrame').$container.append(pgAdmin.DataGrid.spinner_el);
+            setTimeout(function() {
+              var frameInitialized = $(j).data('frameInitialized');
+              if (frameInitialized) {
+                var frame = $(j).data('embeddedFrame');
+                if (frame) {
+                  frame.openURL(baseUrl);
+                  frame.$container.find('.wcLoadingContainer').delay(1000).hide(1);
                 }
-              }, 100);
-            };
+              } else {
+                openQueryToolURL(j);
+              }
+            }, 100);
+          };
 
-            openQueryToolURL(queryToolPanel);
-          }
-        },
-        error: function() {
-          Alertify.alert(
-            gettext('Query Tool Initialize Error')
-          );
-        },
-      });
+          openQueryToolURL(queryToolPanel);
+        }
+      },
     },
-  };
+    Backbone.Events);
 
   return pgAdmin.DataGrid;
 });
diff --git a/web/pgadmin/tools/datagrid/templates/datagrid/index.html b/web/pgadmin/tools/datagrid/templates/datagrid/index.html
index ee62ed1..73c8ba0 100644
--- a/web/pgadmin/tools/datagrid/templates/datagrid/index.html
+++ b/web/pgadmin/tools/datagrid/templates/datagrid/index.html
@@ -24,7 +24,7 @@
         <span class="sql-editor-busy-icon wcLoadingIcon fa fa-spinner fa-pulse"></span>
         <span class="sql-editor-busy-text wcLoadingLabel"></span>
     </div>
-    <div class="sql-editor" data-trans-id="{{ uniqueId }}">
+    <div class="sql-editor">
         <div id="btn-toolbar" class="pg-prop-btn-group bg-gray-2 border-gray-3" role="toolbar" aria-label="">
             <div class="btn-group" role="group" aria-label="">
                 <button id="btn-load-file" type="button" class="btn btn-default btn-load-file"
@@ -361,44 +361,21 @@
           loadingDiv.addClass('hide');
           }
           });
-
-    // Fetch the SQL for Scripts (eg: CREATE/UPDATE/DELETE/SELECT)
-    var script_sql = '';
-{% if script_type_url%}
-    // Call AJAX only if script type url is present
-    $.ajax({
-      url: '{{ script_type_url }}',
-      type:'GET',
-      async: false,
-      success: function(res) {
-        script_sql = res;
-      },
-      error: function(jqx) {
-        var msg = jqx.responseText;
-        /* Error from the server */
-        if (jqx.status == 410 || jqx.status == 500) {
-          try {
-            var data = $.parseJSON(jqx.responseText);
-            msg = data.errormsg;
-          } catch (e) {}
-        }
-        pgBrowser.report_error(
-          S('{{ _('Error fetching SQL for script: "%s"') }}')
-          .sprintf(msg)
-          .value(), msg
-        );
-      }
-    });
-{% endif %}
-
+    {% if script_type_url %}
+        var script_type_url = '{{ script_type_url }}';
+    {% else %}
+        var script_type_url = '';
+    {% endif %}
     // Start the query tool.
     sqlEditorController.start(
+        {{ uniqueId }},
         {{ is_query_tool }},
         "{{ editor_title }}",
-        script_sql,
+        script_type_url,
         {{ is_new_browser_tab }},
         "{{ server_type }}",
-        {{ prompt_save_changes }}
+        {{ prompt_save_changes }},
+        {{ url_params|safe}}
     );
 });
 {% endblock %}
diff --git a/web/pgadmin/tools/sqleditor/__init__.py b/web/pgadmin/tools/sqleditor/__init__.py
index 635219d..2975d8f 100644
--- a/web/pgadmin/tools/sqleditor/__init__.py
+++ b/web/pgadmin/tools/sqleditor/__init__.py
@@ -14,7 +14,8 @@ import pickle
 import random
 import codecs
 
-from flask import Response, url_for, render_template, session, request
+from flask import Response, url_for, render_template, session, request,\
+    current_app
 from flask_babel import gettext
 from flask_security import login_required
 from pgadmin.tools.sqleditor.command import QueryToolCommand
@@ -26,6 +27,7 @@ from pgadmin.utils.driver import get_driver
 from pgadmin.utils.sqlautocomplete.autocomplete import SQLAutoComplete
 from pgadmin.misc.file_manager import Filemanager
 from pgadmin.utils.menu import MenuItem
+from pgadmin.utils.exception import ConnectionLost
 
 from config import PG_DEFAULT_DRIVER, ON_DEMAND_RECORD_COUNT
 
@@ -51,13 +53,13 @@ TX_STATUS_INTRANS = 2
 TX_STATUS_INERROR = 3
 
 # Connection status codes mapping
-CONNECTION_STATUS_MESSAGE_MAPPING = dict({
-    0: 'The session is idle and there is no current transaction.',
-    1: 'A command is currently in progress.',
-    2: 'The session is idle in a valid transaction block.',
-    3: 'The session is idle in a failed transaction block.',
-    4: 'The connection with the server is bad.'
-})
+CONNECTION_STATUS_MESSAGE_MAPPING = dict([
+    (0, 'The session is idle and there is no current transaction.'),
+    (1, 'A command is currently in progress.'),
+    (2, 'The session is idle in a valid transaction block.'),
+    (3, 'The session is idle in a failed transaction block.'),
+    (4, 'The connection with the server is bad.')
+])
 
 
 class SqlEditorModule(PgAdminModule):
@@ -393,9 +395,11 @@ def check_transaction_status(trans_id):
     Returns: status and connection object
 
     """
+
     if 'gridData' not in session:
-        return False, unauthorized(gettext("Unauthorized request.")), \
-            None, None, None
+        return False, gettext(
+            'Transaction ID not found in the session.'
+        ), None, None, None
 
     grid_data = session['gridData']
 
@@ -416,18 +420,23 @@ def check_transaction_status(trans_id):
         conn = manager.connection(
             did=trans_obj.did,
             conn_id=trans_obj.conn_id,
+            auto_reconnect=False,
             use_binary_placeholder=True,
             array_to_string=True
         )
+    except ConnectionLost as e:
+        raise
     except Exception as e:
+        current_app.logger.error(e)
         return False, internal_server_error(errormsg=str(e)), None, None, None
 
-    if conn.connected():
-        return True, None, conn, trans_obj, session_obj
-    else:
-        return False, gettext('Not connected to server or connection with '
-                              'the server has been closed.'), \
-            None, trans_obj, session_obj
+    connect = True if 'connect' in request.args and \
+                      request.args['connect'] == '1' else False
+
+    if connect:
+        conn.connect()
+
+    return True, None, conn, trans_obj, session_obj
 
 
 @blueprint.route(
@@ -448,12 +457,25 @@ def start_view_data(trans_id):
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
 
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     # get the default connection as current connection which is attached to
     # trans id holds the cursor which has query result so we cannot use that
     # connection to execute another query otherwise we'll lose query result.
 
-    manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(trans_obj.sid)
-    default_conn = manager.connection(did=trans_obj.did)
+    try:
+        manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(
+            trans_obj.sid)
+        default_conn = manager.connection(did=trans_obj.did)
+    except ConnectionLost as e:
+        raise
+    except Exception as e:
+        current_app.logger.error(e)
+        return internal_server_error(errormsg=str(e))
 
     # Connect to the Server if not connected.
     if not default_conn.connected():
@@ -465,41 +487,41 @@ def start_view_data(trans_id):
 
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
-        try:
-            # set fetched row count to 0 as we are executing query again.
-            trans_obj.update_fetched_row_cnt(0)
-            session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
+        # set fetched row count to 0 as we are executing query again.
+        trans_obj.update_fetched_row_cnt(0)
+        session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
 
-            # Fetch the sql and primary_keys from the object
-            sql = trans_obj.get_sql()
-            pk_names, primary_keys = trans_obj.get_primary_keys(default_conn)
+        # Fetch the sql and primary_keys from the object
+        sql = trans_obj.get_sql(default_conn)
+        pk_names, primary_keys = trans_obj.get_primary_keys(default_conn)
 
-            has_oids = False
-            if trans_obj.object_type == 'table':
-                # Fetch OIDs status
-                has_oids = trans_obj.has_oids(default_conn)
+        has_oids = False
+        if trans_obj.object_type == 'table':
+            # Fetch OIDs status
+            has_oids = trans_obj.has_oids(default_conn)
 
-            # Fetch the applied filter.
-            filter_applied = trans_obj.is_filter_applied()
+        # Fetch the applied filter.
+        filter_applied = trans_obj.is_filter_applied()
 
-            # Fetch the limit for the SQL query
-            limit = trans_obj.get_limit()
+        # Fetch the limit for the SQL query
+        limit = trans_obj.get_limit()
 
-            can_edit = trans_obj.can_edit()
-            can_filter = trans_obj.can_filter()
+        can_edit = trans_obj.can_edit()
+        can_filter = trans_obj.can_filter()
 
-            # Store the primary keys to the session object
-            session_obj['primary_keys'] = primary_keys
+        # Store the primary keys to the session object
+        session_obj['primary_keys'] = primary_keys
 
-            # Store the OIDs status into session object
-            session_obj['has_oids'] = has_oids
+        # Store the OIDs status into session object
+        session_obj['has_oids'] = has_oids
 
-            update_session_grid_transaction(trans_id, session_obj)
+        update_session_grid_transaction(trans_id, session_obj)
 
-            # Execute sql asynchronously
+        # Execute sql asynchronously
+        try:
             status, result = conn.execute_async(sql)
-        except Exception as e:
-            return internal_server_error(errormsg=str(e))
+        except ConnectionLost as e:
+            raise
     else:
         status = False
         result = error_msg
@@ -537,26 +559,24 @@ def start_query_tool(trans_id):
     else:
         sql = request.args or request.form
 
+    connect = True if 'connect' in request.args and \
+                      request.args['connect'] == '1' else False
+
     if 'gridData' not in session:
         return make_json_response(
-            data={
-                'status': False,
-                'result': gettext('Transaction ID not found in the session.'),
-                'can_edit': False, 'can_filter': False
-            }
-        )
+            success=0,
+            errormsg=gettext('Transaction ID not found in the session.'),
+            info='DATAGRID_TRANSACTION_REQUIRED', status=404)
 
     grid_data = session['gridData']
 
     # Return from the function if transaction id not found
     if str(trans_id) not in grid_data:
         return make_json_response(
-            data={
-                'status': False,
-                'result': gettext('Transaction ID not found in the session.'),
-                'can_edit': False, 'can_filter': False
-            }
-        )
+            success=0,
+            errormsg=gettext('Transaction ID not found in the session.'),
+            info='DATAGRID_TRANSACTION_REQUIRED',
+            status=404)
 
     # Fetch the object for the specified transaction id.
     # Use pickle.loads function to get the command object
@@ -570,60 +590,55 @@ def start_query_tool(trans_id):
 
     if trans_obj is not None and session_obj is not None:
         conn_id = trans_obj.conn_id
-
-        # if conn_id is None then we will have to create a new connection
-        if conn_id is None:
-            # Create asynchronous connection using random connection id.
-            conn_id = str(random.randint(1, 9999999))
-
         try:
             manager = get_driver(
                 PG_DEFAULT_DRIVER).connection_manager(trans_obj.sid)
             conn = manager.connection(did=trans_obj.did, conn_id=conn_id,
+                                      auto_reconnect=False,
                                       use_binary_placeholder=True,
                                       array_to_string=True)
+        except ConnectionLost as e:
+            raise
         except Exception as e:
+            current_app.logger.error(e)
             return internal_server_error(errormsg=str(e))
 
         # Connect to the Server if not connected.
-        if not conn.connected():
+        if connect and not conn.connected():
             status, msg = conn.connect()
             if not status:
+                current_app.logger.error(msg)
                 return internal_server_error(errormsg=str(msg))
 
-        if conn.connected():
-            # on successful connection set the connection id to the
-            # transaction object
-            trans_obj.set_connection_id(conn_id)
+        # on successful connection set the connection id to the
+        # transaction object
+        trans_obj.set_connection_id(conn_id)
 
-            # As we changed the transaction object we need to
-            # restore it and update the session variable.
-            session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
-            update_session_grid_transaction(trans_id, session_obj)
+        # As we changed the transaction object we need to
+        # restore it and update the session variable.
+        session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
+        update_session_grid_transaction(trans_id, session_obj)
 
-            # If auto commit is False and transaction status is Idle
-            # then call is_begin_not_required() function to check BEGIN
-            # is required or not.
+        # If auto commit is False and transaction status is Idle
+        # then call is_begin_not_required() function to check BEGIN
+        # is required or not.
 
-            if not trans_obj.auto_commit \
-                    and conn.transaction_status() == TX_STATUS_IDLE \
-                    and is_begin_required(sql):
-                conn.execute_void("BEGIN;")
+        if not trans_obj.auto_commit \
+                and conn.transaction_status() == TX_STATUS_IDLE \
+                and is_begin_required(sql):
+            conn.execute_void("BEGIN;")
 
-            # Execute sql asynchronously with params is None
-            # and formatted_error is True.
+        # Execute sql asynchronously with params is None
+        # and formatted_error is True.
+        try:
             status, result = conn.execute_async(sql)
-
-            # If the transaction aborted for some reason and
-            # Auto RollBack is True then issue a rollback to cleanup.
-            trans_status = conn.transaction_status()
-            if trans_status == TX_STATUS_INERROR and trans_obj.auto_rollback:
-                conn.execute_void("ROLLBACK;")
-        else:
-            status = False
-            result = gettext(
-                'Not connected to server or connection with the server has '
-                'been closed.')
+        except ConnectionLost as e:
+            raise
+        # If the transaction aborted for some reason and
+        # Auto RollBack is True then issue a rollback to cleanup.
+        trans_status = conn.transaction_status()
+        if trans_status == TX_STATUS_INERROR and trans_obj.auto_rollback:
+            conn.execute_void("ROLLBACK;")
 
         can_edit = trans_obj.can_edit()
         can_filter = trans_obj.can_filter()
@@ -655,10 +670,16 @@ def preferences(trans_id):
             trans_id: unique transaction id
     """
     if request.method == 'GET':
-
         # Check the transaction and connection status
         status, error_msg, conn, trans_obj, session_obj = \
             check_transaction_status(trans_id)
+
+        if error_msg == gettext(
+                'Transaction ID not found in the session.'):
+            return make_json_response(success=0, errormsg=error_msg,
+                                      info='DATAGRID_TRANSACTION_REQUIRED',
+                                      status=404)
+
         if status and conn is not None \
                 and trans_obj is not None and session_obj is not None:
             # Call the set_auto_commit and set_auto_rollback method of
@@ -728,6 +749,13 @@ def poll(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None and session_obj is not None:
         status, result = conn.poll(
             formatted_exception_msg=True, no_result=True)
@@ -915,6 +943,13 @@ def fetch(trans_id, fetch_all=None):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None and session_obj is not None:
         status, result = conn.async_fetchmany_2darray(fetch_row_cnt)
         if not status:
@@ -1030,6 +1065,13 @@ def save(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1092,6 +1134,12 @@ def get_filter(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1123,6 +1171,13 @@ def apply_filter(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1159,6 +1214,13 @@ def append_filter_inclusive(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1208,6 +1270,12 @@ def append_filter_exclusive(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1255,6 +1323,13 @@ def remove_filter(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1293,6 +1368,13 @@ def set_limit(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1325,16 +1407,20 @@ def cancel_transaction(trans_id):
         trans_id: unique transaction id
     """
 
+    if 'gridData' not in session:
+        return make_json_response(
+            success=0,
+            errormsg=gettext('Transaction ID not found in the session.'),
+            info='DATAGRID_TRANSACTION_REQUIRED', status=404)
+
     grid_data = session['gridData']
 
     # Return from the function if transaction id not found
     if str(trans_id) not in grid_data:
         return make_json_response(
-            data={
-                'status': False,
-                'result': gettext('Transaction ID not found in the session.')
-            }
-        )
+            success=0,
+            errormsg=gettext('Transaction ID not found in the session.'),
+            info='DATAGRID_TRANSACTION_REQUIRED', status=404)
 
     # Fetch the object for the specified transaction id.
     # Use pickle.loads function to get the command object
@@ -1403,6 +1489,13 @@ def get_object_name(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
         res = trans_obj.object_name
@@ -1433,6 +1526,13 @@ def set_auto_commit(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1475,6 +1575,13 @@ def set_auto_rollback(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1524,6 +1631,13 @@ def auto_complete(trans_id):
     # Check the transaction and connection status
     status, error_msg, conn, trans_obj, session_obj = \
         check_transaction_status(trans_id)
+
+    if error_msg == gettext(
+            'Transaction ID not found in the session.'):
+        return make_json_response(success=0, errormsg=error_msg,
+                                  info='DATAGRID_TRANSACTION_REQUIRED',
+                                  status=404)
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1947,7 +2061,7 @@ def query_tool_status(trans_id):
         )
 
     if conn and trans_obj and session_obj:
-        status = conn.conn.get_transaction_status()
+        status = conn.transaction_status()
         return make_json_response(
             data={
                 'status': status,
diff --git a/web/pgadmin/tools/sqleditor/command.py b/web/pgadmin/tools/sqleditor/command.py
index e480ab7..dff8b92 100644
--- a/web/pgadmin/tools/sqleditor/command.py
+++ b/web/pgadmin/tools/sqleditor/command.py
@@ -104,7 +104,9 @@ class BaseCommand(object):
             **kwargs : N number of parameters
         """
 
-        # Save the server id and database id, namespace id, object id
+        # Save the server group id, server id and database id, namespace id,
+        # object id
+        self.sgid = kwargs['sgid'] if 'sgid' in kwargs else None
         self.sid = kwargs['sid'] if 'sid' in kwargs else None
         self.did = kwargs['did'] if 'did' in kwargs else None
 
@@ -922,7 +924,7 @@ class QueryToolCommand(BaseCommand, FetchedRowTracker):
         BaseCommand.__init__(self, **kwargs)
         FetchedRowTracker.__init__(self, **kwargs)
 
-        self.conn_id = None
+        self.conn_id = kwargs['conn_id'] if 'conn_id' in kwargs else None
         self.auto_rollback = False
         self.auto_commit = True
 
diff --git a/web/pgadmin/tools/sqleditor/static/css/sqleditor.css b/web/pgadmin/tools/sqleditor/static/css/sqleditor.css
index c939c2f..1e29c3f 100644
--- a/web/pgadmin/tools/sqleditor/static/css/sqleditor.css
+++ b/web/pgadmin/tools/sqleditor/static/css/sqleditor.css
@@ -581,3 +581,24 @@ input.editor-checkbox:focus {
 .sql-editor .copy-all:focus {
   outline: 5px auto -webkit-focus-ring-color;
 }
+
+.ajs-body .warn-icon {
+  color:#f1c40f;
+  font-size: 2em;
+  margin-right: 20px;
+  padding-top: 10px;
+}
+.ajs-body .warn-header {
+  font-size: 13px;
+  font-weight: bold;
+  line-height: 3em;
+}
+
+.ajs-body .warn-body {
+  font-size: 13px;
+}
+
+.ajs-body .warn-footer {
+  font-size: 13px;
+  line-height: 3em;
+}
\ No newline at end of file
diff --git a/web/pgadmin/tools/sqleditor/static/js/sqleditor.js b/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
index 8b86617..a8cb125 100644
--- a/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
+++ b/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
@@ -17,17 +17,19 @@ define('tools.querytool', [
   'react', 'react-dom',
   'sources/keyboard_shortcuts',
   'sources/sqleditor/query_tool_actions',
+  'pgadmin.datagrid',
   'sources/../bundle/slickgrid',
   'pgadmin.file_manager',
   'backgrid.sizeable.columns',
   'slick.pgadmin.formatters',
   'slick.pgadmin.editors',
   'pgadmin.browser',
+  'pgadmin.tools.user_management',
 ], function(
   babelPollyfill, gettext, url_for, $, _, S, alertify, pgAdmin, Backbone, codemirror,
   pgExplain, GridSelector, ActiveCellCapture, clipboard, copyData, RangeSelectionHelper, handleQueryOutputKeyboardEvent,
   XCellSelectionModel, setStagedRows, SqlEditorUtils, HistoryBundle, queryHistory, React, ReactDOM,
-  keyboardShortcuts, queryToolActions) {
+  keyboardShortcuts, queryToolActions, Datagrid) {
   /* Return back, this has been called more than once */
   if (pgAdmin.SqlEditor)
     return pgAdmin.SqlEditor;
@@ -41,6 +43,12 @@ define('tools.querytool', [
 
   var is_query_running = false;
 
+  var is_new_transaction_required = function(xhr) {
+    return xhr.status == 404 && xhr.responseJSON &&
+                xhr.responseJSON.info &&
+                xhr.responseJSON.info == 'DATAGRID_TRANSACTION_REQUIRED';
+  };
+
   // Defining Backbone view for the sql grid.
   var SQLEditorView = Backbone.View.extend({
     initialize: function(opts) {
@@ -300,10 +308,6 @@ define('tools.querytool', [
             p.on(wcDocker.EVENT.GAIN_FOCUS, function() {
               var $container = $(this.$container),
                 transId = self.handler.transId;
-              // If transaction id is already set
-              if($container.data('trans-id') != transId) {
-                $container.data('trans-id', transId);
-              }
 
               if (!$container.hasClass('wcPanelTabContentHidden')) {
                 setTimeout(function () {
@@ -319,7 +323,7 @@ define('tools.querytool', [
             // When any query tool panel lost it focus then
             p.on(wcDocker.EVENT.LOST_FOCUS, function () {
               var $container = $(this.$container),
-                transId = $container.data('trans-id');
+                transId = self.handler.transId;
               // Trigger an event to update connection status flag
               if ($container.hasClass('wcPanelTabContentHidden')) {
                 pgBrowser.Events.trigger(
@@ -477,6 +481,14 @@ define('tools.querytool', [
                   },
                 });
               },
+              error:function(e) {
+                if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+                  return pgAdmin.Browser.UserManagement.pga_login();
+                }
+                if(is_new_transaction_required(e)) {
+                  return self.init_transaction();
+                }
+              },
             });
           }.bind(ctx),
         };
@@ -505,7 +517,7 @@ define('tools.querytool', [
       // Only enable pooling if it is enabled
       if (display_status && display_status.value) {
         SqlEditorUtils.updateConnectionStatus(
-          url_for('sqleditor.connection_status', {'trans_id': self.transId}),
+          self.handler,
           preference.value
         );
       }
@@ -1100,7 +1112,7 @@ define('tools.querytool', [
           'fetch_all': 1,
         });
       } else {
-        url = url = url_for('sqleditor.fetch', {
+        url = url_for('sqleditor.fetch', {
           'trans_id': self.transId,
         });
       }
@@ -1132,6 +1144,10 @@ define('tools.querytool', [
             );
             return;
           }
+
+          if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+            pgAdmin.Browser.UserManagement.pga_login();
+          }
         },
       });
     },
@@ -1284,6 +1300,7 @@ define('tools.querytool', [
     // Callback function for the find next button click.
     on_find_next: function(ev) {
       var self = this;
+
       this._stopEventPropogation(ev);
       this._closeDropDown(ev);
 
@@ -1733,16 +1750,200 @@ define('tools.querytool', [
 
   _.extend(
     SqlEditorController.prototype,
-    Backbone.Events, {
+    Backbone.Events,
+    {
       initialize: function(container) {
+        var self = this;
         this.container = container;
+        this.state = {};
+        if (!alertify.dlgGetServerPass) {
+          alertify.dialog('dlgGetServerPass', function factory() {
+            return {
+              main: function(
+                title, message
+              ) {
+                this.set('title', title);
+                this.setting('message',message);
+              },
+              setup:function() {
+                return {
+                  buttons:[
+                    {
+                      text: gettext('OK'),
+                      key: 13,
+                      className: 'btn btn-primary',
+                    },
+                    {
+                      text: gettext('Cancel'),
+                      className: 'btn btn-danger',
+                    },
+                  ],
+                  focus: {
+                    element: '#password',
+                    select: true,
+                  },
+                  options: {
+                    modal: 0,
+                    resizable: false,
+                    maximizable: false,
+                    pinnable: false,
+                  },
+                };
+              },
+              build:function() {},
+              settings:{
+                message: null,
+              },
+              prepare:function() {
+                this.setContent(this.setting('message'));
+              },
+              callback: function(closeEvent) {
+                if (closeEvent.button.text == gettext('OK')) {
+                  var passdata = $(this.elements.content).find('#frmPassword').serialize();
+                  self.init_connection(false, passdata);
+                }
+              },
+            };
+          });
+        }
+        this.on('pgadmin-datagrid:transaction:created', function(trans_obj) {
+          self.transId = trans_obj.gridTransId;
+          self.warn_before_continue();
+        });
+        pgBrowser.Events.on('pgadmin:user:logged-in', function() {
+          self.init_transaction();
+        });
       },
+      save_state: function(fn, args) {
+        if (fn) {
+          this.state = {
+            'fn': fn,
+            'args': args,
+          };
+        } else {
+          this.state = {};
+        }
+      },
+
+      init_transaction: function() {
+        var url_endpoint;
+        if (this.is_query_tool) {
+          url_endpoint = 'datagrid.initialize_query_tool';
 
+          // If database not present then use Maintenance database
+          // We will handle this at server side
+          if (this.url_params.did) {
+            url_endpoint = 'datagrid.initialize_query_tool_with_did';
+          }
+
+        } else {
+          url_endpoint = 'datagrid.initialize_datagrid';
+        }
+
+        var baseUrl = url_for(url_endpoint, this.url_params);
+
+        Datagrid.create_transaction(baseUrl, this, this.is_query_tool,
+            this.server_type, '', '', '', true);
+      },
+
+      handle_connection_lost: function(create_transaction, xhr) {
+        var self= this;
+        if (xhr.responseJSON.data && !xhr.responseJSON.data.conn_id) {
+          // if conn_id is null then this is maintenance db.
+          // so attempt connection connect without prompt.
+          self.init_connection(create_transaction);
+        } else {
+          self.warn_before_continue();
+        }
+      },
+      warn_before_continue: function() {
+        var self = this;
+
+        alertify.confirm(
+          gettext('Connection Warning'),
+          '<p style="float:left">'+
+            '<span class="fa fa-exclamation-triangle warn-icon" aria-hidden="true">'+
+            '</span>'+
+          '</p>'+
+          '<p style="display: inline-block;">'+
+            '<span class="warn-header">'+
+              gettext('System has lost the connection due to one of the following reason:')+
+            '</span>'+
+            '<br>'+
+            '<span class="warn-body">'+
+              gettext('⁃ The connection might be idle for a long period of time hence it was closed')+
+            '<br>'+
+              gettext('⁃ Application server or database server was restarted')+
+            '<br>'+
+              gettext('⁃ The user session was timed out')+
+            '</span>'+
+            '<br>'+
+            '<span class="warn-footer">'+
+            gettext('This will establish a new connection, do you want to continue?')+
+            '</span>'+
+          '</p>',
+          function() {
+            if ('fn' in self.state) {
+              var fn = self.state['fn'],
+                args = self.state['args'];
+              self.save_state();
+              if (args.indexOf('connect') == -1) {
+                args.push('connect');
+              }
+
+              self[fn].apply(self, args);
+            }
+          }, function() {
+            self.save_state();
+          })
+          .set({
+            labels: {
+              ok: gettext('Continue'),
+              cancel: gettext('Cancel'),
+            },
+          });
+      },
+      init_connection: function(create_transaction, passdata) {
+        var self = this;
+        $.post(url_for('NODE-server.connect_id', {
+          'gid': this.url_params.sgid,
+          'sid': this.url_params.sid,
+        }),passdata)
+        .done(function(res) {
+          if (res.success == 1) {
+            alertify.success(res.info);
+            if (create_transaction) {
+              self.init_transaction();
+            } else if ('fn' in self.state) {
+              var fn = self.state['fn'],
+                args = self.state['args'];
+              self.save_state();
+              self[fn].apply(self, args);
+            }
+          }
+        })
+        .fail(function(xhr) {
+          if (pgAdmin.Browser.UserManagement.is_pga_login_required(xhr)) {
+            pgAdmin.Browser.UserManagement.pga_login();
+          } else {
+            if(xhr.responseJSON &&
+                xhr.responseJSON.result) {
+              alertify.dlgGetServerPass(gettext('Connect to Server'),
+                xhr.responseJSON.result);
+            } else {
+              alertify.dlgGetServerPass(gettext('Connect to Server'),
+                xhr.responseText);
+            }
+          }
+        });
+      },
       /* This function is used to create instance of SQLEditorView,
        * call the render method of the grid view to render the backgrid
        * header and loading icon and start execution of the sql query.
        */
-      start: function(is_query_tool, editor_title, script_sql, is_new_browser_tab, server_type, prompt_save_changes) {
+      start: function(transId, is_query_tool, editor_title, script_type_url,
+          is_new_browser_tab, server_type, prompt_save_changes, url_params
+      ) {
         var self = this;
 
         self.is_query_tool = is_query_tool;
@@ -1758,6 +1959,8 @@ define('tools.querytool', [
         self.close_on_save = false;
         self.server_type = server_type;
         self.prompt_save_changes = prompt_save_changes;
+        self.url_params = url_params;
+        self.script_type_url = script_type_url;
 
         // We do not allow to call the start multiple times.
         if (self.gridView)
@@ -1767,7 +1970,7 @@ define('tools.querytool', [
           el: self.container,
           handler: self,
         });
-        self.transId = self.gridView.transId = self.container.data('transId');
+        self.transId = self.gridView.transId = transId;
 
         self.gridView.editor_title = _.unescape(editor_title);
         self.gridView.current_file = undefined;
@@ -1775,6 +1978,61 @@ define('tools.querytool', [
         // Render the header
         self.gridView.render();
 
+        if (self.is_query_tool) {
+          // Fetch the SQL for Scripts (eg: CREATE/UPDATE/DELETE/SELECT)
+          // Call AJAX only if script type url is present
+          if (script_type_url) {
+            $.ajax({
+              url: script_type_url,
+              type:'GET',
+              success: function(res) {
+                self.gridView.query_tool_obj.refresh();
+                if (res && res !== '') {
+                  self.gridView.query_tool_obj.setValue(res);
+                }
+                self.init_events();
+              },
+              error: function(jqx) {
+                var msg = '';
+                self.init_events();
+
+                if (pgAdmin.Browser.UserManagement.is_pga_login_required(jqx)) {
+                  return pgAdmin.Browser.UserManagement.pga_login();
+                }
+
+                /* Error from the server */
+                if (jqx.status == 410 || jqx.status == 500) {
+                  try {
+                    var data = $.parseJSON(jqx.responseText);
+                    msg = data.errormsg;
+                  } catch (e) {
+                    msg = jqx.responseText;
+                  }
+                }
+                pgBrowser.report_error(
+                  S(gettext('Error fetching SQL for script: %s.')).sprintf(msg).value()
+                );
+              },
+            });
+          } else {
+            self.init_events();
+          }
+        }
+        else {
+          // Disable codemirror by setting cursor to nocursor and background to dark.
+          self.init_events();
+          self.gridView.query_tool_obj.setOption('readOnly', 'nocursor');
+          var cm = self.gridView.query_tool_obj.getWrapperElement();
+          if (cm) {
+            cm.className += ' bg-gray-1 opacity-5';
+          }
+          self.disable_tool_buttons(true);
+          self.execute_data_query();
+        }
+      },
+
+      init_events: function() {
+        var self = this;
         // Listen to the file manager button events
         pgAdmin.Browser.Events.on('pgadmin-storage:finish_btn:select_file', self._select_file_handler, self);
         pgAdmin.Browser.Events.on('pgadmin-storage:finish_btn:create_file', self._save_file_handler, self);
@@ -1808,22 +2066,6 @@ define('tools.querytool', [
         // Indentation related
         self.on('pgadmin-sqleditor:indent_selected_code', self._indent_selected_code, self);
         self.on('pgadmin-sqleditor:unindent_selected_code', self._unindent_selected_code, self);
-
-        if (self.is_query_tool) {
-          self.gridView.query_tool_obj.refresh();
-          if (script_sql && script_sql !== '') {
-            self.gridView.query_tool_obj.setValue(script_sql);
-          }
-        } else {
-          // Disable codemirror by setting cursor to nocursor and background to dark.
-          self.gridView.query_tool_obj.setOption('readOnly', 'nocursor');
-          var cm = self.gridView.query_tool_obj.getWrapperElement();
-          if (cm) {
-            cm.className += ' bg-gray-1 opacity-5';
-          }
-          self.disable_tool_buttons(true);
-          self.execute_data_query();
-        }
       },
 
       // This function checks if there is any dirty data in the grid before
@@ -1858,7 +2100,11 @@ define('tools.querytool', [
 
       // This function makes the ajax call to execute the sql query.
       _run_query: function() {
-        var self = this;
+        var self = this,
+          url = url_for('sqleditor.view_data_start', {
+            'trans_id': self.transId,
+          });
+
         self.query_start_time = new Date();
         self.rows_affected = 0;
         self._init_polling_flags();
@@ -1881,14 +2127,16 @@ define('tools.querytool', [
           gettext('Waiting for the query execution to complete...')
         );
 
+        if (arguments.length > 0 &&
+          arguments[arguments.length - 1] == 'connect') {
+          url += '?connect=1';
+        }
+
         $.ajax({
-          url: url_for('sqleditor.view_data_start', {
-            'trans_id': self.transId,
-          }),
+          url: url,
           method: 'GET',
           success: function(res) {
             if (res.data.status) {
-
               self.can_edit = res.data.can_edit;
               self.can_filter = res.data.can_filter;
               self.info_notifier_timeout = res.data.info_notifier_timeout;
@@ -1935,11 +2183,30 @@ define('tools.querytool', [
               );
               return;
             }
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_run_query', []);
+              pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_run_query', []);
+              self.init_transaction();
+            }
 
             var msg = e.responseText;
-            if (e.responseJSON != undefined &&
-              e.responseJSON.errormsg != undefined)
-              msg = e.responseJSON.errormsg;
+            if (e.responseJSON != undefined) {
+              if(e.responseJSON.errormsg != undefined) {
+                msg = e.responseJSON.errormsg;
+              }
+
+              if(e.status == 503 && e.responseJSON.info != undefined &&
+                  e.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  self.save_state('_run_query', []);
+                  self.handle_connection_lost(false, e);
+                });
+              }
+            }
 
             self.update_msg_history(false, msg);
           },
@@ -1952,8 +2219,8 @@ define('tools.querytool', [
       call_render_after_poll: function(res) {
         var self = this;
         self.query_end_time = new Date();
-        self.rows_affected = res.rows_affected,
-          self.has_more_rows = res.has_more_rows;
+        self.rows_affected = res.rows_affected;
+        self.has_more_rows = res.has_more_rows;
 
         /* If no column information is available it means query
            runs successfully with no result to display. In this
@@ -2042,6 +2309,10 @@ define('tools.querytool', [
                   return;
                 }
 
+                if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+                  return pgAdmin.Browser.UserManagement.pga_login();
+                }
+
                 var msg = e.responseText;
                 if (e.responseJSON != undefined &&
                   e.responseJSON.errormsg != undefined)
@@ -2545,7 +2816,7 @@ define('tools.querytool', [
                 data = [];
 
               if (res.data.status) {
-                if (is_added) {
+                if(is_added) {
                   // Update the rows in a grid after addition
                   dataView.beginUpdate();
                   _.each(res.data.query_result, function(r) {
@@ -2665,10 +2936,30 @@ define('tools.querytool', [
                 return;
               }
 
+              if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+                self.save_state('_save', [view, controller, save_as]);
+                pgAdmin.Browser.UserManagement.pga_login();
+              }
+
+              if(is_new_transaction_required(e)) {
+                self.save_state('_save', [view, controller, save_as]);
+                self.init_transaction();
+              }
+
               var msg = e.responseText;
-              if (e.responseJSON != undefined &&
-                e.responseJSON.errormsg != undefined)
-                msg = e.responseJSON.errormsg;
+              if (e.responseJSON != undefined) {
+                if(e.responseJSON.errormsg != undefined) {
+                  msg = e.responseJSON.errormsg;
+                }
+
+                if(e.status == 503 && e.responseJSON.info != undefined &&
+                    e.responseJSON.info == 'CONNECTION_LOST') {
+                  setTimeout(function() {
+                    self.save_state('_save', [view, controller, save_as]);
+                    self.handle_connection_lost(false, e);
+                  });
+                }
+              }
 
               self.update_msg_history(false, msg);
             },
@@ -2775,6 +3066,7 @@ define('tools.querytool', [
       // read file data and return as response
       _select_file_handler: function(e) {
         var self = this,
+          _e = e,
           data = {
             'file_name': decodeURI(e),
           };
@@ -2810,9 +3102,14 @@ define('tools.querytool', [
             setTimeout(() => { self.gridView.query_tool_obj.focus(); }, 200);
           },
           error: function(e) {
+            self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_select_file_handler', [_e]);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
             var errmsg = $.parseJSON(e.responseText).errormsg;
             alertify.error(errmsg);
-            self.trigger('pgadmin-sqleditor:loading-icon:hide');
             // hide cursor
             $busy_icon_div.removeClass('show_progress');
           },
@@ -2822,6 +3119,7 @@ define('tools.querytool', [
       // read data from codemirror and write to file
       _save_file_handler: function(e) {
         var self = this,
+          _e = e,
           data = {
             'file_name': decodeURI(e),
             'file_content': self.gridView.query_tool_obj.getValue(),
@@ -2857,6 +3155,10 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_save_file_handler', [_e]);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
 
             var errmsg = $.parseJSON(e.responseText).errormsg;
             setTimeout(
@@ -2960,15 +3262,34 @@ define('tools.querytool', [
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_show_filter', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_show_filter', []);
+              return self.init_transaction();
+            }
+
             var msg;
             if (e.readyState == 0) {
               msg =
                 gettext('Not connected to the server or the connection to the server has been closed.');
             } else {
               msg = e.responseText;
-              if (e.responseJSON != undefined &&
-                e.responseJSON.errormsg != undefined)
-                msg = e.responseJSON.errormsg;
+              if (e.responseJSON != undefined) {
+                if(e.responseJSON.errormsg != undefined) {
+                  msg = e.responseJSON.errormsg;
+                }
+                if(e.status == 503 && e.responseJSON.info != undefined &&
+                    e.responseJSON.info == 'CONNECTION_LOST') {
+                  setTimeout(function() {
+                    self.save_state('_show_filter', []);
+                    self.handle_connection_lost(false, e);
+                  });
+                }
+              }
             }
             setTimeout(
               function() {
@@ -3030,6 +3351,16 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_include_filter', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_include_filter', []);
+              return self.init_transaction();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3040,9 +3371,18 @@ define('tools.querytool', [
                 }
 
                 var msg = e.responseText;
-                if (e.responseJSON != undefined &&
-                  e.responseJSON.errormsg != undefined)
-                  msg = e.responseJSON.errormsg;
+                if (e.responseJSON != undefined) {
+                  if(e.responseJSON.errormsg != undefined) {
+                    msg = e.responseJSON.errormsg;
+                  }
+                  if(e.status == 503 && e.responseJSON.info != undefined &&
+                      e.responseJSON.info == 'CONNECTION_LOST') {
+                    setTimeout(function() {
+                      self.save_state('_include_filter', []);
+                      self.handle_connection_lost(false, e);
+                    });
+                  }
+                }
 
                 alertify.alert(gettext('Filter By Selection Error'), msg);
               }, 10
@@ -3102,6 +3442,15 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_exclude_filter', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_exclude_filter', []);
+              return self.init_transaction();
+            }
 
             setTimeout(
               function() {
@@ -3113,9 +3462,18 @@ define('tools.querytool', [
                 }
 
                 var msg = e.responseText;
-                if (e.responseJSON != undefined &&
-                  e.responseJSON.errormsg != undefined)
-                  msg = e.responseJSON.errormsg;
+                if (e.responseJSON != undefined) {
+                  if(e.responseJSON.errormsg != undefined) {
+                    msg = e.responseJSON.errormsg;
+                  }
+                  if(e.status == 503 && e.responseJSON.info != undefined &&
+                      e.responseJSON.info == 'CONNECTION_LOST') {
+                    setTimeout(function() {
+                      self.save_state('_exclude_filter', []);
+                      self.handle_connection_lost(false, e);
+                    });
+                  }
+                }
 
                 alertify.alert(gettext('Filter Exclude Selection Error'), msg);
               }, 10
@@ -3154,6 +3512,16 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_remove_filter', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_remove_filter', []);
+              return self.init_transaction();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3164,9 +3532,18 @@ define('tools.querytool', [
                 }
 
                 var msg = e.responseText;
-                if (e.responseJSON != undefined &&
-                  e.responseJSON.errormsg != undefined)
-                  msg = e.responseJSON.errormsg;
+                if (e.responseJSON != undefined) {
+                  if(e.responseJSON.errormsg != undefined) {
+                    msg = e.responseJSON.errormsg;
+                  }
+                  if(e.status == 503 && e.responseJSON.info != undefined &&
+                      e.responseJSON.info == 'CONNECTION_LOST') {
+                    setTimeout(function() {
+                      self.save_state('_remove_filter', []);
+                      self.handle_connection_lost(false, e);
+                    });
+                  }
+                }
 
                 alertify.alert(gettext('Remove Filter Error'), msg);
               }
@@ -3210,6 +3587,16 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_apply_filter', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_apply_filter', []);
+              return self.init_transaction();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3220,9 +3607,18 @@ define('tools.querytool', [
                 }
 
                 var msg = e.responseText;
-                if (e.responseJSON != undefined &&
-                  e.responseJSON.errormsg != undefined)
-                  msg = e.responseJSON.errormsg;
+                if (e.responseJSON != undefined) {
+                  if(e.responseJSON.errormsg != undefined) {
+                    msg = e.responseJSON.errormsg;
+                  }
+                  if(e.status == 503 && e.responseJSON.info != undefined &&
+                      e.responseJSON.info == 'CONNECTION_LOST') {
+                    setTimeout(function() {
+                      self.save_state('_apply_filter', []);
+                      self.handle_connection_lost(false, e);
+                    });
+                  }
+                }
 
                 alertify.alert(gettext('Apply Filter Error'), msg);
               }, 10
@@ -3346,6 +3742,16 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_set_limit', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_set_limit', []);
+              return self.init_transaction();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3356,9 +3762,18 @@ define('tools.querytool', [
                 }
 
                 var msg = e.responseText;
-                if (e.responseJSON != undefined &&
-                  e.responseJSON.errormsg != undefined)
-                  msg = e.responseJSON.errormsg;
+                if (e.responseJSON != undefined) {
+                  if(e.responseJSON.errormsg != undefined) {
+                    msg = e.responseJSON.errormsg;
+                  }
+                  if(e.status == 503 && e.responseJSON.info != undefined &&
+                      e.responseJSON.info == 'CONNECTION_LOST') {
+                    setTimeout(function() {
+                      self.save_state('_set_limit', []);
+                      self.handle_connection_lost(false, e);
+                    });
+                  }
+                }
 
                 alertify.alert(gettext('Change limit Error'), msg);
               }, 10
@@ -3380,7 +3795,10 @@ define('tools.querytool', [
       // and execute the query.
       execute: function(explain_prefix) {
         var self = this,
-          sql = '';
+          sql = '',
+          url = url_for('sqleditor.query_tool_start', {
+            'trans_id': self.transId,
+          });
 
         self.has_more_rows = false;
         self.fetching_rows = false;
@@ -3416,10 +3834,13 @@ define('tools.querytool', [
         self.disable_tool_buttons(true);
         $('#btn-cancel-query').prop('disabled', false);
 
+        if (arguments.length > 0 &&
+          arguments[arguments.length - 1] == 'connect') {
+          url += '?connect=1';
+        }
+
         $.ajax({
-          url: url_for('sqleditor.query_tool_start', {
-            'trans_id': self.transId,
-          }),
+          url: url,
           method: 'POST',
           contentType: 'application/json',
           data: JSON.stringify(sql),
@@ -3468,11 +3889,29 @@ define('tools.querytool', [
               return;
             }
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('execute', [explain_prefix]);
+              pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('execute', [explain_prefix]);
+              self.init_transaction();
+            }
             var msg = e.responseText;
-            if (e.responseJSON != undefined &&
-              e.responseJSON.errormsg != undefined)
-              msg = e.responseJSON.errormsg;
+            if (e.responseJSON != undefined) {
+              if(e.responseJSON.errormsg != undefined) {
+                msg = e.responseJSON.errormsg;
+              }
 
+              if(e.status == 503 && e.responseJSON.info != undefined &&
+                  e.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  self.save_state('execute', [explain_prefix]);
+                  self.handle_connection_lost(false, e);
+                });
+              }
+            }
             self.update_msg_history(false, msg);
           },
         });
@@ -3573,6 +4012,11 @@ define('tools.querytool', [
               return;
             }
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_cancel_query', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
             var msg = e.responseText;
             if (e.responseJSON != undefined &&
               e.responseJSON.errormsg != undefined)
@@ -3629,10 +4073,30 @@ define('tools.querytool', [
               return;
             }
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_auto_rollback', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_auto_rollback', []);
+              self.init_transaction();
+            }
+
             var msg = e.responseText;
-            if (e.responseJSON != undefined &&
-              e.responseJSON.errormsg != undefined)
-              msg = e.responseJSON.errormsg;
+            if (e.responseJSON != undefined) {
+              if(e.responseJSON.errormsg != undefined) {
+                msg = e.responseJSON.errormsg;
+              }
+
+              if(e.status == 503 && e.responseJSON.info != undefined &&
+                  e.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  self.save_state('_auto_rollback', []);
+                  self.handle_connection_lost(false, e);
+                });
+              }
+            }
 
             alertify.alert(gettext('Auto Rollback Error'), msg);
           },
@@ -3650,7 +4114,7 @@ define('tools.querytool', [
           auto_commit = false;
         }
 
-        // Make ajax call to change the limit
+        // Make ajax call to toggle auto commit
         $.ajax({
           url: url_for('sqleditor.auto_commit', {
             'trans_id': self.transId,
@@ -3670,10 +4134,30 @@ define('tools.querytool', [
               return;
             }
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_auto_commit', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_auto_commit', []);
+              return self.init_transaction();
+            }
+
             var msg = e.responseText;
-            if (e.responseJSON != undefined &&
-              e.responseJSON.errormsg != undefined)
-              msg = e.responseJSON.errormsg;
+            if (e.responseJSON != undefined) {
+              if(e.responseJSON.errormsg != undefined) {
+                msg = e.responseJSON.errormsg;
+              }
+
+              if(e.status == 503 && e.responseJSON.info != undefined &&
+                  e.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  self.save_state('_auto_commit', []);
+                  self.handle_connection_lost(false, e);
+                });
+              }
+            }
 
             alertify.alert(gettext('Auto Commit Error'), msg);
           },
@@ -3710,7 +4194,18 @@ define('tools.querytool', [
               );
             }
           },
-          error: function() {
+          error: function(e) {
+
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_explain_verbose', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_explain_verbose', []);
+              return self.init_transaction();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting verbose option in explain.')
             );
@@ -3749,7 +4244,17 @@ define('tools.querytool', [
               );
             }
           },
-          error: function() {
+          error: function(e) {
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_explain_costs', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_explain_costs', []);
+              return self.init_transaction();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting costs option in explain.')
             );
@@ -3787,7 +4292,17 @@ define('tools.querytool', [
               );
             }
           },
-          error: function() {
+          error: function(e) {
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_explain_buffers', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_explain_buffers', []);
+              return self.init_transaction();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting buffers option in explain.')
             );
@@ -3824,7 +4339,17 @@ define('tools.querytool', [
               );
             }
           },
-          error: function() {
+          error: function(e) {
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('_explain_timing', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('_explain_timing', []);
+              return self.init_transaction();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting timing option in explain.')
             );
@@ -3924,7 +4449,17 @@ define('tools.querytool', [
               updateUI();
             }
           },
-          error: function() {
+          error: function(e) {
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              self.save_state('get_preferences', []);
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              self.save_state('get_preferences', []);
+              return self.init_transaction();
+            }
+
             updateUI();
             alertify.alert(
               gettext('Get Preferences error'),
@@ -3935,6 +4470,8 @@ define('tools.querytool', [
       },
       close: function() {
         var self = this;
+
+        pgBrowser.Events.off('pgadmin:user:logged-in', this.init_transaction);
         _.each(window.top.pgAdmin.Browser.docker.findPanels('frm_datagrid'), function(panel) {
           if (panel.isVisible()) {
             window.onbeforeunload = null;
diff --git a/web/pgadmin/tools/user_management/__init__.py b/web/pgadmin/tools/user_management/__init__.py
index 040b34d..89e36c7 100644
--- a/web/pgadmin/tools/user_management/__init__.py
+++ b/web/pgadmin/tools/user_management/__init__.py
@@ -13,7 +13,7 @@ import simplejson as json
 import re
 
 from flask import render_template, request, \
-    url_for, Response, abort
+    url_for, Response, abort, current_app
 from flask_babel import gettext as _
 from flask_security import login_required, roles_required, current_user
 from flask_security.utils import encrypt_password
@@ -73,7 +73,7 @@ class UserManagementModule(PgAdminModule):
             'user_management.roles', 'user_management.role',
             'user_management.update_user', 'user_management.delete_user',
             'user_management.create_user', 'user_management.users',
-            'user_management.user'
+            'user_management.user', current_app.login_manager.login_view
         ]
 
 
diff --git a/web/pgadmin/tools/user_management/static/js/user_management.js b/web/pgadmin/tools/user_management/static/js/user_management.js
index 8e2f801..2a3b2f0 100644
--- a/web/pgadmin/tools/user_management/static/js/user_management.js
+++ b/web/pgadmin/tools/user_management/static/js/user_management.js
@@ -129,6 +129,95 @@ define([
       alertify.ChangePassword(title, url).resizeTo('75%', '70%');
     },
 
+    is_pga_login_required(xhr) {
+      return xhr.status == 401 && xhr.responseJSON &&
+                xhr.responseJSON.info &&
+                xhr.responseJSON.info == 'PGADMIN_LOGIN_REQUIRED';
+    },
+
+    // Callback to draw pgAdmin4 login dialog.
+    pga_login: function(url) {
+      var title = gettext('pgAdmin 4 login');
+      url = url || url_for('security.login');
+      if(!alertify.PgaLogin) {
+        alertify.dialog('PgaLogin' ,function factory() {
+          return {
+            main: function(title, url) {
+              this.set({
+                'title': title,
+                'url': url,
+              });
+            },
+            build: function() {
+              alertify.pgDialogBuild.apply(this);
+            },
+            settings:{
+              url: undefined,
+            },
+            setup:function() {
+              return {
+                buttons: [{
+                  text: gettext('Close'), key: 27,
+                  className: 'btn btn-danger fa fa-lg fa-times pg-alertify-button',
+                  attrs:{name:'close', type:'button'},
+                }],
+                // Set options for dialog
+                options: {
+                  //disable both padding and overflow control.
+                  padding : !1,
+                  overflow: !1,
+                  modal: true,
+                  resizable: true,
+                  maximizable: true,
+                  pinnable: false,
+                  closableByDimmer: false,
+                  closable: false,
+                },
+              };
+            },
+            hooks: {
+              // Triggered when the dialog is closed
+              onclose: function() {
+                // Clear the view
+                return setTimeout((function() {
+                  return alertify.PgaLogin().destroy();
+                }));
+              },
+            },
+            prepare: function() {
+              // create the iframe element
+              var self = this,
+                iframe = document.createElement('iframe'),
+                url = this.setting('url');
+
+              iframe.onload = function() {
+                var doc = this.contentDocument || this.contentWindow.document;
+                if (doc.location.href.indexOf(url) == -1) {
+                  // login successful.
+
+                  this.contentWindow.stop();
+                  this.onload = null;
+
+                  // close the dialog.
+                  self.close();
+                  pgBrowser.Events.trigger('pgadmin:user:logged-in');
+                }
+              };
+
+              iframe.frameBorder = 'no';
+              iframe.width = '100%';
+              iframe.height = '100%';
+              iframe.src = url;
+              // add it to the dialog
+              self.elements.content.appendChild(iframe);
+            },
+          };
+        });
+      }
+
+      alertify.PgaLogin(title, url).resizeTo('75%','70%');
+    },
+
     // Callback to draw User Management Dialog.
     show_users: function() {
       if (!userInfo['is_admin']) return;
diff --git a/web/pgadmin/utils/driver/psycopg2/__init__.py b/web/pgadmin/utils/driver/psycopg2/__init__.py
index 7c9fb07..0c3eea8 100644
--- a/web/pgadmin/utils/driver/psycopg2/__init__.py
+++ b/web/pgadmin/utils/driver/psycopg2/__init__.py
@@ -179,6 +179,7 @@ class Connection(BaseConnection):
         res['database'] = self.db
         res['async'] = self.async
         res['wasConnected'] = self.wasConnected
+        res['auto_reconnect'] = self.auto_reconnect
         res['use_binary_placeholder'] = self.use_binary_placeholder
         res['array_to_string'] = self.array_to_string
 
@@ -861,6 +862,13 @@ Failed to execute query (execute_async) for the server #{server_id} - {conn_id}
                 query_id=query_id
             )
             )
+
+            if self.is_disconnected(pe):
+                raise ConnectionLost(
+                    self.manager.sid,
+                    self.db,
+                    None if self.conn_id[0:3] == u'DB:' else self.conn_id[5:]
+                )
             return False, errmsg
 
         self.__async_cursor = cur
@@ -1592,6 +1600,52 @@ Failed to reset the connection to the server due to following error:
 
         return errmsg
 
+    #####
+    # As per issue reported on pgsycopg2 github repository link is shared below
+    # conn.closed is not reliable enough to identify the disconnection from the
+    # database server for some unknown reasons.
+    #
+    # (https://github.com/psycopg/psycopg2/issues/263)
+    #
+    # In order to resolve the issue, sqlalchamey follows the below logic to
+    # identify the disconnection. It relies on exception message to identify
+    # the error.
+    #
+    # Reference (MIT license):
+    # https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/dialects/postgresql/psycopg2.py
+    #
+    def is_disconnected(self, err):
+        if not self.conn.closed:
+            # checks based on strings.  in the case that .closed
+            # didn't cut it, fall back onto these.
+            str_e = str(err).partition("\n")[0]
+            for msg in [
+                # these error messages from libpq: interfaces/libpq/fe-misc.c
+                # and interfaces/libpq/fe-secure.c.
+                'terminating connection',
+                'closed the connection',
+                'connection not open',
+                'could not receive data from server',
+                'could not send data to server',
+                # psycopg2 client errors, psycopg2/conenction.h,
+                # psycopg2/cursor.h
+                'connection already closed',
+                'cursor already closed',
+                # not sure where this path is originally from, it may
+                # be obsolete.   It really says "losed", not "closed".
+                'losed the connection unexpectedly',
+                # these can occur in newer SSL
+                'connection has been closed unexpectedly',
+                'SSL SYSCALL error: Bad file descriptor',
+                'SSL SYSCALL error: EOF detected',
+            ]:
+                idx = str_e.find(msg)
+                if idx >= 0 and '"' not in str_e[:idx]:
+                    return True
+
+            return False
+        return True
+
 
 class ServerManager(object):
     """
@@ -1782,12 +1836,14 @@ WHERE db.oid = {0}""".format(did))
             conn_info = connections[conn_id]
             conn = self.connections[conn_info['conn_id']] = Connection(
                 self, conn_info['conn_id'], conn_info['database'],
-                True, conn_info['async'],
+                conn_info['auto_reconnect'], conn_info['async'],
                 use_binary_placeholder=conn_info['use_binary_placeholder'],
                 array_to_string=conn_info['array_to_string']
             )
-            # only try to reconnect if connection was connected previously.
-            if conn_info['wasConnected']:
+
+            # only try to reconnect if connection was connected previously and
+            # auto_reconnect is true.
+            if conn_info['wasConnected'] and conn_info['auto_reconnect']:
                 try:
                     conn.connect(
                         password=data['password'],
diff --git a/web/pgadmin/utils/exception.py b/web/pgadmin/utils/exception.py
index d50c026..f010d35 100644
--- a/web/pgadmin/utils/exception.py
+++ b/web/pgadmin/utils/exception.py
@@ -28,7 +28,7 @@ class ConnectionLost(HTTPException):
 
     @property
     def name(self):
-        return HTTP_STATUS_CODES.get(505, 'Service Unavailable')
+        return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
 
     def get_response(self, environ=None):
         return service_unavailable(
diff --git a/web/pgadmin/utils/session.py b/web/pgadmin/utils/session.py
index 437539c..b7d4595 100644
--- a/web/pgadmin/utils/session.py
+++ b/web/pgadmin/utils/session.py
@@ -24,6 +24,9 @@ import random
 import string
 import time
 from uuid import uuid4
+from flask import current_app, request, flash, redirect
+from flask_login import login_url
+from pgadmin.utils.ajax import make_json_response
 
 try:
     from cPickle import dump, load
@@ -298,3 +301,32 @@ def create_session_interface(app, skip_paths=[]):
             1000
         ), skip_paths,
         datetime.timedelta(days=1))
+
+
+def pga_unauthorised():
+
+    lm = current_app.login_manager
+    login_message = None
+
+    if lm.login_message:
+        if lm.localize_callback is not None:
+            login_message = lm.localize_callback(lm.login_message)
+        else:
+            login_message = lm.login_message
+
+    if not lm.login_view or request.is_xhr:
+        # Only 401 is not enough to distinguish pgAdmin login is required.
+        # There are other cases when we return 401. For eg. wrong password
+        # supplied while connecting to server.
+        # So send additional 'info' message.
+        return make_json_response(
+            status=401,
+            success=0,
+            errormsg=login_message,
+            info='PGADMIN_LOGIN_REQUIRED'
+        )
+
+    if login_message:
+        flash(login_message, category=lm.login_message_category)
+
+    return redirect(login_url(lm.login_view, request.url))
