From 085043f4b9b3d7d491b572387a2d3979b904a8a8 Mon Sep 17 00:00:00 2001
From: Manuel Reyes Bravo <manuelreyesbravo@gmail.com>
Date: Sat, 28 Nov 2026 04:20:26 -0300
Subject: [PATCH v2] Reject temporary objects in columns of permanent relations

A permanent table, or a composite type that is not temporary, could have
a column that depends on a temporary object: a type created in pg_temp,
or the row type of a temporary table, directly or through a domain,
array, range, multirange or composite type, or a collation created in
pg_temp, used by the column itself or by its type.  The dependency can
also go through objects of other kinds, such as a function whose SQL
body reads a temporary table and that a domain calls in its default, or
the rule of a view that calls such a function.  At session exit the
temporary object is dropped with CASCADE, and that drops the column
along with its data, or, for a typed table, the whole table, without an
error or a notice.  When the permanent row type is itself stored in
other tables, the stored values lose that attribute, so values that were
distinct can become equal and break unique indexes.

Reject such columns up front, as is already done for materialized views
that use temporary objects (see 698fa924b11).  Making the relation
temporary instead, as for views, would make its data go away at session
exit, and would not help a row type that other tables already store.

To find out whether the type of a column depends on a temporary object,
follow pg_depend from the type to the objects it depends on, of any
kind, and to their internal parts, the way the drop at session exit
does, rather than knowing how each kind of object is built.  As there, a
column goes with its relation but a relation does not go with one of its
columns, except that a composite type in the values of the column counts
as changed when one of its attributes is dropped.  The objects already
looked at are remembered, so that each is looked at once, however many
paths lead to it.

This covers CREATE TABLE, including CREATE TABLE AS, SELECT INTO, OF and
PARTITION OF, ALTER TABLE ADD COLUMN, ALTER COLUMN TYPE and OF, CREATE
TYPE AS, and ALTER TYPE ADD ATTRIBUTE and ALTER ATTRIBUTE TYPE.
Temporary relations and types are not affected.  Neither is the
transient heap of a table rewrite, so a column of that kind that already
exists, which can only outlive its session after a crash, still works
with VACUUM FULL, CLUSTER and ALTER TABLE.

This rejects DDL that used to be accepted, so it is not backpatched.

Reported-by: Jim Jones <jim.jones@uni-muenster.de>
Reported-by: Manu <manuelreyesbravo@gmail.com>
Reviewed-by: Yilin Zhang <jiezhilove@126.com>
Discussion: https://postgr.es/m/1010769.1764018910@sss.pgh.pa.us
Discussion: https://postgr.es/m/CA+UBoq0bJZOU2_v65fdAqT2K6pmLbnaUvYSL8f00Ntbnfj+L+w@mail.gmail.com
Discussion: https://postgr.es/m/179592992325.510294.16785143669833910636@gmail.com
---
 doc/src/sgml/ref/create_table.sgml |   4 +
 doc/src/sgml/ref/create_type.sgml  |   3 +
 src/backend/catalog/heap.c         | 280 +++++++++++++++++++++++++++++
 src/backend/commands/tablecmds.c   |  29 +++
 src/include/catalog/heap.h         |   5 +
 src/test/regress/expected/temp.out | 223 +++++++++++++++++++++++
 src/test/regress/sql/temp.sql      | 131 ++++++++++++++
 src/tools/pgindent/typedefs.list   |   1 +
 8 files changed, 676 insertions(+)

diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml
index fef24d8f3a2..794d5a7705c 100644
--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -202,6 +202,10 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
       while the temporary table exists, unless they are referenced
       with schema-qualified names. Any indexes created on a temporary
       table are automatically temporary as well.
+      A table that is not temporary cannot have a column that depends on a
+      temporary object, such as a column of the row type of a temporary
+      table or one with a collation created in the temporary schema, nor be
+      a typed table of such a type.
      </para>
 
      <para>
diff --git a/doc/src/sgml/ref/create_type.sgml b/doc/src/sgml/ref/create_type.sgml
index 6aa01eb0daa..0bb94daa62b 100644
--- a/doc/src/sgml/ref/create_type.sgml
+++ b/doc/src/sgml/ref/create_type.sgml
@@ -110,6 +110,9 @@ CREATE TYPE <replaceable class="parameter">name</replaceable>
   <para>
    To be able to create a composite type, you must
    have <literal>USAGE</literal> privilege on all attribute types.
+   Unless the composite type is itself temporary, none of its attributes
+   can depend on a temporary object, such as the row type of a temporary
+   table.
   </para>
   </refsect2>
 
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 49ef6652203..a31796712a5 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -39,12 +39,15 @@
 #include "catalog/catalog.h"
 #include "catalog/heap.h"
 #include "catalog/index.h"
+#include "catalog/namespace.h"
 #include "catalog/objectaccess.h"
