diff --git a/web/pgadmin/__init__.py b/web/pgadmin/__init__.py
index 4a16ea1..0020469 100644
--- a/web/pgadmin/__init__.py
+++ b/web/pgadmin/__init__.py
@@ -25,7 +25,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
 
@@ -344,6 +344,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 b7825fc..14b66cf 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 fbd63e6..98ac533 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,9 @@ 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):
     """
@@ -90,11 +92,11 @@ 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
@@ -104,6 +106,7 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
     Args:
         cmd_type: Contains value for which menu item is clicked.
         obj_type: Contains type of selected object for which data grid to be render
+        sgid: Server group Id
         sid: Server Id
         did: Database Id
         obj_id: Id of currently selected object
@@ -118,15 +121,26 @@ 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,
                                   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:
@@ -135,10 +149,13 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
             obj_type = 'table'
 
         # Get the object as per the object type
-        command_obj = ObjectRegistry.get_object(obj_type, conn_id=conn_id, sid=sid,
-                                                did=did, obj_id=obj_id, cmd_type=cmd_type,
+        command_obj = ObjectRegistry.get_object(obj_type, conn_id=conn_id,
+                                                sgid=sgid, sid=sid, did=did,
+                                                obj_id=obj_id,
+                                                cmd_type=cmd_type,
                                                 sql_filter=filter_sql)
     except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
     # Create a unique id for the transaction
@@ -161,9 +178,11 @@ def initialize_datagrid(cmd_type, obj_type, sid, did, obj_id):
 
     pref = Preferences.module('sqleditor')
     new_browser_tab = pref.preference('new_browser_tab').get()
-
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
     return make_json_response(data={'gridTransId': trans_id,
-                                    'newBrowserTab': new_browser_tab})
+                                    'newBrowserTab': new_browser_tab,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -223,15 +242,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
@@ -248,6 +258,23 @@ 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,
@@ -265,48 +292,41 @@ 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
     """
 
     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.'
-                )
-            )
-
+        manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid)
+        did = manager.did
     try:
-        command_obj = ObjectRegistry.get_object('query_tool', sid=sid, did=did)
+        command_obj = ObjectRegistry.get_object('query_tool', sgid=sgid,
+                                                sid=sid, did=did)
     except Exception as e:
+        app.logger.error(e)
         return internal_server_error(errormsg=str(e))
 
     # Create a unique id for the transaction
@@ -343,6 +363,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
@@ -359,13 +381,15 @@ def close(trans_id):
             manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(cmd_obj.sid)
             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
         if conn.connected():
             manager.release(did=cmd_obj.did, conn_id=cmd_obj.conn_id)
 
-        # Remove the information of unique transaction id from the session variable.
+        # Remove the information of unique transaction id from the session
+        # variable.
         grid_data.pop(str(trans_id), None)
         session['gridData'] = grid_data
 
@@ -397,6 +421,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 24a49ae..2caba64 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.
@@ -11,27 +12,29 @@ define('pgadmin.datagrid', [
     pgBrowser = pgAdmin.Browser,
     CodeMirror = codemirror.default;
 
-  /* Return back, this has been called more than once */
-  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',
+    /* Return back, this has been called more than once */
+    if (pgAdmin.DataGrid)
+      return pgAdmin.DataGrid;
+
+    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
@@ -68,465 +71,424 @@ define('pgadmin.datagrid', [
           }
         };
 
-      // 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);
-    },
+          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
+            },
+            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...'),
+         });
+        }
 
-    // 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;
-      }
+        pgAdmin.Browser.add_menu_category('view_data', gettext('View/Edit Data'), 100, '');
+        pgAdmin.Browser.add_menus(menus);
 
-      // Get the parent data from the tree node hierarchy.
-      var node = pgBrowser.Nodes[d._type],
-        parentData = node.getTreeNodeHierarchy(i);
+        // 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',
+        });
 
-      // 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;
-      }
+        // 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;
+        }
 
-      var nsp_name = '';
+        // Get the parent data from the tree node hierarchy.
+        var node = pgBrowser.Nodes[d._type],
+          parentData = node.getTreeNodeHierarchy(i);
 
-      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);
-    },
+        // 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;
+        }
 
-    // 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 nsp_name = '';
 
-      // Get the parent data from the tree node hierarchy.
-      var node = pgBrowser.Nodes[d._type],
-        parentData = node.getTreeNodeHierarchy(i);
+        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
+        };
 
