*** a/src/backend/utils/adt/ruleutils.c
--- b/src/backend/utils/adt/ruleutils.c
***************
*** 6398,6405 **** appendContextKeyword(deparse_context *context, const char *str,
  		removeStringInfoSpaces(buf);
  		/* ... then add a newline and some spaces */
  		appendStringInfoChar(buf, '\n');
! 		appendStringInfoSpaces(buf,
! 							   Max(context->indentLevel, 0) + indentPlus);
  
  		appendStringInfoString(buf, str);
  
--- 6398,6419 ----
  		removeStringInfoSpaces(buf);
  		/* ... then add a newline and some spaces */
  		appendStringInfoChar(buf, '\n');
! 
! 		if (context->indentLevel <= 40)
! 			appendStringInfoSpaces(buf,
! 								   Max(context->indentLevel, 0) + indentPlus);
! 			
! 		else
! 		{
! 			/* If we're indented > 40 characters try to conserve horizontal
! 			 * space. Specifically it's important that the indentation not
! 			 * grow unboundedly or else the size of some queries is
! 			 * O(n^2). Wrapping modulo 40 guarantees at most a linear blowup
! 			 * in size. */
! 			unsigned wrapped_indent = context->indentLevel + indentPlus;
! 			wrapped_indent = (wrapped_indent / (PRETTYINDENT_STD/2)) % 40;
! 			appendStringInfoSpaces(buf, wrapped_indent);
! 		}			
  
  		appendStringInfoString(buf, str);
  
