diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index b83a2ef..2b114e0 100644
*** a/src/backend/libpq/pqcomm.c
--- b/src/backend/libpq/pqcomm.c
*************** internal_flush(void)
*** 1247,1255 ****
  
  			/*
  			 * We drop the buffered data anyway so that processing can
! 			 * continue, even though we'll probably quit soon.
  			 */
  			PqSendStart = PqSendPointer = 0;
  			return EOF;
  		}
  
--- 1247,1260 ----
  
  			/*
  			 * We drop the buffered data anyway so that processing can
! 			 * continue, even though we'll probably quit soon. We also
! 			 * set a flag that'll cause the next CHECK_FOR_INTERRUPTS
! 			 * to cancel the current query.
  			 */
  			PqSendStart = PqSendPointer = 0;
+ 			InterruptPending = 1;
+ 			QueryCancelPending = 1;
+ 			ClientConnectionLostPending = 1;
  			return EOF;
  		}
  
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 976a832..5e53c24 100644
*** a/src/backend/tcop/postgres.c
--- b/src/backend/tcop/postgres.c
*************** ProcessInterrupts(void)
*** 2876,2881 ****
--- 2876,2891 ----
  				 errmsg("canceling statement due to conflict with recovery"),
  						 errdetail_recovery_conflict()));
  		}
+ 		if (ClientConnectionLostPending)
+ 		{
+ 			ImmediateInterruptOK = false;		/* not idle anymore */
+ 			ClientConnectionLostPending = false;
+ 			DisableNotifyInterrupt();
+ 			DisableCatchupInterrupt();
+ 			ereport(FATAL,
+ 					(errcode(ERRCODE_QUERY_CANCELED),
+ 					 errmsg("canceling statement due to client disconnect")));
+ 		}
  
  		/*
  		 * If we are reading a command from the client, just ignore the cancel
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index c4c4154..a8201ed 100644
*** a/src/backend/utils/init/globals.c
--- b/src/backend/utils/init/globals.c
*************** ProtocolVersion FrontendProtocol;
*** 29,34 ****
--- 29,35 ----
  volatile bool InterruptPending = false;
  volatile bool QueryCancelPending = false;
  volatile bool ProcDiePending = false;
+ bool ClientConnectionLostPending = false;
  volatile bool ImmediateInterruptOK = false;
  volatile uint32 InterruptHoldoffCount = 0;
  volatile uint32 CritSectionCount = 0;
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 9d19417..78ebbe3 100644
*** a/src/include/miscadmin.h
--- b/src/include/miscadmin.h
*************** extern PGDLLIMPORT volatile bool Interru
*** 70,75 ****
--- 70,77 ----
  extern volatile bool QueryCancelPending;
  extern volatile bool ProcDiePending;
  
+ extern bool ClientConnectionLostPending;
+ 
  /* these are marked volatile because they are examined by signal handlers: */
  extern volatile bool ImmediateInterruptOK;
  extern PGDLLIMPORT volatile uint32 InterruptHoldoffCount;
