From: Manu <manuelreyesbravo@gmail.com>
Subject: [PATCH v1 1/3] Find schema members through pg_depend instead of scanning pg_class

GRANT ... ON ALL SEQUENCES | FUNCTIONS | PROCEDURES | ROUTINES IN SCHEMA
and REINDEX SCHEMA scan the whole of pg_class (or pg_proc) to find the
objects of one schema, so their cost grows with the size of the catalog
rather than with the size of the schema.  In a database with many
schemas, one command on a small schema reads every relation of every
other schema.

Every table, view, materialized view, foreign table, sequence and
function created in a schema gets a DEPENDENCY_NORMAL entry in pg_depend
on that schema, except in pinned schemas (pg_catalog, pg_toast).  Add
GetNamespaceRelations() and GetNamespaceFunctions(), which take the
candidates from pg_depend with one scan of pg_depend_reference_index
(new helper getDependentObjectsOfClass()) and recheck each candidate
against its syscache entry, since a pg_depend entry can also come from
an object of another schema that refers to this one (a regnamespace
constant in a partition key or an index expression, for example).

The functions fall back to the catalog scan when the schema is pinned,
and when the candidate count exceeds 1/64 of the estimated catalog
rows. Before selecting a scan, scale the last measured tuple density
to the current page count so catalog growth between ANALYZE runs does
not cause repeated scans of a growing catalog.

When system indexes are ignored, scan the member catalog directly
to avoid scanning pg_depend without its reference index.

Either way the result is sorted by OID: once pg_class is
larger than a quarter of shared_buffers, a catalog scan can start
anywhere (synchronized scans), so the old order changed from one session
to the next.

The new path relies on the namespace entries in pg_depend, which DROP
SCHEMA ... CASCADE already relies on.  An object without its entry would
be skipped silently, so add a query to the oidjoins test that lists
relations and functions of unpinned schemas without one, and, in
assert-enabled builds, cross-check the pg_depend result against the
catalog scan.

Index, TOAST and composite-type relations have no such entry; no caller
asks for those relkinds, and GetNamespaceRelations() asserts that.

---
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index 2bbcc3e824bd4d3cafdfb138f873b59c7ca6d10e..7c4fbab34018198910ce482e24479f5f711f5579 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -800,50 +800,21 @@ objectsInSchemaToOids(ObjectType objtype, List *nspnames)
 				objects = list_concat(objects, objs);
 				break;
 			case OBJECT_SEQUENCE:
-				objs = getRelationsInNamespace(namespaceId, RELKIND_SEQUENCE);
-				objects = list_concat(objects, objs);
+				{
+					static const char seqkinds[] = {RELKIND_SEQUENCE, '\0'};
+
+					objs = GetNamespaceRelations(namespaceId, seqkinds);
+					objects = list_concat(objects, objs);
+				}
 				break;
 			case OBJECT_FUNCTION:
 			case OBJECT_PROCEDURE:
 			case OBJECT_ROUTINE:
-				{
-					ScanKeyData key[2];
-					int			keycount;
-					Relation	rel;
-					TableScanDesc scan;
-					HeapTuple	tuple;
-
-					keycount = 0;
-					ScanKeyInit(&key[keycount++],
-								Anum_pg_proc_pronamespace,
-								BTEqualStrategyNumber, F_OIDEQ,
-								ObjectIdGetDatum(namespaceId));
-
-					if (objtype == OBJECT_FUNCTION)
-						/* includes aggregates and window functions */
-						ScanKeyInit(&key[keycount++],
-									Anum_pg_proc_prokind,
-									BTEqualStrategyNumber, F_CHARNE,
-									CharGetDatum(PROKIND_PROCEDURE));
-					else if (objtype == OBJECT_PROCEDURE)
-						ScanKeyInit(&key[keycount++],
-									Anum_pg_proc_prokind,
-									BTEqualStrategyNumber, F_CHAREQ,
-									CharGetDatum(PROKIND_PROCEDURE));
-
-					rel = table_open(ProcedureRelationId, AccessShareLock);
-					scan = table_beginscan_catalog(rel, keycount, key);
-
-					while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
-					{
-						Oid			oid = ((Form_pg_proc) GETSTRUCT(tuple))->oid;
-
-						objects = lappend_oid(objects, oid);
-					}
-
-					table_endscan(scan);
-					table_close(rel, AccessShareLock);
-				}
+				/* OBJECT_FUNCTION includes aggregates and window functions */
+				objs = GetNamespaceFunctions(namespaceId,
+											 objtype != OBJECT_PROCEDURE,
+											 objtype != OBJECT_FUNCTION);
+				objects = list_concat(objects, objs);
 				break;
 			default:
 				/* should not happen */
diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index f38b7adbd516ff5f0d40c1776d40de2d1cae0018..0561d8cb2c8fe55c5b03bab609bfb2d0f0529139 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -19,17 +19,24 @@
  */
 #include "postgres.h"
 
+#include "access/genam.h"
+#include "access/heapam.h"
 #include "access/htup_details.h"
 #include "access/parallel.h"
+#include "access/table.h"
+#include "access/tableam.h"
 #include "access/xact.h"
 #include "access/xlog.h"
+#include "catalog/catalog.h"
 #include "catalog/dependency.h"
 #include "catalog/namespace.h"
 #include "catalog/objectaccess.h"
 #include "catalog/pg_authid.h"
+#include "catalog/pg_class.h"
 #include "catalog/pg_collation.h"
 #include "catalog/pg_conversion.h"
 #include "catalog/pg_database.h"
+#include "catalog/pg_depend.h"
 #include "catalog/pg_namespace.h"
 #include "catalog/pg_opclass.h"
 #include "catalog/pg_operator.h"
@@ -53,10 +60,12 @@
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/catcache.h"
+#include "utils/fmgroids.h"
 #include "utils/guc_hooks.h"
 #include "utils/inval.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
+#include "utils/rel.h"
 #include "utils/snapmgr.h"
 #include "utils/syscache.h"
 #include "utils/varlena.h"
@@ -3714,6 +3723,366 @@ NameListToQuotedString(const List *names)
 	return string.data;
 }
 
