*
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.186.4.7 2007/05/01 18:54:16 tgl Exp $
+ *       $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.186.4.8 2007/10/11 21:28:20 tgl Exp $
  *
  * HISTORY
  *       AUTHOR                        DATE                    MAJOR EVENT
        /* Get back to outer memory context */
        MemoryContextSwitchTo(oldcontext);
 
-       /* Must copy result out of sub-context used by expression eval */
+       /*
+        * Must copy result out of sub-context used by expression eval.
+        *
+        * Also, if it's varlena, forcibly detoast it.  This protects us against
+        * storing TOAST pointers into plans that might outlive the referenced
+        * data.
+        */
        if (!const_is_null)
-               const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
+       {
+               if (resultTypLen == -1)
+                       const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
+               else
+                       const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
+       }
 
        /* Release all the junk we just created */
        FreeExecutorState(estate);