From 72cd6678b6a6c7b3cb5cba75a48459b32d53a6c9 Mon Sep 17 00:00:00 2001
From: John Naylor <jcnaylor@gmail.com>
Date: Mon, 12 Mar 2018 18:44:55 +0700
Subject: [PATCH] Generate pg_type OID symbols

If there is no oid_symbol entry already in the pg_type.dat, genbki.pl
will generate one when writing pg_type_d.h.
---
 src/backend/catalog/genbki.pl   | 28 ++++++++++++++++++++++++++++
 src/include/catalog/pg_type.dat |  9 +++++++++
 2 files changed, 37 insertions(+)

diff --git a/src/backend/catalog/genbki.pl b/src/backend/catalog/genbki.pl
index cff661e..aafeb7b 100644
--- a/src/backend/catalog/genbki.pl
+++ b/src/backend/catalog/genbki.pl
@@ -368,6 +368,12 @@ EOM
 					sprintf "{%s}", join(',', @argtypeoids);
 			}
 		}
+		elsif ($catname eq 'pg_type' and !exists $bki_values{oid_symbol})
+		{
+			my $symbol = form_pg_type_symbol($bki_values{typname});
+			$bki_values{oid_symbol} = $symbol
+			  if defined $symbol;
+		}
 
 		# Write to postgres.bki
 		print_bki_insert(\%bki_values, $schema);
@@ -699,6 +705,28 @@ sub morph_row_for_schemapg
 	}
 }
 
+# Determine canonical pg_type OID #define symbol from the type name.
+sub form_pg_type_symbol
+{
+	my $typename = shift;
+
+	# Skip for rowtypes of bootstrap tables, since they have their
+	# own naming convention defined elsewhere.
+	return
+	  if $typename eq 'pg_type'
+	    or $typename eq 'pg_proc'
+	    or $typename eq 'pg_attribute'
+	    or $typename eq 'pg_class';
+
+	# Transform like so:
+	#  foo_bar  ->  FOO_BAROID
+	# _foo_bar  ->  FOO_BARARRAYOID
+	$typename =~ /(_)?(.+)/;
+	my $arraystr = $1 ? 'ARRAY' : '';
+	my $name = uc $2;
+	return $name . $arraystr . 'OID';
+}
+
 sub usage
 {
 	die <<EOM;
diff --git a/src/include/catalog/pg_type.dat b/src/include/catalog/pg_type.dat
index 0a7de54..9264f79 100644
--- a/src/include/catalog/pg_type.dat
+++ b/src/include/catalog/pg_type.dat
@@ -18,6 +18,15 @@
 # For types used in the system catalogs, make sure the values here match
 # TypInfo[] in bootstrap.c.
 
+# The defined symbols for pg_type OIDs are generated by genbki.pl
+# according to the following rule, so you don't need to specify them
+# here:
+#  foo_bar  ->  FOO_BAROID
+# _foo_bar  ->  FOO_BARARRAYOID
+#
+# The only symbols in this file are ones that don't match this rule, and
+# are grandfathered in.
+
 # OIDS 1 - 99
 
 { oid => '16', descr => 'boolean, \'true\'/\'false\'',
-- 
2.7.4

