diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 2cbcb4b85e..d6c4b5eb0c 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -1451,14 +1451,24 @@ pg_get_indexdef_worker(Oid indexrelid, int colno,
 		if (showTblSpc)
 		{
 			Oid			tblspc;
+			char	   *spcname = NULL;
 
+			/*
+			 * If this is an index on a partitioned table, it's possible that
+			 * the tablespace was dropped, because there are insufficient
+			 * protections in that case.  Don't add anything if so (and also
+			 * don't crash).
+			 */
 			tblspc = get_rel_tablespace(indexrelid);
-			if (OidIsValid(tblspc))
+			if (tblspc != InvalidOid)
+				spcname = get_tablespace_name(tblspc);
+			if (spcname != NULL)
 			{
 				if (isConstraint)
 					appendStringInfoString(&buf, " USING INDEX");
 				appendStringInfo(&buf, " TABLESPACE %s",
-								 quote_identifier(get_tablespace_name(tblspc)));
+								 quote_identifier(spcname));
+				pfree(spcname);
 			}
 		}
 
@@ -2188,6 +2198,7 @@ pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
 				{
 					char	   *options = flatten_reloptions(indexId);
 					Oid			tblspc;
+					char	   *spcname = NULL;
 
 					if (options)
 					{
@@ -2200,11 +2211,18 @@ pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
 					 * This is to help ALTER TABLE usage of this facility,
 					 * which needs this behavior to recreate exact catalog
 					 * state.
+					 *
+					 * If this is an index on a partitioned table, it's
+					 * possible that the tablespace was dropped, because there
+					 * are insufficient protections in that case.  Don't add
+					 * anything if so (and also don't crash).
 					 */
 					tblspc = get_rel_tablespace(indexId);
-					if (OidIsValid(tblspc))
+					if (tblspc != InvalidOid)
+						spcname = get_tablespace_name(tblspc);
+					if (spcname != NULL)
 						appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
-										 quote_identifier(get_tablespace_name(tblspc)));
+								quote_identifier(spcname));
 				}
 
 				break;