+/*
+ * When a namespace holds more than 1/NAMESPACE_SCAN_DIVISOR of a catalog, one
+ * pass over the catalog is cheaper than a lookup per member.
+ */
+#define NAMESPACE_SCAN_DIVISOR	64
+
+/*
+ * Decide whether to scan the whole catalog rather than look up each of the
+ * "ncandidates" objects that pg_depend lists for a namespace.  Before
+ * choosing a scan, scale the last tuple density to the current catalog
+ * size: the catalog can grow substantially between analyze runs.
+ */
+static bool
+namespace_scan_is_cheaper(Oid catalogId, int ncandidates)
+{
+	Relation	rel;
+	double		reltuples;
+
+	rel = table_open(catalogId, AccessShareLock);
+	reltuples = rel->rd_rel->reltuples;
+	if (reltuples > 0 && ncandidates > reltuples / NAMESPACE_SCAN_DIVISOR)
+	{
+		BlockNumber pages;
+		double		allvisfrac;
+
+		table_relation_estimate_size(rel, NULL, &pages, &reltuples,
+									 &allvisfrac);
+	}
+	table_close(rel, AccessShareLock);
+
+	return reltuples > 0 && ncandidates > reltuples / NAMESPACE_SCAN_DIVISOR;
+}
+
+/*
+ * Scan all of pg_class for the relations in a namespace with one of the
+ * given relkinds.
+ */
+static List *
+scan_namespace_relations(Oid namespaceId, const char *relkinds)
+{
+	List	   *result = NIL;
+	Relation	rel;
+	TableScanDesc scan;
+	ScanKeyData key[1];
+	HeapTuple	tuple;
+
+	ScanKeyInit(&key[0],
+				Anum_pg_class_relnamespace,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(namespaceId));
+
+	rel = table_open(RelationRelationId, AccessShareLock);
+	scan = table_beginscan_catalog(rel, 1, key);
+
+	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
+	{
+		Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
+
+		if (strchr(relkinds, classForm->relkind) != NULL)
+			result = lappend_oid(result, classForm->oid);
+	}
+
+	table_endscan(scan);
+	table_close(rel, AccessShareLock);
+
+	/* see GetNamespaceRelations about the order */
+	list_sort(result, list_oid_cmp);
+	return result;
+}
+
+/*
+ * Scan all of pg_proc for the functions and/or procedures in a namespace.
+ */
+static List *
+scan_namespace_functions(Oid namespaceId, bool functions, bool procedures)
+{
+	List	   *result = NIL;
+	Relation	rel;
+	TableScanDesc scan;
+	ScanKeyData key[1];
+	HeapTuple	tuple;
+
+	ScanKeyInit(&key[0],
+				Anum_pg_proc_pronamespace,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(namespaceId));
+
+	rel = table_open(ProcedureRelationId, AccessShareLock);
+	scan = table_beginscan_catalog(rel, 1, key);
+
+	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
+	{
+		Form_pg_proc procForm = (Form_pg_proc) GETSTRUCT(tuple);
+
+		if (procForm->prokind == PROKIND_PROCEDURE ? procedures : functions)
+			result = lappend_oid(result, procForm->oid);
+	}
+
+	table_endscan(scan);
+	table_close(rel, AccessShareLock);
+
+	/* see GetNamespaceRelations about the order */
+	list_sort(result, list_oid_cmp);
+	return result;
+}
+
+#ifdef USE_ASSERT_CHECKING
+/*
+ * Does object catalogId/objectId have a pg_depend entry on namespaceId?
+ */
+static bool
+object_depends_on_namespace(Oid catalogId, Oid objectId, Oid namespaceId)
+{
+	Relation	depRel;
+	ScanKeyData key[3];
+	SysScanDesc scan;
+	HeapTuple	tup;
+	bool		found = false;
+
+	depRel = table_open(DependRelationId, AccessShareLock);
+
+	ScanKeyInit(&key[0],
+				Anum_pg_depend_classid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(catalogId));
+	ScanKeyInit(&key[1],
+				Anum_pg_depend_objid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(objectId));
+	ScanKeyInit(&key[2],
+				Anum_pg_depend_objsubid,
+				BTEqualStrategyNumber, F_INT4EQ,
+				Int32GetDatum(0));
+
+	scan = systable_beginscan(depRel, DependDependerIndexId, true,
+							  NULL, 3, key);
+
+	while (HeapTupleIsValid(tup = systable_getnext(scan)))
+	{
+		Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
+
+		if (deprec->refclassid == NamespaceRelationId &&
+			deprec->refobjid == namespaceId &&
+			deprec->refobjsubid == 0)
+		{
+			found = true;
+			break;
+		}
+	}
+
+	systable_endscan(scan);
+	table_close(depRel, AccessShareLock);
+
+	return found;
+}
+
+/*
+ * The namespace of a pg_class or pg_proc entry, or InvalidOid if it is gone.
+ */
+static Oid
+object_namespace(Oid catalogId, Oid objectId)
+{
+	HeapTuple	tuple;
+	Oid			result = InvalidOid;
+
+	if (catalogId == RelationRelationId)
+	{
+		tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(objectId));
+		if (HeapTupleIsValid(tuple))
+		{
+			result = ((Form_pg_class) GETSTRUCT(tuple))->relnamespace;
+			ReleaseSysCache(tuple);
+		}
+	}
+	else
+	{
+		Assert(catalogId == ProcedureRelationId);
+		tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(objectId));
+		if (HeapTupleIsValid(tuple))
+		{
+			result = ((Form_pg_proc) GETSTRUCT(tuple))->pronamespace;
+			ReleaseSysCache(tuple);
+		}
+	}
+
+	return result;
+}
+
+/*
+ * Check a member list built from pg_depend against a scan of the catalog.
+ *
+ * The pg_depend route depends on every member having a dependency on its
+ * namespace; one that lacks it would be left out without any error.  So in
+ * assert-enabled builds, every object the scan finds must be in "members",
+ * unless it gained its pg_depend entry (was created or moved in) or left
+ * the namespace after pg_depend was read.  We look at pg_depend before
+ * pg_class, because a concurrent move changes both in one transaction.
+ */
+static void
+check_namespace_members(Oid catalogId, Oid namespaceId,
+						List *members, List *scanned)
+{
+	ListCell   *lc;
+
+	foreach(lc, scanned)
+	{
+		Oid			objectId = lfirst_oid(lc);
+
+		if (list_member_oid(members, objectId))
+			continue;
+		if (object_depends_on_namespace(catalogId, objectId, namespaceId))
+			continue;
+		if (object_namespace(catalogId, objectId) != namespaceId)
+			continue;
+
+		elog(ERROR, "object %u of catalog %u in namespace %u has no pg_depend entry on its namespace",
+			 objectId, catalogId, namespaceId);
+	}
+}
+#endif							/* USE_ASSERT_CHECKING */
+
+/*
+ * GetNamespaceRelations
+ *		Return the OIDs of the relations in a namespace whose relkind is one
+ *		of the characters in "relkinds".
+ *
+ * pg_class has no index on relnamespace, so a plain search costs a scan of
+ * the whole catalog no matter how small the namespace is.  But every table,
+ * view, materialized view, sequence, foreign table and partitioned table
+ * records a pg_depend entry on its namespace (see heap_create_with_catalog),
+ * and pg_depend is indexed by referenced object, so we can find the members
+ * of a namespace from there.  Two cases are not covered by pg_depend:
+ *
+ * - No dependencies are recorded on a pinned namespace (pg_catalog, pg_toast
+ *	 and so on), so for those we scan pg_class as before.
+ *
+ * - Indexes, composite types and TOAST tables have no namespace dependency
+ *	 of their own.  Callers must not ask for those relkinds.
+ *
+ * When system indexes are ignored, scan pg_class directly rather than
+ * scanning pg_depend without its reference index.
+ *
+ * A pg_depend entry is only a candidate: a relation can also depend on some
+ * other namespace through an expression (a regnamespace constant in a
+ * partition key, say), so each one is rechecked against its pg_class row.
+ *
+ * Looking up each candidate costs far more than reading one row in a scan,
+ * so if the namespace turns out to hold a sizable part of pg_class we scan
+ * anyway (see namespace_scan_is_cheaper).
+ *
+ * The result is sorted by OID, whichever way it was found.  Callers such as
+ * GRANT update every member, and a catalog scan may start anywhere in the
+ * heap (synchronized scans), so without a fixed order two sessions working
+ * on the same namespace could take the row locks in different orders and
+ * deadlock.
+ */
+List *
+GetNamespaceRelations(Oid namespaceId, const char *relkinds)
+{
+	List	   *result = NIL;
+	List	   *candidates;
+	ListCell   *lc;
+
+	Assert(relkinds != NULL);
+	Assert(strchr(relkinds, RELKIND_INDEX) == NULL);
+	Assert(strchr(relkinds, RELKIND_PARTITIONED_INDEX) == NULL);
+	Assert(strchr(relkinds, RELKIND_COMPOSITE_TYPE) == NULL);
+	Assert(strchr(relkinds, RELKIND_TOASTVALUE) == NULL);
+
+	if (IgnoreSystemIndexes || IsPinnedObject(NamespaceRelationId, namespaceId))
+		return scan_namespace_relations(namespaceId, relkinds);
+
+	candidates = getDependentObjectsOfClass(RelationRelationId,
+											NamespaceRelationId,
+											namespaceId);
+	if (namespace_scan_is_cheaper(RelationRelationId, list_length(candidates)))
+	{
+		list_free(candidates);
+		return scan_namespace_relations(namespaceId, relkinds);
+	}
+
+	foreach(lc, candidates)
+	{
+		Oid			relid = lfirst_oid(lc);
+		HeapTuple	tuple;
+		Form_pg_class classForm;
+
+		tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
+		if (!HeapTupleIsValid(tuple))
+			continue;			/* concurrently dropped */
+		classForm = (Form_pg_class) GETSTRUCT(tuple);
+		if (classForm->relnamespace == namespaceId &&
+			strchr(relkinds, classForm->relkind) != NULL)
+			result = lappend_oid(result, relid);
+		ReleaseSysCache(tuple);
+	}
+	list_free(candidates);
+
+#ifdef USE_ASSERT_CHECKING
+	check_namespace_members(RelationRelationId, namespaceId, result,
+							scan_namespace_relations(namespaceId, relkinds));
+#endif
+
+	return result;
+}
+
+/*
+ * GetNamespaceFunctions
+ *		Return the OIDs of the functions (including aggregates and window
+ *		functions) and/or procedures in a namespace.
+ *
+ * Same method as GetNamespaceRelations: every pg_proc entry records a
+ * dependency on its namespace (see ProcedureCreate) unless the namespace is
+ * pinned.  Scan pg_proc directly if system indexes are ignored.
+ */
+List *
+GetNamespaceFunctions(Oid namespaceId, bool functions, bool procedures)
+{
+	List	   *result = NIL;
+	List	   *candidates;
+	ListCell   *lc;
+
+	if (IgnoreSystemIndexes || IsPinnedObject(NamespaceRelationId, namespaceId))
+		return scan_namespace_functions(namespaceId, functions, procedures);
+
+	candidates = getDependentObjectsOfClass(ProcedureRelationId,
+											NamespaceRelationId,
+											namespaceId);
+	if (namespace_scan_is_cheaper(ProcedureRelationId, list_length(candidates)))
+	{
+		list_free(candidates);
+		return scan_namespace_functions(namespaceId, functions, procedures);
+	}
+
+	foreach(lc, candidates)
+	{
+		Oid			procid = lfirst_oid(lc);
+		HeapTuple	tuple;
+		Form_pg_proc procForm;
+
+		tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(procid));
+		if (!HeapTupleIsValid(tuple))
+			continue;			/* concurrently dropped */
+		procForm = (Form_pg_proc) GETSTRUCT(tuple);
+		if (procForm->pronamespace == namespaceId &&
+			(procForm->prokind == PROKIND_PROCEDURE ? procedures : functions))
+			result = lappend_oid(result, procid);
+		ReleaseSysCache(tuple);
+	}
+	list_free(candidates);
+
+#ifdef USE_ASSERT_CHECKING
+	check_namespace_members(ProcedureRelationId, namespaceId, result,
+							scan_namespace_functions(namespaceId, functions,
+													 procedures));
+#endif
+
+	return result;
+}
+
 /*
  * isTempNamespace - is the given namespace my temporary-table namespace?
  */
