#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "lib/stringinfo.h"
#include "nodes/nodes.h"
#include "nodes/pg_list.h"

char *
deparse_expression(Node *expr, List *dpcontext, bool forceprefix);

PG_FUNCTION_INFO_V1(pg_get_expr);

/* ----------
 * get_expr			- Turn a node expression into a expression
 * Used to get the expr used in partial indicies
 * ----------
 */
Datum
pg_get_expr(PG_FUNCTION_ARGS)
{
	text			*expr = PG_GETARG_TEXT_P(0);
	StringInfoData buf;
	text			*result;
	List	*list;
	List	*node;
	char	*str;
	int	len;

	/*
	 * Get the rules definition and put it into executors memory
	 */
	initStringInfo(&buf);
	list = (List*)stringToNode( VARDATA(expr) );
	if( list->type != T_List )
		PG_RETURN_NULL();
		
	foreach( node, list )
	{
		str = deparse_expression( lfirst(node), NULL, true);
		appendStringInfo( &buf, str );
	}
	
	len = buf.len + VARHDRSZ;
	result = palloc(len);
	VARATT_SIZEP(result) = len;
	memcpy(VARDATA(result), buf.data, buf.len);
	pfree(buf.data);

	PG_RETURN_TEXT_P(result);
}

