diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 412dfe6..dfc91d1 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -39,6 +39,7 @@
 #include "nodes/nodeFuncs.h"
 #include "optimizer/clauses.h"
 #include "optimizer/tlist.h"
+#include "parser/analyze.h"
 #include "parser/keywords.h"
 #include "parser/parse_func.h"
 #include "parser/parse_oper.h"
@@ -47,6 +48,7 @@
 #include "rewrite/rewriteHandler.h"
 #include "rewrite/rewriteManip.h"
 #include "rewrite/rewriteSupport.h"
+#include "tcop/tcopprot.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/fmgroids.h"
@@ -435,6 +437,39 @@ pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
 	PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags)));
 }
 
+
+Datum
+pg_pretty_query(PG_FUNCTION_ARGS)
+{
+	text	*qstring = PG_GETARG_TEXT_P(0);
+	bool	indent = PG_GETARG_BOOL(1);
+	bool	paren = PG_GETARG_BOOL(2);
+	int		prettyFlags;
+	Query *query;
+	StringInfoData  buf;
+	List			*parsetree;
+	const char *query_string;
+
+	query_string = text_to_cstring(qstring);
+	prettyFlags = ( indent ? PRETTYFLAG_INDENT : 0 ) | ( ! paren ? PRETTYFLAG_PAREN : 0 );
+
+	/*
+	 * Do this first so that string is alloc'd in outer context not SPI's.
+	 */
+	initStringInfo(&buf);
+
+	parsetree = pg_parse_query(query_string);
+  
+	query = parse_analyze((Node *) linitial(parsetree), query_string, NULL, 0);
+
+	//query->commandType = CMD_SELECT;
+
+	get_query_def(query, &buf, NIL, NULL, prettyFlags, 0);
+
+	PG_RETURN_TEXT_P(string_to_text(buf.data));
+}
+
+
 /*
  * Common code for by-OID and by-name variants of pg_get_viewdef
  */
diff --git a/src/include/catalog/pg_proc.h b/src/include/catalog/pg_proc.h
index 665918f..5101683 100644
--- a/src/include/catalog/pg_proc.h
+++ b/src/include/catalog/pg_proc.h
@@ -1959,6 +1959,9 @@ DESCR("identity argument list of a function");
 DATA(insert OID = 2165 (  pg_get_function_result	   PGNSP PGUID 12 1 0 0 0 f f f f t f s 1 0 25 "26" _null_ _null_ _null_ _null_ pg_get_function_result _null_ _null_ _null_ ));
 DESCR("result type of a function");
 
+DATA(insert OID = 3839 (  pg_pretty_query	   PGNSP PGUID 12 1 0 0 0 f f f f t f s 3 0 25 "25 16 16" _null_ _null_ _null_ _null_ pg_pretty_query _null_ _null_ _null_ ));
+DESCR("query pretty format");
+
 DATA(insert OID = 1686 (  pg_get_keywords		PGNSP PGUID 12 10 400 0 0 f f f f t t s 0 0 2249 "" "{25,18,25}" "{o,o,o}" "{word,catcode,catdesc}" _null_ pg_get_keywords _null_ _null_ _null_ ));
 DESCR("list of SQL keywords");
 