diff --git a/src/backend/catalog/pg_depend.c b/src/backend/catalog/pg_depend.c
index 9a7a401acedb0ee0ffe11b048f49001df8bb97b4..8006383dbc70b3595bd21d0bbc503a62d3cc5060 100644
--- a/src/backend/catalog/pg_depend.c
+++ b/src/backend/catalog/pg_depend.c
@@ -1293,3 +1293,59 @@ get_index_ref_constraints(Oid indexId)
 
 	return result;
 }
+
+/*
+ * getDependentObjectsOfClass
+ *		Return the OIDs of the objects of catalog "classId" that have a
+ *		pg_depend entry (of any type) on the whole object
+ *		refClassId/refObjectId.
+ *
+ * This answers "what hangs from X" with one scan of the reference index.
+ * The list is sorted by OID and has no duplicates.  An entry here says only
+ * that some dependency exists; callers that want a specific relationship
+ * (members of a namespace, for example) must recheck each object.
+ */
+List *
+getDependentObjectsOfClass(Oid classId, Oid refClassId, Oid refObjectId)
+{
+	List	   *result = NIL;
+	Relation	depRel;
+	ScanKeyData key[3];
+	SysScanDesc scan;
+	HeapTuple	tup;
+
+	depRel = table_open(DependRelationId, AccessShareLock);
+
+	ScanKeyInit(&key[0],
+				Anum_pg_depend_refclassid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(refClassId));
+	ScanKeyInit(&key[1],
+				Anum_pg_depend_refobjid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(refObjectId));
+	ScanKeyInit(&key[2],
+				Anum_pg_depend_refobjsubid,
+				BTEqualStrategyNumber, F_INT4EQ,
+				Int32GetDatum(0));
+
+	scan = systable_beginscan(depRel, DependReferenceIndexId, true,
+							  NULL, 3, key);
+
+	while (HeapTupleIsValid(tup = systable_getnext(scan)))
+	{
+		Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
+
+		if (deprec->classid == classId && deprec->objsubid == 0)
+			result = lappend_oid(result, deprec->objid);
+	}
+
+	systable_endscan(scan);
+	table_close(depRel, AccessShareLock);
+
+	/* pg_depend may hold duplicate entries */
+	list_sort(result, list_oid_cmp);
+	list_deduplicate_oid(result);
+
+	return result;
+}
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 0f2e9c3dd74b96be6327f6878ba00b161c3a3205..80b2c7afd25006e88bd5aa0eccd819bfc1d4ff82 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -3313,13 +3313,13 @@ ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
 
 	Oid			objectOid;
 	Relation	relationRelation;