+#include "catalog/objectaddress.h"
 #include "catalog/partition.h"
 #include "catalog/pg_am.h"
 #include "catalog/pg_attrdef.h"
 #include "catalog/pg_collation.h"
 #include "catalog/pg_constraint.h"
+#include "catalog/pg_depend.h"
 #include "catalog/pg_foreign_table.h"
 #include "catalog/pg_inherits.h"
 #include "catalog/pg_namespace.h"
@@ -737,6 +740,256 @@ CheckAttributeType(const char *attname,
 	}
 }
 
+/*
+ * object_is_temp
+ *		Is the object in a temporary schema?
+ */
+static bool
+object_is_temp(const ObjectAddress *object)
+{
+	Oid			objnamespace;
+
+	if (!is_objectclass_supported(object->classId))
+		return false;
+	objnamespace = get_object_namespace(object);
+	return OidIsValid(objnamespace) && isAnyTempNamespace(objnamespace);
+}
+
+/* objectSubId for object_uses_temp_object: the relation and all its columns */
+#define TEMPDEP_ALL_COLUMNS (-1)
+
+/* entry of the set of objects already looked at by object_uses_temp_object */
+typedef struct TempDepCheckedKey
+{
+	Oid			classId;
+	Oid			objectId;
+	int32		objectSubId;
+	bool		values;
+} TempDepCheckedKey;
+
+/*
+ * object_uses_temp_object
+ *		Would the object go away, or change, along with the temporary objects?
+ *
+ * At session exit, the temporary schema is dropped with CASCADE.  That drops
+ * every object that depends on a temporary object, at any distance and
+ * whatever the kinds of the objects in between: a domain whose default calls
+ * a function whose SQL body reads a temporary table is dropped too.  It also
+ * drops the owner of an internal part that it drops (see
+ * findDependentObjects), such as the view of a rule that calls that
+ * function.  So follow pg_depend from the object to what it depends on and
+ * to its internal parts, and from each of those in the same way.  Return
+ * true and set *tempobj to the first temporary object found.
+ *
+ * As in findDependentObjects, a column (objectSubId > 0) goes with what it
+ * depends on and with its relation, but a relation does not go with one of
+ * its columns.  TEMPDEP_ALL_COLUMNS asks about a relation and all of its
+ * columns.
+ *
+ * values is true for the type of a column and for the types its values are
+ * made of (those it depends on, such as the base type of a domain or the
+ * element type of an array, and the attribute types of a composite type).
+ * Those values change, without the column being dropped, when a composite
+ * type among them loses an attribute, so for such a composite type look at
+ * all the columns of its relation, too.
+ *
+ * Objects made by initdb do not depend on temporary objects, so the walk
+ * stops there.  checked holds the objects already looked at, so that each
+ * is looked at once, however many paths lead to it.
+ */
+static bool
+object_uses_temp_object(const ObjectAddress *object, bool values,
+						ObjectAddress *tempobj, HTAB *checked)
+{
+	int32		subid = object->objectSubId;
+	TempDepCheckedKey key;
+	bool		seen;
+	bool		found = false;
+	Relation	depRel;
+	ScanKeyData skey[2];
+	SysScanDesc scan;
+	HeapTuple	tup;
+	Oid			typrelid = InvalidOid;
+
+	if (object->objectId < FirstNormalObjectId)
+		return false;
+
+	/* a column goes with its relation */
+	if (subid != 0)
+	{
+		ObjectAddress whole;
+
+		ObjectAddressSet(whole, object->classId, object->objectId);
+		if (object_uses_temp_object(&whole, false, tempobj, checked))
+			return true;
+	}
+
+	memset(&key, 0, sizeof(key));	/* the padding is hashed too */
+	key.classId = object->classId;
+	key.objectId = object->objectId;
+	key.objectSubId = subid;
+	/* looking at an object for its values covers looking at it otherwise */
+	key.values = true;
+	if (!values && hash_search(checked, &key, HASH_FIND, NULL) != NULL)
+		return false;
+	key.values = values;
+	(void) hash_search(checked, &key, HASH_ENTER, &seen);
+	if (seen)
+		return false;
+
+	/* since this function recurses, it could be driven to stack overflow */
+	check_stack_depth();
+
+	if (subid == 0)
+	{
+		if (object_is_temp(object))
+		{
+			ObjectAddressSet(*tempobj, object->classId, object->objectId);
+			return true;
+		}
+		if (values && object->classId == TypeRelationId)
+			typrelid = get_typ_typrelid(object->objectId);
+	}
+
+	depRel = table_open(DependRelationId, AccessShareLock);
+
+	/* the objects it depends on */
+	ScanKeyInit(&skey[0], Anum_pg_depend_classid, BTEqualStrategyNumber,
+				F_OIDEQ, ObjectIdGetDatum(object->classId));
+	ScanKeyInit(&skey[1], Anum_pg_depend_objid, BTEqualStrategyNumber,
+				F_OIDEQ, ObjectIdGetDatum(object->objectId));
+	scan = systable_beginscan(depRel, DependDependerIndexId, true,
+							  NULL, 2, skey);
+	while (!found && HeapTupleIsValid(tup = systable_getnext(scan)))
+	{
+		Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(tup);
+		ObjectAddress ref;
+
+		if (subid == TEMPDEP_ALL_COLUMNS ? dep->objsubid == 0 :
+			dep->objsubid != subid)
+			continue;
+		ObjectAddressSubSet(ref, dep->refclassid, dep->refobjid,
+							dep->refobjsubid);
+		found = object_uses_temp_object(&ref,
+										values && ref.classId == TypeRelationId,
+										tempobj, checked);
+	}
+	systable_endscan(scan);
+
+	/* its internal parts */
+	if (!found)
+	{
+		ScanKeyInit(&skey[0], Anum_pg_depend_refclassid, BTEqualStrategyNumber,
+					F_OIDEQ, ObjectIdGetDatum(object->classId));
+		ScanKeyInit(&skey[1], Anum_pg_depend_refobjid, BTEqualStrategyNumber,
+					F_OIDEQ, ObjectIdGetDatum(object->objectId));
+		scan = systable_beginscan(depRel, DependReferenceIndexId, true,
+								  NULL, 2, skey);
+		while (!found && HeapTupleIsValid(tup = systable_getnext(scan)))
+		{
+			Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(tup);
+			ObjectAddress part;
+
+			if (dep->deptype != DEPENDENCY_INTERNAL ||
+				(subid == TEMPDEP_ALL_COLUMNS ? dep->refobjsubid == 0 :
+				 dep->refobjsubid != subid))
+				continue;
+			ObjectAddressSubSet(part, dep->classid, dep->objid,
+								dep->objsubid);
+			found = object_uses_temp_object(&part, false, tempobj, checked);
+		}
+		systable_endscan(scan);
+	}
+
+	table_close(depRel, AccessShareLock);
+
+	/* the attributes of a composite type are the columns of its relation */
+	if (!found && OidIsValid(typrelid))
+	{
+		ObjectAddress columns;
+
+		ObjectAddressSubSet(columns, RelationRelationId, typrelid,
+							TEMPDEP_ALL_COLUMNS);
+		found = object_uses_temp_object(&columns, true, tempobj, checked);
+	}
+
+	return found;
+}
+
+/* --------------------------------
+ *		CheckAttributeTypeNotTemp
+ *
+ *		Complain if a column of a permanent relation would depend on a
+ *		temporary object, through its type or its collation.
+ *
+ * A temporary object is dropped at the end of the session, with everything
+ * that depends on it.  For a column of a permanent relation, that drops the
+ * column and its data; for a composite type stored in other tables, it
+ * changes the stored values of that type.  So reject it up front, as for
+ * materialized views.
+ *
+ * attname is NULL when checking the type of a typed table (OF type).
+ * *checked is the set of objects already looked at; it is created here if
+ * NULL, and callers checking several columns share it.  The caller frees it
+ * with hash_destroy() if it is not NULL.
+ * --------------------------------
+ */
+void
+CheckAttributeTypeNotTemp(const char *relname, char relkind,
+						  const char *attname, Oid atttypid,
+						  Oid attcollation, HTAB **checked)
+{
+	ObjectAddress typaddr;
+	ObjectAddress colladdr;
+	ObjectAddress tempobj;
+	bool		direct;
+	char	   *tempdesc;
+
+	/* nothing to look at for types and collations made by initdb */
+	if (atttypid < FirstNormalObjectId &&
+		(!OidIsValid(attcollation) || attcollation < FirstNormalObjectId))
+		return;
+
+	if (*checked == NULL)
+	{
+		HASHCTL		ctl;
+
+		ctl.keysize = sizeof(TempDepCheckedKey);
+		ctl.entrysize = sizeof(TempDepCheckedKey);
+		ctl.hcxt = CurrentMemoryContext;
+		*checked = hash_create("objects checked for temporary dependencies",
+							   64, &ctl,
+							   HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
+	}
+
+	ObjectAddressSet(typaddr, TypeRelationId, atttypid);
+	ObjectAddressSet(colladdr, CollationRelationId, attcollation);
+	if (OidIsValid(attcollation) &&
+		object_uses_temp_object(&colladdr, false, &tempobj, *checked))
+		direct = true;
+	else if (object_uses_temp_object(&typaddr, true, &tempobj, *checked))
+		direct = (tempobj.classId == typaddr.classId &&
+				  tempobj.objectId == typaddr.objectId);
+	else
+		return;
+
+	tempdesc = getObjectDescription(&tempobj, false);
+	ereport(ERROR,
+			(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			 attname == NULL ?
+			 errmsg("permanent relation \"%s\" must not use temporary objects",
+					relname) :
+			 relkind == RELKIND_COMPOSITE_TYPE ?
+			 errmsg("attribute \"%s\" of permanent type \"%s\" must not use temporary objects",
+					attname, relname) :
+			 errmsg("column \"%s\" of permanent relation \"%s\" must not use temporary objects",
+					attname, relname),
+			 direct ?
+			 errdetail("It depends on temporary %s.", tempdesc) :
+			 errdetail("Its type %s depends on temporary %s.",
+					   format_type_be(atttypid), tempdesc)));
+}
+
 /*
  * InsertPgAttributeTuples
  *		Construct and insert a set of tuples in pg_attribute.
@@ -1436,6 +1689,33 @@ heap_create_with_catalog(const char *relname,
 	CheckAttributeNamesTypes(tupdesc, relkind,
 							 allow_system_table_mods ? CHKATYPE_ANYARRAY : 0);
 
+	/*
+	 * A permanent relation must not depend on temporary objects.  Skip the
+	 * transient heap of a rewrite, which copies an existing relation, and
+	 * bootstrap mode, where there are no temporary objects and no syscache to
+	 * look.
+	 */
+	if (relpersistence != RELPERSISTENCE_TEMP && !OidIsValid(relrewrite) &&
+		!IsBootstrapProcessingMode())
+	{
+		HTAB	   *checked = NULL;
+
+		for (int i = 0; i < tupdesc->natts; i++)
+		{
+			Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+			if (!attr->attisdropped)
+				CheckAttributeTypeNotTemp(relname, relkind,
+										  NameStr(attr->attname), attr->atttypid,
+										  attr->attcollation, &checked);
+		}
+		if (OidIsValid(reloftypeid))
+			CheckAttributeTypeNotTemp(relname, relkind, NULL, reloftypeid,
+									  InvalidOid, &checked);
+		if (checked)
+			hash_destroy(checked);
+	}
+
 	/*
 	 * This would fail later on anyway, if the relation already exists.  But
 	 * by catching it here we can emit a nicer error message.
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9e363a44c20..e9da56d51d8 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -7994,6 +7994,16 @@ ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
 					   list_make1_oid(rel->rd_rel->reltype),
 					   (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
+	if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
+	{
+		HTAB	   *checked = NULL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  NameStr(attribute->attname), attribute->atttypid,
+								  attribute->attcollation, &checked);
+		if (checked)
+			hash_destroy(checked);
+	}
 
 	/*
 	 * Set up information to set the new attribute's version, if needed (the
@@ -15542,6 +15552,15 @@ ATPrepAlterColumnType(List **wqueue,
 	CheckAttributeType(colName, targettype, targetcollid,
 					   list_make1_oid(rel->rd_rel->reltype),
 					   (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
+	if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
+	{
+		HTAB	   *checked = NULL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  colName, targettype, targetcollid, &checked);
+		if (checked)
+			hash_destroy(checked);
+	}
 
 	if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
 	{
@@ -19562,6 +19581,16 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	if (aclresult != ACLCHECK_OK)
 		aclcheck_error_type(aclresult, typeid);
 
+	if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
+	{
+		HTAB	   *checked = NULL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  NULL, typeid, InvalidOid, &checked);
+		if (checked)
+			hash_destroy(checked);
+	}
+
 	/* Fail if the table has any inheritance parents. */
 	inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
 	ScanKeyInit(&key,
diff --git a/src/include/catalog/heap.h b/src/include/catalog/heap.h
index 0b2aaa5aa35..89fa86d23db 100644
--- a/src/include/catalog/heap.h
+++ b/src/include/catalog/heap.h
@@ -17,6 +17,7 @@
 #include "catalog/indexing.h"
 #include "catalog/objectaddress.h"
 #include "parser/parse_node.h"
+#include "utils/hsearch.h"
 
 
 /* flag bits for CheckAttributeType/CheckAttributeNamesTypes */
@@ -156,6 +157,10 @@ extern const FormData_pg_attribute *SystemAttributeByName(const char *attname);
 extern void CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
 									 int flags);
 
+extern void CheckAttributeTypeNotTemp(const char *relname, char relkind,
+									  const char *attname, Oid atttypid,
+									  Oid attcollation, HTAB **checked);
+
 extern void CheckAttributeType(const char *attname,
 							   Oid atttypid, Oid attcollation,
 							   List *containing_rowtypes,
diff --git a/src/test/regress/expected/temp.out b/src/test/regress/expected/temp.out
index e6f14b5f5b8..4b9786e1a0b 100644
--- a/src/test/regress/expected/temp.out
+++ b/src/test/regress/expected/temp.out
@@ -236,6 +236,229 @@ ERROR:  value for domain nonempty violates check constraint "nonempty_check"
 select ''::nonempty;
 ERROR:  value for domain nonempty violates check constraint "nonempty_check"
 reset search_path;
+-- Columns of permanent relations and composite types cannot depend on
+-- temporary objects, through their type or their collation, since dropping
+-- those at session exit would silently drop the column and its data, or, for
+-- a stored composite type, change the stored values.
+create temp table temp_tab (x int);
+create domain pg_temp.temp_dom as int;
+create type pg_temp.temp_comp as (x int);
+create type pg_temp.temp_rng as range (subtype = int8);
+create table perm_tab (a int, b temp_tab);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_tab.
+create table perm_tab (a int, b temp_dom);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+create table perm_tab (a int, b temp_dom[]);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom[].
+create table perm_tab (a int, b temp_rng);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_rng.
+create table perm_tab (a int, b temp_rng_multirange);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_rng_multirange.
+create unlogged table perm_tab (a int, b temp_dom);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+create table perm_tab (a int, b temp_dom) partition by list (a);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+-- through permanent types built on temporary ones, at any depth
+create domain perm_dom as temp_dom;
+create domain perm_dom2 as perm_dom;
+create type perm_rng as range (subtype = temp_dom);
+NOTICE:  function "perm_rng" will be effectively temporary
+DETAIL:  It depends on temporary type temp_dom.
+NOTICE:  function "perm_rng" will be effectively temporary
+DETAIL:  It depends on temporary type temp_dom.
+create domain perm_dom_arr as temp_comp[];
+create table perm_tab (a int, b perm_dom2);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  Its type perm_dom2 depends on temporary type temp_dom.
+create table perm_tab (a int, b perm_rng);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  Its type perm_rng depends on temporary type temp_dom.
+create table perm_tab (a int, b perm_rng_multirange);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  Its type perm_rng_multirange depends on temporary type temp_dom.
+create table perm_tab (a int, b perm_rng[]);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  Its type perm_rng[] depends on temporary type temp_dom.
+create table perm_tab (a int, b perm_dom_arr);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  Its type perm_dom_arr depends on temporary type temp_comp[].
+-- typed tables, CREATE TABLE AS and SELECT INTO
+create table perm_tab of temp_comp;  -- fail
+ERROR:  permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_comp.
+create table perm_tab as select 1 as a, row(1)::temp_tab as b;  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_tab.
+select 1 as a, 2::temp_dom as b into perm_tab;  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+-- composite types
+create type perm_comp as (a int, b temp_tab);  -- fail
+ERROR:  attribute "b" of permanent type "perm_comp" must not use temporary objects
+DETAIL:  It depends on temporary type temp_tab.
+create type perm_comp as (a int, b int);
+alter type perm_comp add attribute c temp_dom;  -- fail
+ERROR:  attribute "c" of permanent type "perm_comp" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+alter type perm_comp alter attribute b type perm_dom2;  -- fail
+ERROR:  attribute "b" of permanent type "perm_comp" must not use temporary objects
+DETAIL:  Its type perm_dom2 depends on temporary type temp_dom.
+-- columns added or changed later
+create table perm_tab (a int, b int);
+alter table perm_tab add column c temp_dom;  -- fail
+ERROR:  column "c" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+alter table perm_tab alter column b type temp_dom;  -- fail
+ERROR:  column "b" of permanent relation "perm_tab" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+create table perm_tab2 (x int);
+alter table perm_tab2 of temp_comp;  -- fail
+ERROR:  permanent relation "perm_tab2" must not use temporary objects
+DETAIL:  It depends on temporary type temp_comp.
+create table perm_parted (a int) partition by list (a);
+create table perm_part1 partition of perm_parted for values in (1);
+alter table perm_parted add column b temp_dom;  -- fail
+ERROR:  column "b" of permanent relation "perm_parted" must not use temporary objects
+DETAIL:  It depends on temporary type temp_dom.
+-- collations, and objects a type depends on other than types
+create collation pg_temp.temp_coll (provider = libc, locale = 'C');
+create function pg_temp.temp_diff(int4, int4) returns float8
+  language sql immutable return $1 - $2;
+create domain perm_dom_coll as text collate pg_temp.temp_coll;
+create type perm_rng_coll as range (subtype = text, collation = pg_temp.temp_coll);
+create type perm_rng_diff as range (subtype = int4, subtype_diff = pg_temp.temp_diff);
+\set VERBOSITY terse
+create table perm_tab3 (a text collate pg_temp.temp_coll);  -- fail
+ERROR:  column "a" of permanent relation "perm_tab3" must not use temporary objects
+create table perm_tab3 (a perm_dom_coll);  -- fail
+ERROR:  column "a" of permanent relation "perm_tab3" must not use temporary objects
+create table perm_tab3 (a perm_rng_coll);  -- fail
+ERROR:  column "a" of permanent relation "perm_tab3" must not use temporary objects
+create table perm_tab3 (a perm_rng_diff);  -- fail
+ERROR:  column "a" of permanent relation "perm_tab3" must not use temporary objects
+create table perm_tab3 as select 'x'::text collate pg_temp.temp_coll as a;  -- fail
+ERROR:  column "a" of permanent relation "perm_tab3" must not use temporary objects
+create type perm_comp3 as (a text collate pg_temp.temp_coll);  -- fail
+ERROR:  attribute "a" of permanent type "perm_comp3" must not use temporary objects
+alter table perm_tab add column d text collate pg_temp.temp_coll;  -- fail
+ERROR:  column "d" of permanent relation "perm_tab" must not use temporary objects
+alter table perm_tab alter column a type text collate pg_temp.temp_coll;  -- fail
+ERROR:  column "a" of permanent relation "perm_tab" must not use temporary objects
+\set VERBOSITY default
+-- through objects of any kind that depend on a temporary object: a function
+-- whose SQL body reads a temporary table is dropped along with it, and so is
+-- everything that depends on the function
+create function perm_eff_f() returns int language sql
+  begin atomic select count(*)::int from temp_tab; end;
+NOTICE:  function "perm_eff_f" will be effectively temporary
+DETAIL:  It depends on temporary table temp_tab.
+create function perm_eff_imm() returns int language sql immutable
+  begin atomic select count(*)::int from temp_tab; end;
+NOTICE:  function "perm_eff_imm" will be effectively temporary
+DETAIL:  It depends on temporary table temp_tab.
+create function perm_eff_diff(int8, int8) returns float8 language sql immutable
+  begin atomic select ($1 - $2)::float8 + 0 * (select count(*) from temp_tab); end;
+NOTICE:  function "perm_eff_diff" will be effectively temporary
+DETAIL:  It depends on temporary table temp_tab.
+\set VERBOSITY terse
+create domain perm_dom_def as int default perm_eff_f();
+create type perm_rng_eff as range (subtype = int8, subtype_diff = perm_eff_diff);
+create view perm_view_eff as select perm_eff_f() as c;
+create table perm_gen (k int, g int generated always as (k + perm_eff_imm()) stored);
+create function perm_gen_k() returns int language sql
+  begin atomic select max(k) from perm_gen; end;
+create function perm_gen_g() returns int language sql
+  begin atomic select max(g) from perm_gen; end;
+create domain perm_dom_k as int default perm_gen_k();
+create domain perm_dom_g as int default perm_gen_g();
+create function perm_eff_chk(int) returns bool language sql immutable
+  begin atomic select $1 >= (select count(*)::int from temp_tab); end;
+NOTICE:  function "perm_eff_chk" will be effectively temporary
+create domain perm_dom_chk as int check (perm_eff_chk(value));
+\set VERBOSITY default
+create table perm_tab4 (a int, b perm_dom_def);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+DETAIL:  Its type perm_dom_def depends on temporary table temp_tab.
+create table perm_tab4 (a int, b perm_dom_def[]);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+DETAIL:  Its type perm_dom_def[] depends on temporary table temp_tab.
+create type perm_comp4 as (a int, b perm_dom_def);  -- fail
+ERROR:  attribute "b" of permanent type "perm_comp4" must not use temporary objects
+DETAIL:  Its type perm_dom_def depends on temporary table temp_tab.
+\set VERBOSITY terse
+create table perm_tab4 (a int, b perm_rng_eff);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+create table perm_tab4 (a int, b perm_rng_eff_multirange);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+-- the rule of the view calls the function, and the view goes with its rule
+create table perm_tab4 (a int, b perm_view_eff);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+-- a stored row of perm_gen would lose g
+create table perm_tab4 (a int, b perm_gen);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+create table perm_tab4 (a int, b perm_gen[]);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+-- perm_gen_g() goes with the column g
+create table perm_tab4 (a int, b perm_dom_g);  -- fail
+ERROR:  column "b" of permanent relation "perm_tab4" must not use temporary objects
+\set VERBOSITY default
+-- but perm_gen_k() does not use g, and stays; and the CHECK constraint of
+-- perm_dom_chk goes, but not the domain
+create table perm_tab4 (a int, b perm_dom_k, c perm_dom_chk);
+drop table perm_tab4;
+drop domain perm_dom_def, perm_dom_k, perm_dom_g, perm_dom_chk;
+drop type perm_rng_eff;
+drop view perm_view_eff;
+drop function perm_gen_k(), perm_gen_g();
+drop table perm_gen;
+drop function perm_eff_f(), perm_eff_imm(), perm_eff_diff(int8, int8),
+  perm_eff_chk(int);
+-- still allowed: temporary relations and types, views, functions
+create temp table temp_tab2 (a temp_dom, b temp_tab, c perm_dom2, d perm_rng);
+alter table temp_tab2 add column e temp_comp;
+create type pg_temp.temp_comp2 as (a temp_dom, b temp_tab);
+create view perm_view as select row(1)::temp_tab as r;  -- becomes temporary
+NOTICE:  view "perm_view" will be a temporary view
+DETAIL:  It depends on temporary type temp_tab.
+create function perm_func(temp_tab) returns int language sql as 'select 1';
+NOTICE:  function "perm_func" will be effectively temporary
+DETAIL:  It depends on temporary type temp_tab.
+-- materialized views keep their own error
+create materialized view perm_mv as select row(1)::temp_tab as r;  -- fail
+ERROR:  materialized views must not use temporary objects
+DETAIL:  This view depends on temporary type temp_tab.
+select relname, relpersistence from pg_class
+  where relname in ('perm_tab', 'perm_tab2', 'perm_parted', 'perm_part1',
+                    'perm_comp', 'perm_view', 'temp_tab2', 'temp_comp2')
+  order by relname;
+   relname   | relpersistence 
+-------------+----------------
+ perm_comp   | p
+ perm_part1  | p
+ perm_parted | p
+ perm_tab    | p
+ perm_tab2   | p
+ perm_view   | t
+ temp_comp2  | t
+ temp_tab2   | t
+(8 rows)
+
+drop table perm_tab, perm_tab2, perm_parted, temp_tab2;
+drop view perm_view;
+drop function perm_func(temp_tab);
+drop type temp_comp2, perm_comp, perm_dom_arr, perm_rng, perm_dom2, perm_dom,
+  perm_dom_coll, perm_rng_coll, perm_rng_diff;
+drop table temp_tab;
+drop type temp_comp, temp_rng, temp_dom;
+drop collation pg_temp.temp_coll;
+drop function pg_temp.temp_diff(int4, int4);
 -- For partitioned temp tables, ON COMMIT actions ignore storage-less
 -- partitioned tables.
 begin;
diff --git a/src/test/regress/sql/temp.sql b/src/test/regress/sql/temp.sql
index 84978621830..0632c0489d9 100644
--- a/src/test/regress/sql/temp.sql
+++ b/src/test/regress/sql/temp.sql
@@ -182,6 +182,137 @@ select ''::nonempty;
 
 reset search_path;
 
+-- Columns of permanent relations and composite types cannot depend on
+-- temporary objects, through their type or their collation, since dropping
+-- those at session exit would silently drop the column and its data, or, for
+-- a stored composite type, change the stored values.
+create temp table temp_tab (x int);
+create domain pg_temp.temp_dom as int;
+create type pg_temp.temp_comp as (x int);
+create type pg_temp.temp_rng as range (subtype = int8);
+create table perm_tab (a int, b temp_tab);  -- fail
+create table perm_tab (a int, b temp_dom);  -- fail
+create table perm_tab (a int, b temp_dom[]);  -- fail
+create table perm_tab (a int, b temp_rng);  -- fail
+create table perm_tab (a int, b temp_rng_multirange);  -- fail
+create unlogged table perm_tab (a int, b temp_dom);  -- fail
+create table perm_tab (a int, b temp_dom) partition by list (a);  -- fail
+-- through permanent types built on temporary ones, at any depth
+create domain perm_dom as temp_dom;
+create domain perm_dom2 as perm_dom;
+create type perm_rng as range (subtype = temp_dom);
+create domain perm_dom_arr as temp_comp[];
+create table perm_tab (a int, b perm_dom2);  -- fail
+create table perm_tab (a int, b perm_rng);  -- fail
+create table perm_tab (a int, b perm_rng_multirange);  -- fail
+create table perm_tab (a int, b perm_rng[]);  -- fail
+create table perm_tab (a int, b perm_dom_arr);  -- fail
+-- typed tables, CREATE TABLE AS and SELECT INTO
+create table perm_tab of temp_comp;  -- fail
+create table perm_tab as select 1 as a, row(1)::temp_tab as b;  -- fail
+select 1 as a, 2::temp_dom as b into perm_tab;  -- fail
+-- composite types
+create type perm_comp as (a int, b temp_tab);  -- fail
+create type perm_comp as (a int, b int);
+alter type perm_comp add attribute c temp_dom;  -- fail
+alter type perm_comp alter attribute b type perm_dom2;  -- fail
+-- columns added or changed later
+create table perm_tab (a int, b int);
+alter table perm_tab add column c temp_dom;  -- fail
+alter table perm_tab alter column b type temp_dom;  -- fail
+create table perm_tab2 (x int);
+alter table perm_tab2 of temp_comp;  -- fail
+create table perm_parted (a int) partition by list (a);
+create table perm_part1 partition of perm_parted for values in (1);
+alter table perm_parted add column b temp_dom;  -- fail
+-- collations, and objects a type depends on other than types
+create collation pg_temp.temp_coll (provider = libc, locale = 'C');
+create function pg_temp.temp_diff(int4, int4) returns float8
+  language sql immutable return $1 - $2;
+create domain perm_dom_coll as text collate pg_temp.temp_coll;
+create type perm_rng_coll as range (subtype = text, collation = pg_temp.temp_coll);
+create type perm_rng_diff as range (subtype = int4, subtype_diff = pg_temp.temp_diff);
+\set VERBOSITY terse
+create table perm_tab3 (a text collate pg_temp.temp_coll);  -- fail
+create table perm_tab3 (a perm_dom_coll);  -- fail
+create table perm_tab3 (a perm_rng_coll);  -- fail
+create table perm_tab3 (a perm_rng_diff);  -- fail
+create table perm_tab3 as select 'x'::text collate pg_temp.temp_coll as a;  -- fail
+create type perm_comp3 as (a text collate pg_temp.temp_coll);  -- fail
+alter table perm_tab add column d text collate pg_temp.temp_coll;  -- fail
+alter table perm_tab alter column a type text collate pg_temp.temp_coll;  -- fail
+\set VERBOSITY default
+-- through objects of any kind that depend on a temporary object: a function
+-- whose SQL body reads a temporary table is dropped along with it, and so is
+-- everything that depends on the function
+create function perm_eff_f() returns int language sql
+  begin atomic select count(*)::int from temp_tab; end;
+create function perm_eff_imm() returns int language sql immutable
+  begin atomic select count(*)::int from temp_tab; end;
+create function perm_eff_diff(int8, int8) returns float8 language sql immutable
+  begin atomic select ($1 - $2)::float8 + 0 * (select count(*) from temp_tab); end;
+\set VERBOSITY terse
+create domain perm_dom_def as int default perm_eff_f();
+create type perm_rng_eff as range (subtype = int8, subtype_diff = perm_eff_diff);
+create view perm_view_eff as select perm_eff_f() as c;
+create table perm_gen (k int, g int generated always as (k + perm_eff_imm()) stored);
+create function perm_gen_k() returns int language sql
+  begin atomic select max(k) from perm_gen; end;
+create function perm_gen_g() returns int language sql
+  begin atomic select max(g) from perm_gen; end;
+create domain perm_dom_k as int default perm_gen_k();
+create domain perm_dom_g as int default perm_gen_g();
+create function perm_eff_chk(int) returns bool language sql immutable
+  begin atomic select $1 >= (select count(*)::int from temp_tab); end;
+create domain perm_dom_chk as int check (perm_eff_chk(value));
+\set VERBOSITY default
+create table perm_tab4 (a int, b perm_dom_def);  -- fail
+create table perm_tab4 (a int, b perm_dom_def[]);  -- fail
+create type perm_comp4 as (a int, b perm_dom_def);  -- fail
+\set VERBOSITY terse
+create table perm_tab4 (a int, b perm_rng_eff);  -- fail
+create table perm_tab4 (a int, b perm_rng_eff_multirange);  -- fail
+-- the rule of the view calls the function, and the view goes with its rule
+create table perm_tab4 (a int, b perm_view_eff);  -- fail
+-- a stored row of perm_gen would lose g
+create table perm_tab4 (a int, b perm_gen);  -- fail
+create table perm_tab4 (a int, b perm_gen[]);  -- fail
+-- perm_gen_g() goes with the column g
+create table perm_tab4 (a int, b perm_dom_g);  -- fail
+\set VERBOSITY default
+-- but perm_gen_k() does not use g, and stays; and the CHECK constraint of
+-- perm_dom_chk goes, but not the domain
+create table perm_tab4 (a int, b perm_dom_k, c perm_dom_chk);
+drop table perm_tab4;
+drop domain perm_dom_def, perm_dom_k, perm_dom_g, perm_dom_chk;
+drop type perm_rng_eff;
+drop view perm_view_eff;
+drop function perm_gen_k(), perm_gen_g();
+drop table perm_gen;
+drop function perm_eff_f(), perm_eff_imm(), perm_eff_diff(int8, int8),
+  perm_eff_chk(int);
+-- still allowed: temporary relations and types, views, functions
+create temp table temp_tab2 (a temp_dom, b temp_tab, c perm_dom2, d perm_rng);
+alter table temp_tab2 add column e temp_comp;
+create type pg_temp.temp_comp2 as (a temp_dom, b temp_tab);
+create view perm_view as select row(1)::temp_tab as r;  -- becomes temporary
+create function perm_func(temp_tab) returns int language sql as 'select 1';
+-- materialized views keep their own error
+create materialized view perm_mv as select row(1)::temp_tab as r;  -- fail
+select relname, relpersistence from pg_class
+  where relname in ('perm_tab', 'perm_tab2', 'perm_parted', 'perm_part1',
+                    'perm_comp', 'perm_view', 'temp_tab2', 'temp_comp2')
+  order by relname;
+drop table perm_tab, perm_tab2, perm_parted, temp_tab2;
+drop view perm_view;
+drop function perm_func(temp_tab);
+drop type temp_comp2, perm_comp, perm_dom_arr, perm_rng, perm_dom2, perm_dom,
+  perm_dom_coll, perm_rng_coll, perm_rng_diff;
+drop table temp_tab;
+drop type temp_comp, temp_rng, temp_dom;
+drop collation pg_temp.temp_coll;
+drop function pg_temp.temp_diff(int4, int4);
+
 -- For partitioned temp tables, ON COMMIT actions ignore storage-less
 -- partitioned tables.
 begin;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..aa268d24ff8 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -3165,6 +3165,7 @@ Tcl_NotifierProcs
 Tcl_Obj
 Tcl_Size
 Tcl_Time
+TempDepCheckedKey
 TempNamespaceStatus
 TestCustomScanState
 TestDSMRegistryHashEntry
-- 
2.56.1

