From 1f720adc8dc6b527165af376abf54bbb8c8397aa 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 v1] 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.  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 down from the type, rather than knowing how each kind
of type is built.  The types already looked at are remembered, so that a
composite type used by several columns of another one is looked at once
rather than once per path.

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>
Discussion: https://postgr.es/m/1010769.1764018910@sss.pgh.pa.us
Discussion: https://postgr.es/m/CA+UBoq0bJZOU2_v65fdAqT2K6pmLbnaUvYSL8f00Ntbnfj+L+w@mail.gmail.com
---
 doc/src/sgml/ref/create_table.sgml |   4 +
 doc/src/sgml/ref/create_type.sgml  |   3 +
 src/backend/catalog/heap.c         | 169 +++++++++++++++++++++++++++++
 src/backend/commands/tablecmds.c   |  26 +++++
 src/include/catalog/heap.h         |   4 +
 src/test/regress/expected/temp.out | 155 ++++++++++++++++++++++++++
 src/test/regress/sql/temp.sql      |  82 ++++++++++++++
 7 files changed, 443 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..eff3f690014 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,146 @@ CheckAttributeType(const char *attname,
 	}
 }
 
+/*
+ * object_is_temp
+ *		Is the object in a temporary schema?
+ *
+ * Objects made by initdb are never temporary, so skip looking them up.
+ */
+static bool
+object_is_temp(const ObjectAddress *object)
+{
+	Oid			objnamespace;
+
+	if (object->objectId < FirstNormalObjectId)
+		return false;
+	objnamespace = get_object_namespace(object);
+	return OidIsValid(objnamespace) && isAnyTempNamespace(objnamespace);
+}
+
+/*
+ * type_uses_temp_object
+ *		Does a column of type typid depend on a temporary object?
+ *
+ * The type itself may be temporary, or be built from a temporary object: the
+ * base type or collation of a domain, the element type of an array, the
+ * subtype, collation or support functions of a range, a column of a
+ * composite type, and so on.  pg_depend records all of that, so follow it
+ * instead of knowing about each kind of type.  Return true and set *tempobj
+ * to the first temporary object found.
+ *
+ * *checked lists the types already looked at.  Without it, a composite type
+ * that uses another one in several columns would be walked once per path.
+ */
+static bool
+type_uses_temp_object(Oid typid, ObjectAddress *tempobj, List **checked)
+{
+	ObjectAddress typaddr;
+	Oid			typrelid;
+	Relation	depRel;
+	ScanKeyData key[2];
+	SysScanDesc scan;
+	HeapTuple	tup;
+	bool		found = false;
+
+	if (typid < FirstNormalObjectId || list_member_oid(*checked, typid))
+		return false;
+	*checked = lappend_oid(*checked, typid);
+
+	/* since this function recurses, it could be driven to stack overflow */
+	check_stack_depth();
+
+	ObjectAddressSet(typaddr, TypeRelationId, typid);
+	if (object_is_temp(&typaddr))
+	{
+		*tempobj = typaddr;
+		return true;
+	}
+
+	/* the attributes of a composite type are the columns of its relation */
+	typrelid = get_typ_typrelid(typid);
+
+	depRel = table_open(DependRelationId, AccessShareLock);
+	ScanKeyInit(&key[0], Anum_pg_depend_classid, BTEqualStrategyNumber,
+				F_OIDEQ, ObjectIdGetDatum(OidIsValid(typrelid) ?
+										  RelationRelationId : TypeRelationId));
+	ScanKeyInit(&key[1], Anum_pg_depend_objid, BTEqualStrategyNumber,
+				F_OIDEQ, ObjectIdGetDatum(OidIsValid(typrelid) ? typrelid : typid));
+	scan = systable_beginscan(depRel, DependDependerIndexId, true,
+							  NULL, 2, key);
+	while (!found && HeapTupleIsValid(tup = systable_getnext(scan)))
+	{
+		Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(tup);
+		ObjectAddress ref;
+
+		ObjectAddressSubSet(ref, dep->refclassid, dep->refobjid,
+							dep->refobjsubid);
+		if (ref.classId == TypeRelationId)
+			found = type_uses_temp_object(ref.objectId, tempobj, checked);
+		else if (object_is_temp(&ref))
+		{
+			*tempobj = ref;
+			found = true;
+		}
+	}
+	systable_endscan(scan);
+	table_close(depRel, AccessShareLock);
+
+	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 passed to type_uses_temp_object(); callers checking several
+ * columns share it.
+ * --------------------------------
+ */
+void
+CheckAttributeTypeNotTemp(const char *relname, char relkind,
+						  const char *attname, Oid atttypid,
+						  Oid attcollation, List **checked)
+{
+	ObjectAddress tempobj;
+	bool		direct;
+	char	   *tempdesc;
+
+	ObjectAddressSet(tempobj, CollationRelationId, attcollation);
+	if (OidIsValid(attcollation) && object_is_temp(&tempobj))
+		direct = true;
+	else if (type_uses_temp_object(atttypid, &tempobj, checked))
+		direct = (tempobj.classId == TypeRelationId &&
+				  tempobj.objectId == atttypid);
+	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 +1579,32 @@ 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())
+	{
+		List	   *checked = NIL;
+
+		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);
+		list_free(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..c60476a6361 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -7994,6 +7994,15 @@ 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)
+	{
+		List	   *checked = NIL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  NameStr(attribute->attname), attribute->atttypid,
+								  attribute->attcollation, &checked);
+		list_free(checked);
+	}
 
 	/*
 	 * Set up information to set the new attribute's version, if needed (the
@@ -15542,6 +15551,14 @@ 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)
+	{
+		List	   *checked = NIL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  colName, targettype, targetcollid, &checked);
+		list_free(checked);
+	}
 
 	if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
 	{
@@ -19562,6 +19579,15 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	if (aclresult != ACLCHECK_OK)
 		aclcheck_error_type(aclresult, typeid);
 
+	if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
+	{
+		List	   *checked = NIL;
+
+		CheckAttributeTypeNotTemp(RelationGetRelationName(rel), rel->rd_rel->relkind,
+								  NULL, typeid, InvalidOid, &checked);
+		list_free(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..b9388e997e5 100644
--- a/src/include/catalog/heap.h
+++ b/src/include/catalog/heap.h
@@ -156,6 +156,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, List **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..1ea87e13058 100644
--- a/src/test/regress/expected/temp.out
+++ b/src/test/regress/expected/temp.out
@@ -236,6 +236,161 @@ 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
+-- 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..03bf0f7d223 100644
--- a/src/test/regress/sql/temp.sql
+++ b/src/test/regress/sql/temp.sql
@@ -182,6 +182,88 @@ 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
+-- 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;
-- 
2.56.1