-	TableScanDesc scan;
-	ScanKeyData scan_keys[1];
+	TableScanDesc scan = NULL;
 	HeapTuple	tuple;
 	MemoryContext private_context;
 	MemoryContext old;
 	List	   *relids = NIL;
-	int			num_keys;
+	List	   *schemarels = NIL;
+	int			nextrel = 0;
 	bool		concurrent_warning = false;
 	bool		tablespace_warning = false;
 	const char *objectName = stmt->name;
@@ -3381,33 +3381,51 @@ ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
 											ALLOCSET_SMALL_SIZES);
 
 	/*
-	 * Define the search keys to find the objects to reindex. For a schema, we
-	 * select target relations using relnamespace, something not necessary for
-	 * a database-wide operation.
+	 * Build a list of the relations we need to reindex.  For a schema, we
+	 * get its tables and materialized views from GetNamespaceRelations();
+	 * for a database-wide operation, we scan pg_class.
+	 *
+	 * We only consider plain relations and materialized views here (toast
+	 * rels will be processed indirectly by reindex_relation).
 	 */
+	relationRelation = table_open(RelationRelationId, AccessShareLock);
 	if (objectKind == REINDEX_OBJECT_SCHEMA)
 	{
-		num_keys = 1;
-		ScanKeyInit(&scan_keys[0],
-					Anum_pg_class_relnamespace,
-					BTEqualStrategyNumber, F_OIDEQ,
-					ObjectIdGetDatum(objectOid));
+		static const char reindexkinds[] = {RELKIND_RELATION, RELKIND_MATVIEW, '\0'};
+
+		schemarels = GetNamespaceRelations(objectOid, reindexkinds);
 	}
 	else
