ScanKeyData key;
        SysScanDesc scan;
        HeapTuple       tuple;
-       MemoryContext oldcxt,
-                               perTupCxt;
+       MemoryContext perTupCxt;
 
        ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
                                F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
 
        perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
                                                                          "clone trig", ALLOCSET_SMALL_SIZES);
-       oldcxt = MemoryContextSwitchTo(perTupCxt);
 
        while (HeapTupleIsValid(tuple = systable_getnext(scan)))
        {
-               Form_pg_trigger trigForm;
+               Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
                CreateTrigStmt *trigStmt;
                Node       *qual = NULL;
                Datum           value;
                bool            isnull;
                List       *cols = NIL;
-
-               trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
+               MemoryContext oldcxt;
 
                /*
                 * Ignore statement-level triggers; those are not cloned.
                        elog(ERROR, "unexpected trigger \"%s\" found",
                                 NameStr(trigForm->tgname));
 
+               /* Use short-lived context for CREATE TRIGGER */
+               oldcxt = MemoryContextSwitchTo(perTupCxt);
+
                /*
                 * If there is a WHEN clause, generate a 'cooked' version of it that's
                 * appropriate for the partition.
                                          trigForm->tgfoid, trigForm->oid, qual,
                                          false, true);
 
+               MemoryContextSwitchTo(oldcxt);
                MemoryContextReset(perTupCxt);
        }
 
-       MemoryContextSwitchTo(oldcxt);
        MemoryContextDelete(perTupCxt);
 
        systable_endscan(scan);