-      // If server or database is undefined then return from the function.
-      if (parentData.server === undefined || parentData.database === undefined) {
-        return;
-      }
+        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;
+        }
 
-      // 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 the parent data from the tree node hierarchy.
+        var node = pgBrowser.Nodes[d._type],
+          parentData = node.getTreeNodeHierarchy(i);
 
-      var nsp_name = '';
+        // If server or database is undefined then return from the function.
+        if (parentData.server === undefined || parentData.database === undefined) {
+          return;
+        }
 
-      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;
-      }
+        // 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 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;
-            },
+        var nsp_name = '';
 
-            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');
+        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;
+        }
 
-              $(this.elements.body.childNodes[0]).addClass(
-                'dataview_filter_dialog'
-              );
+        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
+        };
 
-              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);
-            },
+        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
+                });
 
-            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(
+                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);
+                      }
+                      else {
+                        alertify.alert(
+                          gettext('Validation Error'),
+                            res.data.result
+                        );
+                      }
+                    },
+                    error: function(e) {
+                      alertify.alert(
                         gettext('Validation Error'),
-                        res.data.result
+                        e
                       );
                     }
-                  },
-                  error: function(e) {
-                    Alertify.alert(
-                      gettext('Validation Error'),
-                      e
-                    );
-                  },
-                });
+                  });
+                }
               }
-            },
-          };
-        });
-      }
-
-      $.get(url_for('datagrid.filter'),
-        function(data) {
-          Alertify.filterDialog('Data Filter', data, baseUrl, validateUrl)
-            .resizeTo(300, 200);
+            };
+          });
         }
-      );
-    },
 