-		num_keys = 0;
+		scan = table_beginscan_catalog(relationRelation, 0, NULL);
 
-	/*
-	 * Scan pg_class to build a list of the relations we need to reindex.
-	 *
-	 * We only consider plain relations and materialized views here (toast
-	 * rels will be processed indirectly by reindex_relation).
-	 */
-	relationRelation = table_open(RelationRelationId, AccessShareLock);
-	scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
-	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
+	for (;;)
 	{
-		Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
-		Oid			relid = classtuple->oid;
+		FormData_pg_class classform;
+		Form_pg_class classtuple;
+		Oid			relid;
+
+		if (objectKind == REINDEX_OBJECT_SCHEMA)
+		{
+			if (nextrel >= list_length(schemarels))
+				break;
+			tuple = SearchSysCache1(RELOID,
+									ObjectIdGetDatum(list_nth_oid(schemarels,
+																  nextrel++)));
+			if (!HeapTupleIsValid(tuple))
+				continue;
+			/* keep the fixed-size part only, so that we can just "continue" */
+			memcpy(&classform, GETSTRUCT(tuple), CLASS_TUPLE_SIZE);
+			ReleaseSysCache(tuple);
+			classtuple = &classform;
+		}
+		else
+		{
+			tuple = heap_getnext(scan, ForwardScanDirection);
+			if (tuple == NULL)
+				break;
+			classtuple = (Form_pg_class) GETSTRUCT(tuple);
+		}
+		relid = classtuple->oid;
 
 		/*
 		 * Only regular tables and matviews can have indexes, so ignore any
@@ -3511,7 +3529,8 @@ ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
 
 		MemoryContextSwitchTo(old);
 	}
-	table_endscan(scan);
+	if (scan != NULL)
+		table_endscan(scan);
 	table_close(relationRelation, AccessShareLock);
 
 	/*
diff --git a/src/include/catalog/dependency.h b/src/include/catalog/dependency.h
index 9782d0df2a7c8ba9f781030c9940d82add9302b6..d1284a78433a27f1bd2eec349437bea26496453b 100644
--- a/src/include/catalog/dependency.h
+++ b/src/include/catalog/dependency.h
@@ -200,6 +200,9 @@ extern Oid	getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
 
 extern Oid	get_index_constraint(Oid indexId);
 
+extern List *getDependentObjectsOfClass(Oid classId, Oid refClassId,
+										Oid refObjectId);
+
 extern List *get_index_ref_constraints(Oid indexId);
 
 /* in pg_shdepend.c */
diff --git a/src/include/catalog/namespace.h b/src/include/catalog/namespace.h
index 9453a3e49329742feed1f3e153beaf7284eb6dcf..39b2b2f5dc61537cfe242f9cac55b7bee2c1aac1 100644
--- a/src/include/catalog/namespace.h
+++ b/src/include/catalog/namespace.h
@@ -171,6 +171,10 @@ extern RangeVar *makeRangeVarFromNameList(const List *names);
 extern char *NameListToString(const List *names);
 extern char *NameListToQuotedString(const List *names);
 
+extern List *GetNamespaceRelations(Oid namespaceId, const char *relkinds);
+extern List *GetNamespaceFunctions(Oid namespaceId, bool functions,
+								   bool procedures);
+
 extern bool isTempNamespace(Oid namespaceId);
 extern bool isTempToastNamespace(Oid namespaceId);
 extern bool isTempOrTempToastNamespace(Oid namespaceId);
diff --git a/src/test/regress/expected/oidjoins.out b/src/test/regress/expected/oidjoins.out
index 51b9608a6680854bce7ae6e47fea380ad970a427..6e2ad2c0bb45ddba77e297e3599f57f5e299e268 100644
--- a/src/test/regress/expected/oidjoins.out
+++ b/src/test/regress/expected/oidjoins.out
@@ -273,3 +273,35 @@ NOTICE:  checking pg_subscription {subowner} => pg_authid {oid}
 NOTICE:  checking pg_subscription {subserver} => pg_foreign_server {oid}
 NOTICE:  checking pg_subscription_rel {srsubid} => pg_subscription {oid}
 NOTICE:  checking pg_subscription_rel {srrelid} => pg_class {oid}
+--
+-- Verify that relations and functions depend on their namespace
+--
+-- GetNamespaceRelations() and GetNamespaceFunctions() find the members of a
+-- namespace through pg_depend, so every relation of a kind they can return,
+-- and every function, must have a dependency on its namespace, unless the
+-- namespace is pinned (OID below FirstUnpinnedObjectId, except public).
+SELECT c.oid::regclass, c.relkind
+FROM pg_class c
+WHERE c.relkind IN ('r', 'v', 'm', 'S', 'f', 'p') AND
+      (c.relnamespace >= 12000 OR c.relnamespace = 'public'::regnamespace) AND
+      NOT EXISTS (SELECT 1 FROM pg_depend d
+                  WHERE d.classid = 'pg_class'::regclass AND
+                        d.objid = c.oid AND d.objsubid = 0 AND
+                        d.refclassid = 'pg_namespace'::regclass AND
+                        d.refobjid = c.relnamespace AND d.refobjsubid = 0);
+ oid | relkind 
+-----+---------
+(0 rows)
+
+SELECT p.oid::regprocedure, p.prokind
+FROM pg_proc p
+WHERE (p.pronamespace >= 12000 OR p.pronamespace = 'public'::regnamespace) AND
+      NOT EXISTS (SELECT 1 FROM pg_depend d
+                  WHERE d.classid = 'pg_proc'::regclass AND
+                        d.objid = p.oid AND d.objsubid = 0 AND
+                        d.refclassid = 'pg_namespace'::regclass AND
+                        d.refobjid = p.pronamespace AND d.refobjsubid = 0);
+ oid | prokind 
+-----+---------
+(0 rows)
+
diff --git a/src/test/regress/sql/oidjoins.sql b/src/test/regress/sql/oidjoins.sql
index 8b22e6d10c5eca68c208b2c9598fe2b689a508c1..651d7dee87a37c13400dc29e7b1132a91375a697 100644
--- a/src/test/regress/sql/oidjoins.sql
+++ b/src/test/regress/sql/oidjoins.sql
@@ -47,3 +47,30 @@ begin
   end loop;
 end
 $doblock$;
+
+--
+-- Verify that relations and functions depend on their namespace
+--
+-- GetNamespaceRelations() and GetNamespaceFunctions() find the members of a
+-- namespace through pg_depend, so every relation of a kind they can return,
+-- and every function, must have a dependency on its namespace, unless the
+-- namespace is pinned (OID below FirstUnpinnedObjectId, except public).
+
+SELECT c.oid::regclass, c.relkind
+FROM pg_class c
+WHERE c.relkind IN ('r', 'v', 'm', 'S', 'f', 'p') AND
+      (c.relnamespace >= 12000 OR c.relnamespace = 'public'::regnamespace) AND
+      NOT EXISTS (SELECT 1 FROM pg_depend d
+                  WHERE d.classid = 'pg_class'::regclass AND
+                        d.objid = c.oid AND d.objsubid = 0 AND
+                        d.refclassid = 'pg_namespace'::regclass AND
+                        d.refobjid = c.relnamespace AND d.refobjsubid = 0);
+
+SELECT p.oid::regprocedure, p.prokind
+FROM pg_proc p
+WHERE (p.pronamespace >= 12000 OR p.pronamespace = 'public'::regnamespace) AND
+      NOT EXISTS (SELECT 1 FROM pg_depend d
+                  WHERE d.classid = 'pg_proc'::regclass AND
+                        d.objid = p.oid AND d.objsubid = 0 AND
+                        d.refclassid = 'pg_namespace'::regclass AND
+                        d.refobjid = p.pronamespace AND d.refobjsubid = 0);
