From 9e14a21e5cd5dcd7680a2cbdcc761126c8a23f79 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Wed, 15 Apr 2026 13:32:12 +0800
Subject: [PATCH v2] ddlutils: error out when pg_get_database_ddl() sees a
 missing tablespace

pg_get_database_ddl_internal() calls get_tablespace_name() for a
database's dattablespace, and then passes the result to
pg_strcasecmp() without checking for NULL first.

Fix that by detecting the missing tablespace explicitly and raising an
ERROR with ERRCODE_UNDEFINED_OBJECT.

Author: Chao Li <lic@highgo.com>
Reviewed-by:
Discussion: https://postgr.es/m/573E45C1-31A4-4885-A00C-1A2171159A2A@gmail.com
---
 src/backend/utils/adt/ddlutils.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/src/backend/utils/adt/ddlutils.c b/src/backend/utils/adt/ddlutils.c
index d83cda3342e..b3f819271ad 100644
--- a/src/backend/utils/adt/ddlutils.c
+++ b/src/backend/utils/adt/ddlutils.c
@@ -986,6 +986,12 @@ pg_get_database_ddl_internal(Oid dbid, bool pretty,
 	{
 		char	   *spcname = get_tablespace_name(dbform->dattablespace);
 
+		if (spcname == NULL)
+			ereport(ERROR,
+					errcode(ERRCODE_UNDEFINED_OBJECT),
+					errmsg("tablespace with OID %u does not exist",
+						   dbform->dattablespace));
+
 		if (pg_strcasecmp(spcname, "pg_default") != 0)
 			append_ddl_option(&buf, pretty, 4, "TABLESPACE = %s",
 							  quote_identifier(spcname));
-- 
2.50.1 (Apple Git-155)