-    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;
-    },
-
-    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) {
-
-          /* 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 content = '';
+        $.get(url_for('datagrid.filter'),
+          function(data) {
+            alertify.filterDialog('Data Filter', data, baseUrl, validateUrl)
+                    .resizeTo(300, 200);
+          }
+        );
+      },
 
-          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_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 self = this;
 
-            // 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',
-              });
-            });
+        var node = pgBrowser.Nodes[item_data._type],
+          parentData = node.getTreeNodeHierarchy(selected_item);
 
-            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);
-                }
-              }, 100);
-            };
-
-            openDataGridURL(dataGridPanel);
-          }
-        },
-        error: function() {
-          Alertify.alert(
-            gettext('Error'),
-            gettext('Query Tool Initialization Error')
+        // 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 self = this,
+          sURL = url || '',
+          panel_title = panel_title || '',
+          d = pgAdmin.Browser.tree.itemData(i);
+        if (d === undefined) {
+          alertify.alert(
+            gettext('Query Tool Error'),
+            gettext('No object selected.')
           );
-        },
-      });
-    },
-
-    // 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);
-
-      panel_title = panel_title || '';
+          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);
 
-      // 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;
+        }
 
-      // If server, database is undefined then return from the function.
-      if (parentData.server === undefined) {
-        return;
-      }
+        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, '');
+      },
+      create_transaction: function(baseUrl, target, is_query_tool, server_type, sURL, panel_title, sql_filter) {
+        var self = this;
+        target =  target || self;
+
+        $.ajax({
+          url: baseUrl,
+          method: 'POST',
+          dataType: 'json',
+          data: JSON.stringify(sql_filter),
+          contentType: 'application/json',
+          success: function(res) {
+            self.handle_connection_reset(res.data);
+            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, status, error) {
+            if (target !== self) {
+              if(xhr.status == 503 && xhr.responseJSON.info != undefined &&
+                  xhr.responseJSON.info == 'CONNECTION_LOST') {
+                setTimeout(function() {
+                  target.handle_connection_lost(true);
+                });
+                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();
+            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',
-            'editor_title': encodeURIComponent(grid_title),
-          };
-
-          var baseUrl = url_for('datagrid.panel', url_params) +
-            '?' + 'query_url=' + encodeURI(sURL) + '&server_type=' + encodeURIComponent(parentData.server.server_type);
+          url_params = {
+            'trans_id': trans_obj.gridTransId,
+            'is_query_tool': trans_obj.is_query_tool,
+            'editor_title': encodeURIComponent(grid_title)
+          },
+          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 =
@@ -534,64 +496,65 @@ 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);
+        }
+      },
+      handle_connection_reset: function(res) {
+        if (res.connection_reset && res.connection_reset == true) {
+          setTimeout(function() {
+            alertify.alert(gettext('Connection reset'),
+              gettext('Connection has been reset. This is because one of the reasons connection was idle for long time period and was closed, application server or database server was restarted, user session was timed out.'));
+          });
+        }
+      }
     },
-  };
+    Backbone.Events);
 
   return pgAdmin.DataGrid;
-});
\ No newline at end of file
+});
diff --git a/web/pgadmin/tools/datagrid/templates/datagrid/index.html b/web/pgadmin/tools/datagrid/templates/datagrid/index.html
index c0f7d99..4385a0a 100644
--- a/web/pgadmin/tools/datagrid/templates/datagrid/index.html
+++ b/web/pgadmin/tools/datagrid/templates/datagrid/index.html
@@ -25,7 +25,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 f967a15..7e2dffb 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
 
@@ -85,7 +87,6 @@ class SqlEditorModule(PgAdminModule):
             'when': None
         }]
 
-
     def get_panels(self):
         return []
 
@@ -390,9 +391,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']
 
@@ -412,7 +415,10 @@ def check_transaction_status(trans_id):
         conn = manager.connection(did=trans_obj.did, conn_id=trans_obj.conn_id,
                                   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():
@@ -439,12 +445,23 @@ def start_view_data(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)
+
     # 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():
@@ -488,8 +505,12 @@ def start_view_data(trans_id):
             update_session_grid_transaction(trans_id, session_obj)
 
             # Execute sql asynchronously
-            status, result = conn.execute_async(sql)
+            try:
+                status, result = conn.execute_async(sql)
+            except ConnectionLost as e:
+                raise
         except Exception as e:
+            current_app.logger.error(e)
             return internal_server_error(errormsg=str(e))
     else:
         status = False
@@ -499,13 +520,17 @@ def start_view_data(trans_id):
         can_filter = False
         sql = None
 
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
     return make_json_response(
         data={
             'status': status, 'result': result,
             'filter_applied': filter_applied,
             'limit': limit, 'can_edit': can_edit,
             'can_filter': can_filter, 'sql': sql,
-            'info_notifier_timeout': blueprint.info_notifier_timeout.get()
+            'info_notifier_timeout': blueprint.info_notifier_timeout.get(),
+            'connection_reset': connection_reset
         }
     )
 
@@ -530,24 +555,19 @@ def start_query_tool(trans_id):
 
     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
@@ -572,13 +592,17 @@ def start_query_tool(trans_id):
             conn = manager.connection(did=trans_obj.did, conn_id=conn_id,
                                       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():
             status, msg = conn.connect()
             if not status:
+                current_app.logger.error(msg)
                 return internal_server_error(errormsg=str(msg))
 
         if conn.connected():
@@ -602,8 +626,10 @@ def start_query_tool(trans_id):
 
             # Execute sql asynchronously with params is None
             # and formatted_error is True.
-            status, result = conn.execute_async(sql)
-
+            try:
+                status, result = conn.execute_async(sql)
+            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()
@@ -620,11 +646,15 @@ def start_query_tool(trans_id):
         status = False
         result = gettext('Either transaction object or session object not found.')
 
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
     return make_json_response(
         data={
             'status': status, 'result': result,
             'can_edit': can_edit, 'can_filter': can_filter,
-            'info_notifier_timeout': blueprint.info_notifier_timeout.get()
+            'info_notifier_timeout': blueprint.info_notifier_timeout.get(),
+            'connection_reset': connection_reset
         }
     )
 
@@ -645,9 +675,16 @@ def preferences(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:
-            # Call the set_auto_commit and set_auto_rollback method of transaction object
+            # Call the set_auto_commit and set_auto_rollback method of
+            # transaction object
             trans_obj.set_auto_commit(blueprint.auto_commit.get())
             trans_obj.set_auto_rollback(blueprint.auto_rollback.get())
 
@@ -656,6 +693,9 @@ def preferences(trans_id):
             session_obj['command_obj'] = pickle.dumps(trans_obj, -1)
             update_session_grid_transaction(trans_id, session_obj)
 
+        connection_reset = conn.is_renewed
+        conn.is_renewed = False
+
         return make_json_response(
             data={
                 'explain_verbose': blueprint.explain_verbose.get(),
@@ -663,7 +703,8 @@ def preferences(trans_id):
                 'explain_buffers': blueprint.explain_buffers.get(),
                 'explain_timing': blueprint.explain_timing.get(),
                 'auto_commit': blueprint.auto_commit.get(),
-                'auto_rollback': blueprint.auto_rollback.get()
+                'auto_rollback': blueprint.auto_rollback.get(),
+                'connection_reset': connection_reset
             }
         )
     else:
@@ -711,6 +752,12 @@ 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)
         if not status:
@@ -889,6 +936,12 @@ 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:
@@ -1002,6 +1055,14 @@ 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)
+
+    connection_reset = False
+
     if status and conn is not None \
             and trans_obj is not None and session_obj is not None:
 
@@ -1025,7 +1086,7 @@ def save(trans_id):
                     data={'status': status, 'result': u"{}".format(msg)}
                 )
 
-        status, res, query_res, _rowid = trans_obj.save(
+        status, res, query_res, _rowid, connection_reset = trans_obj.save(
             changed_data,
             session_obj['columns_info'],
             session_obj['client_primary_key'],
@@ -1040,7 +1101,8 @@ def save(trans_id):
             'status': status,
             'result': res,
             'query_result': query_res,
-            '_rowid': _rowid
+            '_rowid': _rowid,
+            'connection_reset': connection_reset
         }
     )
 
@@ -1060,6 +1122,11 @@ 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:
 
@@ -1068,7 +1135,11 @@ def get_filter(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1090,6 +1161,12 @@ 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:
 
@@ -1103,7 +1180,11 @@ def apply_filter(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1125,6 +1206,12 @@ 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:
 
@@ -1149,7 +1236,11 @@ def append_filter_inclusive(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1171,6 +1262,11 @@ 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:
 
@@ -1214,6 +1310,12 @@ 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:
 
@@ -1230,7 +1332,11 @@ def remove_filter(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1251,6 +1357,12 @@ 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:
 
@@ -1267,7 +1379,11 @@ def set_limit(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1283,15 +1399,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
@@ -1353,6 +1474,12 @@ 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:
 
@@ -1361,7 +1488,11 @@ def get_object_name(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1383,6 +1514,12 @@ 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:
 
@@ -1402,7 +1539,11 @@ def set_auto_commit(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1424,6 +1565,12 @@ 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:
 
@@ -1443,7 +1590,11 @@ def set_auto_rollback(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route(
@@ -1472,6 +1623,12 @@ 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:
 
@@ -1484,7 +1641,11 @@ def auto_complete(trans_id):
         status = False
         res = error_msg
 
-    return make_json_response(data={'status': status, 'result': res})
+    connection_reset = conn.is_renewed
+    conn.is_renewed = False
+
+    return make_json_response(data={'status': status, 'result': res,
+                                    'connection_reset': connection_reset})
 
 
 @blueprint.route("/sqleditor.js")
@@ -1884,7 +2045,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 97f13ea..d27e5d3 100644
--- a/web/pgadmin/tools/sqleditor/command.py
+++ b/web/pgadmin/tools/sqleditor/command.py
@@ -103,7 +103,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
 
@@ -493,7 +495,6 @@ class TableCommand(GridCommand):
                 if len(changed_data[of_type]) < 1:
                     continue
 
-
                 column_type = {}
                 column_data = {}
                 for each_col in columns_info:
@@ -639,7 +640,10 @@ class TableCommand(GridCommand):
                             except Exception:
                                 _rowid = 0
 
-                            return status, res, query_res, _rowid
+                            connection_reset = conn.is_renewed
+                            conn.is_renewed = False
+
+                            return status, res, query_res, _rowid, connection_reset
 
                         # Select added row from the table
                         if 'select_sql' in item:
@@ -660,7 +664,9 @@ class TableCommand(GridCommand):
                                 except Exception:
                                     _rowid = 0
 
-                                return status, sel_res, query_res, _rowid
+                                connection_reset = conn.is_renewed
+                                conn.is_renewed = False
+                                return status, sel_res, query_res, _rowid, connection_reset
 
                             if 'rows' in sel_res and len(sel_res['rows']) > 0:
                                 row_added = {item['client_row']: sel_res['rows'][0]}
@@ -676,8 +682,9 @@ class TableCommand(GridCommand):
 
             # Commit the transaction if there is no error found
             conn.execute_void('COMMIT;')
-
-        return status, res, query_res, _rowid
+        connection_reset = conn.is_renewed
+        conn.is_renewed = False
+        return status, res, query_res, _rowid, connection_reset
 
 
 class ViewCommand(GridCommand):
diff --git a/web/pgadmin/tools/sqleditor/static/js/sqleditor.js b/web/pgadmin/tools/sqleditor/static/js/sqleditor.js
index 590996b..479137a 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/sqleditor/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) {
@@ -296,10 +304,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 () {
@@ -315,7 +319,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(
@@ -412,6 +416,7 @@ define('tools.querytool', [
               contentType: 'application/json',
               data: JSON.stringify(self.data),
               success: function(res) {
+                handle_connection_reset(res.data);
                 var result = [];
 
                 _.each(res.data.result, function(obj, key) {
@@ -473,6 +478,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),
         };
@@ -501,7 +514,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
         );
       }
@@ -1096,7 +1109,7 @@ define('tools.querytool', [
           'fetch_all': 1,
         });
       } else {
-        url = url = url_for('sqleditor.fetch', {
+        url = url_for('sqleditor.fetch', {
           'trans_id': self.transId,
         });
       }
@@ -1128,7 +1141,11 @@ define('tools.querytool', [
             );
             return;
           }
-        },
+
+          if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+            pgAdmin.Browser.UserManagement.pga_login();
+          }
+        }
       });
     },
 
@@ -1280,6 +1297,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);
 
@@ -1712,16 +1730,141 @@ define('tools.querytool', [
 
   _.extend(
     SqlEditorController.prototype,
-    Backbone.Events, {
-      initialize: function(container) {
+    Backbone.Events,
+    {
+      initialize: function(container, opts) {
+        self= this;
         this.container = container;
+        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;
+          if (self.is_query_tool) {
+            alertify.success(gettext('New SQL editor session created.'));
+          } else {
+            alertify.success(gettext('New Data grid session created.'));
+          }
+        });
+        pgBrowser.Events.on('pgadmin:user:logged-in', function() {
+          self.init_transaction();
+        });
+      },
+
+      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, '', '', '');
+      },
+
+      handle_connection_lost: function(create_transaction) {
+        var self= this;
+        alertify.confirm(
+            gettext('Connection lost'),
+            gettext('Would you like to reconnect to the server?'),
+            function() {
+              self.init_connection(create_transaction);
+            }, function() {});
       },
 
+      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();
+            }
+          }
+        })
+        .fail(function(xhr, status, error) {
+          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;
@@ -1737,6 +1880,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)
@@ -1746,7 +1891,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;
@@ -1754,6 +1899,59 @@ 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 = jqx.responseText;
+                self.init_events();
+
+                if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+                  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) {}
+                }
+                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);
@@ -1787,22 +1985,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
@@ -1867,7 +2049,7 @@ define('tools.querytool', [
           method: 'GET',
           success: function(res) {
             if (res.data.status) {
-
+              Datagrid.handle_connection_reset(res.data);
               self.can_edit = res.data.can_edit;
               self.can_filter = res.data.can_filter;
               self.info_notifier_timeout = res.data.info_notifier_timeout;
@@ -1914,14 +2096,30 @@ define('tools.querytool', [
               );
               return;
             }
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              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.handle_connection_lost();
+                });
+              }
+            }
 
             self.update_msg_history(false, msg);
-          },
+          }
         });
       },
 
@@ -1931,8 +2129,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
@@ -2021,6 +2219,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)
@@ -2481,7 +2683,7 @@ define('tools.querytool', [
               'dialog_type': 'create_file',
               'dialog_title': 'Save File',
               'btn_primary': 'Save',
-            };
+            }
             pgAdmin.FileManager.init();
             pgAdmin.FileManager.show_dialog(params);
           }
@@ -2512,7 +2714,7 @@ define('tools.querytool', [
           // Make ajax call to save the data
           $.ajax({
             url: url_for('sqleditor.save', {
-              'trans_id': self.transId,
+              'trans_id': self.transId
             }),
             method: 'POST',
             contentType: 'application/json',
@@ -2524,7 +2726,8 @@ define('tools.querytool', [
                 data = [];
 
               if (res.data.status) {
-                if (is_added) {
+                Datagrid.handle_connection_reset(res.data);
+                if(is_added) {
                   // Update the rows in a grid after addition
                   dataView.beginUpdate();
                   _.each(res.data.query_result, function(r) {
@@ -2644,13 +2847,17 @@ define('tools.querytool', [
                 return;
               }
 
+              if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+                pgAdmin.Browser.UserManagement.pga_login();
+              }
+
               var msg = e.responseText;
               if (e.responseJSON != undefined &&
                 e.responseJSON.errormsg != undefined)
                 msg = e.responseJSON.errormsg;
 
               self.update_msg_history(false, msg);
-            },
+            }
           });
         }
       },
@@ -2788,9 +2995,13 @@ define('tools.querytool', [
             self.is_query_changed = false;
           },
           error: function(e) {
+            self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(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');
           },
@@ -2834,6 +3045,9 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
 
             var errmsg = $.parseJSON(e.responseText).errormsg;
             setTimeout(
@@ -2918,6 +3132,7 @@ define('tools.querytool', [
             if (res.data.status) {
               $('#filter').removeClass('hidden');
               $('#editor-panel').addClass('sql-editor-busy-fetching');
+              Datagrid.handle_connection_reset(res.data);
               self.gridView.filter_obj.refresh();
 
               if (res.data.result == null)
@@ -2937,6 +3152,14 @@ define('tools.querytool', [
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
 
+            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();
+            }
+
             var msg;
             if (e.readyState == 0) {
               msg =
@@ -2994,6 +3217,7 @@ define('tools.querytool', [
           data: JSON.stringify(data),
           success: function(res) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            Datagrid.handle_connection_reset(res.data);
             setTimeout(
               function() {
                 if (res.data.status) {
@@ -3007,6 +3231,14 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            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();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3024,7 +3256,7 @@ define('tools.querytool', [
                 alertify.alert(gettext('Filter By Selection Error'), msg);
               }, 10
             );
-          },
+          }
         });
       },
 
@@ -3066,6 +3298,7 @@ define('tools.querytool', [
           data: JSON.stringify(data),
           success: function(res) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            Datagrid.handle_connection_reset(res.data);
             setTimeout(
               function() {
                 if (res.data.status) {
@@ -3079,6 +3312,13 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            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();
+            }
 
             setTimeout(
               function() {
@@ -3118,6 +3358,7 @@ define('tools.querytool', [
           method: 'POST',
           success: function(res) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            Datagrid.handle_connection_reset(res.data);
             setTimeout(
               function() {
                 if (res.data.status) {
@@ -3131,6 +3372,14 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            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();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3172,6 +3421,7 @@ define('tools.querytool', [
           data: JSON.stringify(sql),
           success: function(res) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            Datagrid.handle_connection_reset(res.data);
             setTimeout(
               function() {
                 if (res.data.status) {
@@ -3187,6 +3437,14 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            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();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3311,6 +3569,7 @@ define('tools.querytool', [
           data: JSON.stringify(limit),
           success: function(res) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            Datagrid.handle_connection_reset(res.data);
             setTimeout(
               function() {
                 if (res.data.status) {
@@ -3323,6 +3582,14 @@ define('tools.querytool', [
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
+            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();
+            }
+
             setTimeout(
               function() {
                 if (e.readyState == 0) {
@@ -3432,6 +3699,7 @@ define('tools.querytool', [
               // Highlight the error in the sql panel
               self._highlight_error(res.data.result);
             }
+            Datagrid.handle_connection_reset(res.data);
           },
           error: function(e) {
             self.trigger('pgadmin-sqleditor:loading-icon:hide');
@@ -3445,11 +3713,26 @@ define('tools.querytool', [
               return;
             }
 
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              pgAdmin.Browser.UserManagement.pga_login();
+            }
+
+            if(is_new_transaction_required(e)) {
+              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.handle_connection_lost();
+                });
+              }
+            }
             self.update_msg_history(false, msg);
           },
         });
@@ -3548,6 +3831,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)
@@ -3593,6 +3880,7 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(auto_rollback),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (!res.data.status)
               alertify.alert(gettext('Auto Rollback Error'), res.data.result);
           },
@@ -3604,6 +3892,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)
@@ -3625,7 +3917,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,
@@ -3634,6 +3926,7 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(auto_commit),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (!res.data.status)
               alertify.alert(gettext('Auto Commit Error'), res.data.result);
           },
@@ -3645,6 +3938,14 @@ define('tools.querytool', [
               return;
             }
 
+            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();
+            }
+
             var msg = e.responseText;
             if (e.responseJSON != undefined &&
               e.responseJSON.errormsg != undefined)
@@ -3679,13 +3980,23 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(data),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (res.success == undefined || !res.success) {
               alertify.alert(gettext('Explain options error'),
                 gettext('Error occurred while setting verbose option in explain.')
               );
             }
           },
-          error: function() {
+          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();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting verbose option in explain.')
             );
@@ -3718,13 +4029,22 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(data),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (res.success == undefined || !res.success) {
               alertify.alert(gettext('Explain options error'),
                 gettext('Error occurred while setting costs option in explain.')
               );
             }
           },
-          error: function() {
+          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();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting costs option in explain.')
             );
@@ -3756,13 +4076,22 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(data),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (res.success == undefined || !res.success) {
               alertify.alert(gettext('Explain options error'),
                 gettext('Error occurred while setting buffers option in explain.')
               );
             }
           },
-          error: function() {
+          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();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting buffers option in explain.')
             );
@@ -3793,13 +4122,22 @@ define('tools.querytool', [
           contentType: 'application/json',
           data: JSON.stringify(data),
           success: function(res) {
+            Datagrid.handle_connection_reset(res.data);
             if (res.success == undefined || !res.success) {
               alertify.alert(gettext('Explain options error'),
                 gettext('Error occurred while setting timing option in explain.')
               );
             }
           },
-          error: function() {
+          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();
+            }
+
             alertify.alert(gettext('Explain options error'),
               gettext('Error occurred while setting timing option in explain.')
             );
@@ -3890,6 +4228,7 @@ define('tools.querytool', [
           method: 'GET',
           success: function(res) {
             if (res.data) {
+              Datagrid.handle_connection_reset(res.data);
               explain_verbose = res.data.explain_verbose;
               explain_costs = res.data.explain_costs;
               explain_buffers = res.data.explain_buffers;
@@ -3899,7 +4238,10 @@ define('tools.querytool', [
               updateUI();
             }
           },
-          error: function() {
+          error: function(e) {
+            if (pgAdmin.Browser.UserManagement.is_pga_login_required(e)) {
+              return pgAdmin.Browser.UserManagement.pga_login();
+            }
             updateUI();
             alertify.alert(
               gettext('Get Preferences error'),
@@ -3910,6 +4252,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 3eb96f5..c0d6f10 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..5c408b3 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..5f77785 100644
--- a/web/pgadmin/utils/driver/psycopg2/__init__.py
+++ b/web/pgadmin/utils/driver/psycopg2/__init__.py
@@ -162,6 +162,7 @@ class Connection(BaseConnection):
         self.reconnecting = False
         self.use_binary_placeholder = use_binary_placeholder
         self.array_to_string = array_to_string
+        self.is_renewed = False
 
         super(Connection, self).__init__()
 
@@ -202,6 +203,7 @@ class Connection(BaseConnection):
 
     def connect(self, **kwargs):
         if self.conn:
+            self.is_renewed = True
             if self.conn.closed:
                 self.conn = None
             else:
@@ -861,6 +863,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
@@ -1117,10 +1126,12 @@ Failed to execute query (execute_void) for the server #{server_id} - {conn_id}
             if not self.conn.closed:
                 return True
             self.conn = None
+            self.is_renewed = True
         return False
 
     def reset(self):
         if self.conn:
+            self.is_renewed = True
             if self.conn.closed:
                 self.conn = None
         pg_conn = None
@@ -1184,6 +1195,7 @@ Failed to reset the connection to the server due to following error:
     def _release(self):
         if self.wasConnected:
             if self.conn:
+                self.is_renewed = True
                 self.conn.close()
                 self.conn = None
             self.password = None
@@ -1592,6 +1604,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):
     """
@@ -1786,6 +1844,7 @@ WHERE db.oid = {0}""".format(did))
                 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']:
                 try:
@@ -1795,6 +1854,7 @@ WHERE db.oid = {0}""".format(did))
                     )
                     # This will also update wasConnected flag in connection so
                     # no need to update the flag manually.
+                    conn.is_renewed = True
                 except Exception as e:
                     current_app.logger.exception(e)
                     self.connections.pop(conn_info['conn_id'])
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))
