*** src/backend/commands/portalcmds.c.orig	Thu Sep 16 12:58:28 2004
--- src/backend/commands/portalcmds.c	Sun Nov 28 17:02:22 2004
***************
*** 62,73 ****
  		RequireTransactionChain((void *) stmt, "DECLARE CURSOR");
  
  	/*
  	 * The query has been through parse analysis, but not rewriting or
  	 * planning as yet.  Note that the grammar ensured we have a SELECT
  	 * query, so we are not expecting rule rewriting to do anything
  	 * strange.
  	 */
! 	rewritten = QueryRewrite((Query *) stmt->query);
  	if (list_length(rewritten) != 1 || !IsA(linitial(rewritten), Query))
  		elog(ERROR, "unexpected rewrite result");
  	query = (Query *) linitial(rewritten);
--- 62,82 ----
  		RequireTransactionChain((void *) stmt, "DECLARE CURSOR");
  
  	/*
+ 	 * Because the planner is not cool about not scribbling on its input,
+ 	 * we make a preliminary copy of the source querytree.  This prevents
+ 	 * problems in the case that the DECLARE CURSOR is in a portal and is
+ 	 * executed repeatedly.  XXX the planner really shouldn't modify its
+ 	 * input ... FIXME someday.
+ 	 */
+ 	query = copyObject(stmt->query);
+ 
+ 	/*
  	 * The query has been through parse analysis, but not rewriting or
  	 * planning as yet.  Note that the grammar ensured we have a SELECT
  	 * query, so we are not expecting rule rewriting to do anything
  	 * strange.
  	 */
! 	rewritten = QueryRewrite(query);
  	if (list_length(rewritten) != 1 || !IsA(linitial(rewritten), Query))
  		elog(ERROR, "unexpected rewrite result");
  	query = (Query *) linitial(rewritten);
