Subject: Add a function to get the version of installed extension

From: Yugo Nagata <[email-masked]>
Date: Tue, 21 Jan 2025 12:29:37 +0900

Hi,
When an extension module is updated, first the new binary is installed, then
ALTER EXTENSION UPDATE is executed to create or modify SQL objects. Between
these two steps, users could see an error, or in worst case segfalut, during
a query execution due to the lack or incompatibility of SQL objects.

This might be avoidable if the binary is made carefully to check the existing
of objects, but I think it is useful if an extension module function can check
the current extension version. So, I would like to propose a new function to
return the current extension version, get_extension_version. I've attached a
patch.

Also, as an application of this function, how about allowing to include versions
in the "requires" list in the control file? It seems useful when an extension
requires other extension with a certain version. The proposed
get_extension_version can be used to check the versions of existing extensions.
This is just an idea and a patch is not created yet.

Regards,
Yugo Nagata

-- 
Yugo Nagata <[email-masked]>
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ba540e3de5..48c9109c31 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -215,6 +215,28 @@ get_extension_schema(Oid ext_oid)
 	return result;
 }
 
+/*
+ * get_extension_version - given an extension OID, look up the version
+ *
+ * Returns a palloc'd string, or NULL if no such extension.
+ */
+char *
+get_extension_version(Oid ext_oid)
+{
+	char	   *result;
+	HeapTuple	tuple;
+
+	tuple = SearchSysCache1(EXTENSIONOID, ObjectIdGetDatum(ext_oid));
+
+	if (!HeapTupleIsValid(tuple))
+		return NULL;
+
+	result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extversion));
+	ReleaseSysCache(tuple);
+
+	return result;
+}
+
 /*
  * Utility functions to check validity of extension and version names
  */
diff --git a/src/include/commands/extension.h b/src/include/commands/extension.h
index 0b63640512..43a55adea7 100644
--- a/src/include/commands/extension.h
+++ b/src/include/commands/extension.h
@@ -48,6 +48,7 @@ extern ObjectAddress ExecAlterExtensionContentsStmt(AlterExtensionContentsStmt *
 extern Oid	get_extension_oid(const char *extname, bool missing_ok);
 extern char *get_extension_name(Oid ext_oid);
 extern Oid	get_extension_schema(Oid ext_oid);
+extern char *get_extension_version(Oid ext_oid);
 extern bool extension_file_exists(const char *extensionName);
 
 extern ObjectAddress AlterExtensionNamespace(const char *extensionName, const char *newschema,