From 54faaa30643da0ad55c11b9b0c10b8b08c709051 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Sat, 15 Nov 2025 17:24:49 +0000
Subject: [PATCH v1 2/8] Use OidIsValid() in various places

Let's use OidIsValid() instead of:

- direct comparisons with InvalidOid
- direct comparisons with literal 0
---
 contrib/pg_overexplain/pg_overexplain.c       |  2 +-
 contrib/pg_prewarm/autoprewarm.c              |  6 +--
 .../pg_stat_statements/pg_stat_statements.c   |  8 ++--
 contrib/postgres_fdw/deparse.c                | 32 +++++++--------
 src/backend/access/brin/brin.c                |  2 +-
 src/backend/access/brin/brin_bloom.c          |  2 +-
 src/backend/access/brin/brin_inclusion.c      |  4 +-
 src/backend/access/brin/brin_minmax.c         |  2 +-
 src/backend/access/brin/brin_minmax_multi.c   |  6 +--
 src/backend/access/common/toast_internals.c   |  2 +-
 src/backend/access/gin/gininsert.c            |  2 +-
 src/backend/access/gin/ginutil.c              |  4 +-
 src/backend/access/gist/gistutil.c            |  4 +-
 src/backend/access/hash/hashfunc.c            |  4 +-
 src/backend/access/hash/hashsearch.c          |  2 +-
 src/backend/access/heap/heapam.c              |  2 +-
 src/backend/access/heap/heapam_visibility.c   | 16 ++++----
 src/backend/access/index/indexam.c            |  2 +-
 src/backend/access/nbtree/nbtcompare.c        |  2 +-
 src/backend/access/nbtree/nbtpreprocesskeys.c | 18 ++++-----
 src/backend/access/nbtree/nbtsearch.c         |  2 +-
 src/backend/access/table/tableamapi.c         |  2 +-
 src/backend/bootstrap/bootstrap.c             |  2 +-
 src/backend/catalog/aclchk.c                  |  3 +-
 src/backend/catalog/catalog.c                 |  2 +-
 src/backend/catalog/heap.c                    | 12 +++---
 src/backend/catalog/index.c                   |  2 +-
 src/backend/catalog/namespace.c               |  4 +-
 src/backend/catalog/objectaddress.c           |  4 +-
 src/backend/catalog/partition.c               |  2 +-
 src/backend/catalog/pg_aggregate.c            |  2 +-
 src/backend/catalog/pg_inherits.c             |  4 +-
 src/backend/catalog/pg_operator.c             |  6 +--
 src/backend/catalog/pg_shdepend.c             |  2 +-
 src/backend/catalog/pg_tablespace.c           |  2 +-
 src/backend/catalog/toasting.c                |  2 +-
 src/backend/commands/aggregatecmds.c          |  2 +-
 src/backend/commands/cluster.c                |  2 +-
 src/backend/commands/copyto.c                 |  2 +-
 src/backend/commands/event_trigger.c          |  2 +-
 src/backend/commands/extension.c              |  2 +-
 src/backend/commands/functioncmds.c           |  4 +-
 src/backend/commands/indexcmds.c              | 12 +++---
 src/backend/commands/sequence.c               |  4 +-
 src/backend/commands/statscmds.c              |  6 +--
 src/backend/commands/tablecmds.c              | 22 +++++-----
 src/backend/commands/tablespace.c             |  8 ++--
 src/backend/commands/trigger.c                |  2 +-
 src/backend/commands/typecmds.c               | 18 ++++-----
 src/backend/commands/vacuum.c                 |  2 +-
 src/backend/commands/view.c                   |  2 +-
 src/backend/executor/execUtils.c              |  2 +-
 src/backend/executor/functions.c              |  2 +-
 src/backend/nodes/nodeFuncs.c                 |  8 ++--
 src/backend/optimizer/path/costsize.c         |  4 +-
 src/backend/optimizer/path/indxpath.c         |  6 +--
 src/backend/optimizer/path/joinpath.c         |  2 +-
 src/backend/optimizer/prep/prepqual.c         |  4 +-
 src/backend/optimizer/util/plancat.c          | 20 +++++-----
 src/backend/parser/parse_clause.c             |  2 +-
 src/backend/parser/parse_coerce.c             |  6 +--
 src/backend/parser/parse_expr.c               |  6 +--
 src/backend/parser/parse_oper.c               | 10 ++---
 src/backend/parser/parse_target.c             |  2 +-
 src/backend/parser/parse_type.c               |  2 +-
 src/backend/parser/parse_utilcmd.c            |  4 +-
 .../libpqwalreceiver/libpqwalreceiver.c       |  2 +-
 src/backend/replication/logical/decode.c      |  2 +-
 src/backend/replication/logical/logical.c     |  2 +-
 src/backend/replication/logical/relation.c    |  4 +-
 .../replication/logical/reorderbuffer.c       |  4 +-
 src/backend/replication/pgoutput/pgoutput.c   |  2 +-
 src/backend/replication/slot.c                |  4 +-
 src/backend/replication/slotfuncs.c           |  6 +--
 src/backend/replication/walsender.c           |  8 ++--
 src/backend/rewrite/rewriteHandler.c          |  2 +-
 src/backend/statistics/dependencies.c         |  2 +-
 src/backend/statistics/mcv.c                  |  2 +-
 src/backend/statistics/mvdistinct.c           |  2 +-
 src/backend/storage/buffer/bufmgr.c           |  2 +-
 src/backend/storage/file/fd.c                 |  4 +-
 src/backend/storage/ipc/procarray.c           |  4 +-
 src/backend/storage/lmgr/lock.c               |  2 +-
 src/backend/storage/lmgr/predicate.c          |  2 +-
 src/backend/tcop/postgres.c                   |  2 +-
 src/backend/tsearch/ts_parse.c                |  2 +-
 src/backend/utils/activity/pgstat.c           |  2 +-
 src/backend/utils/adt/array_selfuncs.c        |  2 +-
 src/backend/utils/adt/array_userfuncs.c       |  4 +-
 src/backend/utils/adt/enum.c                  |  8 ++--
 src/backend/utils/adt/format_type.c           |  4 +-
 src/backend/utils/adt/json.c                  | 10 ++---
 src/backend/utils/adt/jsonb.c                 | 10 ++---
 src/backend/utils/adt/like_support.c          |  2 +-
 src/backend/utils/adt/misc.c                  |  8 ++--
 .../utils/adt/multirangetypes_selfuncs.c      |  2 +-
 src/backend/utils/adt/network.c               |  4 +-
 src/backend/utils/adt/pgstatfuncs.c           |  4 +-
 src/backend/utils/adt/rangetypes_selfuncs.c   |  2 +-
 src/backend/utils/adt/regproc.c               | 20 +++++-----
 src/backend/utils/adt/ruleutils.c             |  4 +-
 src/backend/utils/adt/selfuncs.c              |  8 ++--
 src/backend/utils/adt/varchar.c               |  4 +-
 src/backend/utils/cache/inval.c               | 14 +++----
 src/backend/utils/cache/lsyscache.c           |  2 +-
 src/backend/utils/cache/plancache.c           |  6 +--
 src/backend/utils/cache/relfilenumbermap.c    |  4 +-
 src/backend/utils/cache/spccache.c            |  2 +-
 src/backend/utils/cache/ts_cache.c            |  2 +-
 src/backend/utils/cache/typcache.c            | 40 +++++++++----------
 src/backend/utils/fmgr/funcapi.c              |  2 +-
 src/backend/utils/misc/queryenvironment.c     |  2 +-
 src/bin/pg_dump/common.c                      |  2 +-
 src/bin/pg_dump/pg_backup_archiver.c          |  2 +-
 src/bin/pg_dump/pg_backup_custom.c            |  6 +--
 src/bin/pg_dump/pg_backup_null.c              |  2 +-
 src/bin/pg_dump/pg_backup_tar.c               |  4 +-
 src/bin/pg_dump/pg_dump.c                     | 24 +++++------
 src/bin/pg_resetwal/pg_resetwal.c             |  6 +--
 src/bin/psql/describe.c                       |  2 +-
 src/bin/psql/large_obj.c                      |  2 +-
 src/common/relpath.c                          |  4 +-
 src/interfaces/libpq/fe-lobj.c                | 30 +++++++-------
 src/pl/plperl/plperl.c                        | 12 +++---
 src/pl/plpgsql/src/pl_exec.c                  |  4 +-
 src/pl/plpython/plpy_procedure.c              |  2 +-
 src/pl/plpython/plpy_typeio.c                 |  8 +---
 src/test/examples/testlo.c                    |  4 +-
 src/test/examples/testlo64.c                  |  4 +-
 129 files changed, 346 insertions(+), 349 deletions(-)
   3.8% contrib/postgres_fdw/
   3.3% src/backend/access/brin/
   8.4% src/backend/access/
   7.5% src/backend/catalog/
  15.7% src/backend/commands/
   3.0% src/backend/optimizer/util/
   4.5% src/backend/parser/
   4.6% src/backend/replication/
   9.9% src/backend/utils/adt/
  11.3% src/backend/utils/cache/
   9.4% src/backend/
   4.3% src/bin/pg_dump/
   4.1% src/interfaces/libpq/
   4.7% src/pl/

diff --git a/contrib/pg_overexplain/pg_overexplain.c b/contrib/pg_overexplain/pg_overexplain.c
index bd70b6d9d5e..ebf8109ec84 100644
--- a/contrib/pg_overexplain/pg_overexplain.c
+++ b/contrib/pg_overexplain/pg_overexplain.c
@@ -479,7 +479,7 @@ overexplain_range_table(PlannedStmt *plannedstmt, ExplainState *es)
 		 * displayed only in verbose mode, and we emit nothing if there is no
 		 * relation OID.
 		 */
-		if (rte->relid != 0)
+		if (OidIsValid(rte->relid))
 		{
 			const char *relname;
 			const char *qualname;
diff --git a/contrib/pg_prewarm/autoprewarm.c b/contrib/pg_prewarm/autoprewarm.c
index 5ba1240d51f..837fe43f937 100644
--- a/contrib/pg_prewarm/autoprewarm.c
+++ b/contrib/pg_prewarm/autoprewarm.c
@@ -398,7 +398,7 @@ apw_load_buffers(void)
 				 * Combine BlockInfoRecords for global objects with those of
 				 * the database.
 				 */
-				if (current_db != InvalidOid)
+				if (OidIsValid(current_db))
 					break;
 				current_db = blkinfo[j].database;
 			}
@@ -411,7 +411,7 @@ apw_load_buffers(void)
 		 * BlockInfoRecords belonging to global objects exist.  We can't
 		 * prewarm without a database connection, so just bail out.
 		 */
-		if (current_db == InvalidOid)
+		if (!OidIsValid(current_db))
 			break;
 
 		/* Configure stop point and database for next per-database worker. */
@@ -536,7 +536,7 @@ autoprewarm_database_main(Datum main_arg)
 		 * All blocks between prewarm_start_idx and prewarm_stop_idx should
 		 * belong either to global objects or the same database.
 		 */
-		Assert(blk.database == apw_state->database || blk.database == 0);
+		Assert(blk.database == apw_state->database || !OidIsValid(blk.database));
 
 		StartTransactionCommand();
 
diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 39208f80b5b..83ac02f2f0e 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -2730,7 +2730,7 @@ entry_reset(Oid userid, Oid dbid, int64 queryid, bool minmax_only)
 
 	stats_reset = GetCurrentTimestamp();
 
-	if (userid != 0 && dbid != 0 && queryid != INT64CONST(0))
+	if (OidIsValid(userid) && OidIsValid(dbid) && queryid != INT64CONST(0))
 	{
 		/* If all the parameters are available, use the fast path. */
 		memset(&key, 0, sizeof(pgssHashKey));
@@ -2753,14 +2753,14 @@ entry_reset(Oid userid, Oid dbid, int64 queryid, bool minmax_only)
 
 		SINGLE_ENTRY_RESET(entry);
 	}
-	else if (userid != 0 || dbid != 0 || queryid != INT64CONST(0))
+	else if (OidIsValid(userid) || OidIsValid(dbid) || queryid != INT64CONST(0))
 	{
 		/* Reset entries corresponding to valid parameters. */
 		hash_seq_init(&hash_seq, pgss_hash);
 		while ((entry = hash_seq_search(&hash_seq)) != NULL)
 		{
-			if ((!userid || entry->key.userid == userid) &&
-				(!dbid || entry->key.dbid == dbid) &&
+			if ((!OidIsValid(userid) || entry->key.userid == userid) &&
+				(!OidIsValid(dbid) || entry->key.dbid == dbid) &&
 				(!queryid || entry->key.queryid == queryid))
 			{
 				SINGLE_ENTRY_RESET(entry);
diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c
index f2fb0051843..f2b8968c189 100644
--- a/contrib/postgres_fdw/deparse.c
+++ b/contrib/postgres_fdw/deparse.c
@@ -367,7 +367,7 @@ foreign_expr_walker(Node *node,
 				{
 					/* Var belongs to some other table */
 					collation = var->varcollid;
-					if (collation == InvalidOid ||
+					if (!OidIsValid(collation) ||
 						collation == DEFAULT_COLLATION_OID)
 					{
 						/*
@@ -472,7 +472,7 @@ foreign_expr_walker(Node *node,
 				 * non-collation-sensitive context.
 				 */
 				collation = c->constcollid;
-				if (collation == InvalidOid ||
+				if (!OidIsValid(collation) ||
 					collation == DEFAULT_COLLATION_OID)
 					state = FDW_COLLATE_NONE;
 				else
@@ -503,7 +503,7 @@ foreign_expr_walker(Node *node,
 				 * Collation rule is same as for Consts and non-foreign Vars.
 				 */
 				collation = p->paramcollid;
-				if (collation == InvalidOid ||
+				if (!OidIsValid(collation) ||
 					collation == DEFAULT_COLLATION_OID)
 					state = FDW_COLLATE_NONE;
 				else
@@ -543,7 +543,7 @@ foreign_expr_walker(Node *node,
 				 * function nodes.
 				 */
 				collation = sr->refcollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -577,7 +577,7 @@ foreign_expr_walker(Node *node,
 				 * If function's input collation is not derived from a foreign
 				 * Var, it can't be sent to remote.
 				 */
-				if (fe->inputcollid == InvalidOid)
+				if (!OidIsValid(fe->inputcollid))
 					 /* OK, inputs are all noncollatable */ ;
 				else if (inner_cxt.state != FDW_COLLATE_SAFE ||
 						 fe->inputcollid != inner_cxt.collation)
@@ -590,7 +590,7 @@ foreign_expr_walker(Node *node,
 				 * node might not care.)
 				 */
 				collation = fe->funccollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -625,7 +625,7 @@ foreign_expr_walker(Node *node,
 				 * If operator's input collation is not derived from a foreign
 				 * Var, it can't be sent to remote.
 				 */
-				if (oe->inputcollid == InvalidOid)
+				if (!OidIsValid(oe->inputcollid))
 					 /* OK, inputs are all noncollatable */ ;
 				else if (inner_cxt.state != FDW_COLLATE_SAFE ||
 						 oe->inputcollid != inner_cxt.collation)
@@ -633,7 +633,7 @@ foreign_expr_walker(Node *node,
 
 				/* Result-collation handling is same as for functions */
 				collation = oe->opcollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -665,7 +665,7 @@ foreign_expr_walker(Node *node,
 				 * If operator's input collation is not derived from a foreign
 				 * Var, it can't be sent to remote.
 				 */
-				if (oe->inputcollid == InvalidOid)
+				if (!OidIsValid(oe->inputcollid))
 					 /* OK, inputs are all noncollatable */ ;
 				else if (inner_cxt.state != FDW_COLLATE_SAFE ||
 						 oe->inputcollid != inner_cxt.collation)
@@ -692,7 +692,7 @@ foreign_expr_walker(Node *node,
 				 * an input foreign Var (same logic as for a real function).
 				 */
 				collation = r->resultcollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -720,7 +720,7 @@ foreign_expr_walker(Node *node,
 				 * function).
 				 */
 				collation = e->resultcollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -846,7 +846,7 @@ foreign_expr_walker(Node *node,
 				 * the THEN and ELSE subexpressions.
 				 */
 				collation = ce->casecollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -871,7 +871,7 @@ foreign_expr_walker(Node *node,
 				 * the CASE arg.
 				 */
 				collation = c->collation;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (case_arg_cxt->state == FDW_COLLATE_SAFE &&
 						 collation == case_arg_cxt->collation)
@@ -898,7 +898,7 @@ foreign_expr_walker(Node *node,
 				 * an input foreign Var (same logic as for a function).
 				 */
 				collation = a->array_collid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
@@ -1010,7 +1010,7 @@ foreign_expr_walker(Node *node,
 				 * If aggregate's input collation is not derived from a
 				 * foreign Var, it can't be sent to remote.
 				 */
-				if (agg->inputcollid == InvalidOid)
+				if (!OidIsValid(agg->inputcollid))
 					 /* OK, inputs are all noncollatable */ ;
 				else if (inner_cxt.state != FDW_COLLATE_SAFE ||
 						 agg->inputcollid != inner_cxt.collation)
@@ -1023,7 +1023,7 @@ foreign_expr_walker(Node *node,
 				 * node might not care.)
 				 */
 				collation = agg->aggcollid;
-				if (collation == InvalidOid)
+				if (!OidIsValid(collation))
 					state = FDW_COLLATE_NONE;
 				else if (inner_cxt.state == FDW_COLLATE_SAFE &&
 						 collation == inner_cxt.collation)
diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 2f7d1437919..8d6ad686fbc 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -692,7 +692,7 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 * general, so this should be negligible, and repeated repalloc calls
 		 * are not free either.
 		 */
-		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
+		if (!OidIsValid(consistentFn->fn_oid))
 		{
 			FmgrInfo   *tmp;
 
diff --git a/src/backend/access/brin/brin_bloom.c b/src/backend/access/brin/brin_bloom.c
index 64dbb7b8532..1c91adbf708 100644
--- a/src/backend/access/brin/brin_bloom.c
+++ b/src/backend/access/brin/brin_bloom.c
@@ -726,7 +726,7 @@ bloom_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum)
 	 */
 	opaque = (BloomOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
 
-	if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->extra_procinfos[basenum].fn_oid))
 	{
 		if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
 												procnum)))
diff --git a/src/backend/access/brin/brin_inclusion.c b/src/backend/access/brin/brin_inclusion.c
index b86ca5744a3..3a7317a843d 100644
--- a/src/backend/access/brin/brin_inclusion.c
+++ b/src/backend/access/brin/brin_inclusion.c
@@ -560,7 +560,7 @@ inclusion_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum,
 	if (opaque->extra_proc_missing[basenum])
 		return NULL;
 
-	if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->extra_procinfos[basenum].fn_oid))
 	{
 		if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
 												procnum)))
@@ -629,7 +629,7 @@ inclusion_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype,
 		opaque->cached_subtype = subtype;
 	}
 
-	if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->strategy_procinfos[strategynum - 1].fn_oid))
 	{
 		Form_pg_attribute attr;
 		HeapTuple	tuple;
diff --git a/src/backend/access/brin/brin_minmax.c b/src/backend/access/brin/brin_minmax.c
index 79c5a0aa185..3744007be23 100644
--- a/src/backend/access/brin/brin_minmax.c
+++ b/src/backend/access/brin/brin_minmax.c
@@ -282,7 +282,7 @@ minmax_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype,
 		opaque->cached_subtype = subtype;
 	}
 
-	if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->strategy_procinfos[strategynum - 1].fn_oid))
 	{
 		Form_pg_attribute attr;
 		HeapTuple	tuple;
diff --git a/src/backend/access/brin/brin_minmax_multi.c b/src/backend/access/brin/brin_minmax_multi.c
index f8a11444d66..e5207e1ee9f 100644
--- a/src/backend/access/brin/brin_minmax_multi.c
+++ b/src/backend/access/brin/brin_minmax_multi.c
@@ -303,7 +303,7 @@ AssertCheckRanges(Ranges *ranges, FmgrInfo *cmpFn, Oid colloid)
 	Assert(ranges->nsorted >= 0);
 	Assert(ranges->nvalues >= ranges->nsorted);
 	Assert(ranges->maxvalues >= 2 * ranges->nranges + ranges->nvalues);
-	Assert(ranges->typid != InvalidOid);
+	Assert(OidIsValid(ranges->typid));
 
 	/*
 	 * First the ranges - there are 2*nranges boundary values, and the values
@@ -2871,7 +2871,7 @@ minmax_multi_get_procinfo(BrinDesc *bdesc, uint16 attno, uint16 procnum)
 	 */
 	opaque = (MinmaxMultiOpaque *) bdesc->bd_info[attno - 1]->oi_opaque;
 
-	if (opaque->extra_procinfos[basenum].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->extra_procinfos[basenum].fn_oid))
 	{
 		if (RegProcedureIsValid(index_getprocid(bdesc->bd_index, attno,
 												procnum)))
@@ -2920,7 +2920,7 @@ minmax_multi_get_strategy_procinfo(BrinDesc *bdesc, uint16 attno, Oid subtype,
 		opaque->cached_subtype = subtype;
 	}
 
-	if (opaque->strategy_procinfos[strategynum - 1].fn_oid == InvalidOid)
+	if (!OidIsValid(opaque->strategy_procinfos[strategynum - 1].fn_oid))
 	{
 		Form_pg_attribute attr;
 		HeapTuple	tuple;
diff --git a/src/backend/access/common/toast_internals.c b/src/backend/access/common/toast_internals.c
index 81dbd67c725..69ee1267b34 100644
--- a/src/backend/access/common/toast_internals.c
+++ b/src/backend/access/common/toast_internals.c
@@ -260,7 +260,7 @@ toast_save_datum(Relation rel, Datum value,
 				}
 			}
 		}
-		if (toast_pointer.va_valueid == InvalidOid)
+		if (!OidIsValid(toast_pointer.va_valueid))
 		{
 			/*
 			 * new value; must choose an OID that doesn't conflict in either
diff --git a/src/backend/access/gin/gininsert.c b/src/backend/access/gin/gininsert.c
index c2b879b2bf6..512bd403680 100644
--- a/src/backend/access/gin/gininsert.c
+++ b/src/backend/access/gin/gininsert.c
@@ -1302,7 +1302,7 @@ GinBufferInit(Relation index)
 		 * up the index key type's default btree comparator.
 		 */
 		cmpFunc = index_getprocid(index, i + 1, GIN_COMPARE_PROC);
-		if (cmpFunc == InvalidOid)
+		if (!OidIsValid(cmpFunc))
 		{
 			TypeCacheEntry *typentry;
 
diff --git a/src/backend/access/gin/ginutil.c b/src/backend/access/gin/ginutil.c
index 49631200a5a..5abca6d750d 100644
--- a/src/backend/access/gin/ginutil.c
+++ b/src/backend/access/gin/ginutil.c
@@ -182,8 +182,8 @@ initGinState(GinState *state, Relation index)
 						   CurrentMemoryContext);
 		}
 
-		if (state->consistentFn[i].fn_oid == InvalidOid &&
-			state->triConsistentFn[i].fn_oid == InvalidOid)
+		if (!OidIsValid(state->consistentFn[i].fn_oid) &&
+			!OidIsValid(state->triConsistentFn[i].fn_oid))
 		{
 			elog(ERROR, "missing GIN support function (%d or %d) for attribute %d of index \"%s\"",
 				 GIN_CONSISTENT_PROC, GIN_TRICONSISTENT_PROC,
diff --git a/src/backend/access/gist/gistutil.c b/src/backend/access/gist/gistutil.c
index 75272827837..cfda8b0f2e4 100644
--- a/src/backend/access/gist/gistutil.c
+++ b/src/backend/access/gist/gistutil.c
@@ -677,14 +677,14 @@ gistFetchTuple(GISTSTATE *giststate, Relation r, IndexTuple tuple)
 
 		datum = index_getattr(tuple, i + 1, giststate->leafTupdesc, &isnull[i]);
 
-		if (giststate->fetchFn[i].fn_oid != InvalidOid)
+		if (OidIsValid(giststate->fetchFn[i].fn_oid))
 		{
 			if (!isnull[i])
 				fetchatt[i] = gistFetchAtt(giststate, i, datum, r);
 			else
 				fetchatt[i] = (Datum) 0;
 		}
-		else if (giststate->compressFn[i].fn_oid == InvalidOid)
+		else if (!OidIsValid(giststate->compressFn[i].fn_oid))
 		{
 			/*
 			 * If opclass does not provide compress method that could change
diff --git a/src/backend/access/hash/hashfunc.c b/src/backend/access/hash/hashfunc.c
index ec96348942e..211eca234ff 100644
--- a/src/backend/access/hash/hashfunc.c
+++ b/src/backend/access/hash/hashfunc.c
@@ -271,7 +271,7 @@ hashtext(PG_FUNCTION_ARGS)
 	pg_locale_t mylocale;
 	Datum		result;
 
-	if (!collid)
+	if (!OidIsValid(collid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INDETERMINATE_COLLATION),
 				 errmsg("could not determine which collation to use for string hashing"),
@@ -326,7 +326,7 @@ hashtextextended(PG_FUNCTION_ARGS)
 	pg_locale_t mylocale;
 	Datum		result;
 
-	if (!collid)
+	if (!OidIsValid(collid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INDETERMINATE_COLLATION),
 				 errmsg("could not determine which collation to use for string hashing"),
diff --git a/src/backend/access/hash/hashsearch.c b/src/backend/access/hash/hashsearch.c
index 92c15a65be2..4559978c725 100644
--- a/src/backend/access/hash/hashsearch.c
+++ b/src/backend/access/hash/hashsearch.c
@@ -338,7 +338,7 @@ _hash_first(IndexScanDesc scan, ScanDirection dir)
 	 * opclass input type; this is a hack to simplify life for ScanKeyInit().
 	 */
 	if (cur->sk_subtype == rel->rd_opcintype[0] ||
-		cur->sk_subtype == InvalidOid)
+		!OidIsValid(cur->sk_subtype))
 		hashkey = _hash_datum2hashkey(rel, cur->sk_argument);
 	else
 		hashkey = _hash_datum2hashkey_type(rel, cur->sk_argument,
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 4b0c49f4bb0..c9ebd0e4ced 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -9076,7 +9076,7 @@ log_heap_new_cid(Relation relation, HeapTuple tup)
 	HeapTupleHeader hdr = tup->t_data;
 
 	Assert(ItemPointerIsValid(&tup->t_self));
-	Assert(tup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(tup->t_tableOid));
 
 	xlrec.top_xid = GetTopTransactionId();
 	xlrec.target_locator = relation->rd_locator;
diff --git a/src/backend/access/heap/heapam_visibility.c b/src/backend/access/heap/heapam_visibility.c
index 05f6946fe60..9c8e20a4256 100644
--- a/src/backend/access/heap/heapam_visibility.c
+++ b/src/backend/access/heap/heapam_visibility.c
@@ -172,7 +172,7 @@ HeapTupleSatisfiesSelf(HeapTuple htup, Snapshot snapshot, Buffer buffer)
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	if (!HeapTupleHeaderXminCommitted(tuple))
 	{
@@ -365,7 +365,7 @@ HeapTupleSatisfiesToast(HeapTuple htup, Snapshot snapshot,
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	if (!HeapTupleHeaderXminCommitted(tuple))
 	{
@@ -461,7 +461,7 @@ HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid,
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	if (!HeapTupleHeaderXminCommitted(tuple))
 	{
@@ -746,7 +746,7 @@ HeapTupleSatisfiesDirty(HeapTuple htup, Snapshot snapshot,
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	snapshot->xmin = snapshot->xmax = InvalidTransactionId;
 	snapshot->speculativeToken = 0;
@@ -972,7 +972,7 @@ HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot,
 	Assert(snapshot->regd_count > 0 || snapshot->active_count > 0);
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	if (!HeapTupleHeaderXminCommitted(tuple))
 	{
@@ -1207,7 +1207,7 @@ HeapTupleSatisfiesVacuumHorizon(HeapTuple htup, Buffer buffer, TransactionId *de
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 	Assert(dead_after != NULL);
 
 	*dead_after = InvalidTransactionId;
@@ -1476,7 +1476,7 @@ HeapTupleIsSurelyDead(HeapTuple htup, GlobalVisState *vistest)
 	HeapTupleHeader tuple = htup->t_data;
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	/*
 	 * If the inserting transaction is marked invalid, then it aborted, and
@@ -1601,7 +1601,7 @@ HeapTupleSatisfiesHistoricMVCC(HeapTuple htup, Snapshot snapshot,
 	TransactionId xmax = HeapTupleHeaderGetRawXmax(tuple);
 
 	Assert(ItemPointerIsValid(&htup->t_self));
-	Assert(htup->t_tableOid != InvalidOid);
+	Assert(OidIsValid(htup->t_tableOid));
 
 	/* inserting transaction aborted */
 	if (HeapTupleHeaderXminInvalid(tuple))
diff --git a/src/backend/access/index/indexam.c b/src/backend/access/index/indexam.c
index 0492d92d23b..fb51cde5a6d 100644
--- a/src/backend/access/index/indexam.c
+++ b/src/backend/access/index/indexam.c
@@ -937,7 +937,7 @@ index_getprocinfo(Relation irel,
 	locinfo += procindex;
 
 	/* Initialize the lookup info if first time through */
-	if (locinfo->fn_oid == InvalidOid)
+	if (!OidIsValid(locinfo->fn_oid))
 	{
 		RegProcedure *loc = irel->rd_support;
 		RegProcedure procId;
diff --git a/src/backend/access/nbtree/nbtcompare.c b/src/backend/access/nbtree/nbtcompare.c
index 188c27b4925..0f852833708 100644
--- a/src/backend/access/nbtree/nbtcompare.c
+++ b/src/backend/access/nbtree/nbtcompare.c
@@ -458,7 +458,7 @@ oid_decrement(Relation rel, Datum existing, bool *underflow)
 {
 	Oid			oexisting = DatumGetObjectId(existing);
 
-	if (oexisting == InvalidOid)
+	if (!OidIsValid(oexisting))
 	{
 		/* return value is undefined */
 		*underflow = true;
diff --git a/src/backend/access/nbtree/nbtpreprocesskeys.c b/src/backend/access/nbtree/nbtpreprocesskeys.c
index a871bf62cab..d03d9e4ebc7 100644
--- a/src/backend/access/nbtree/nbtpreprocesskeys.c
+++ b/src/backend/access/nbtree/nbtpreprocesskeys.c
@@ -1013,13 +1013,13 @@ _bt_compare_scankey_args(IndexScanDesc scan, ScanKey op,
 	 * input type; this is a hack to simplify life for ScanKeyInit().
 	 */
 	lefttype = leftarg->sk_subtype;
-	if (lefttype == InvalidOid)
+	if (!OidIsValid(lefttype))
 		lefttype = opcintype;
 	righttype = rightarg->sk_subtype;
-	if (righttype == InvalidOid)
+	if (!OidIsValid(righttype))
 		righttype = opcintype;
 	optype = op->sk_subtype;
-	if (optype == InvalidOid)
+	if (!OidIsValid(optype))
 		optype = opcintype;
 
 	/*
@@ -1150,7 +1150,7 @@ _bt_saoparray_shrink(IndexScanDesc scan, ScanKey arraysk, ScanKey skey,
 	 * means the opclass input type; this is a hack to simplify life for
 	 * ScanKeyInit().
 	 */
-	if (skey->sk_subtype != opcintype && skey->sk_subtype != InvalidOid)
+	if (skey->sk_subtype != opcintype && OidIsValid(skey->sk_subtype))
 	{
 		RegProcedure cmp_proc;
 		Oid			arraysk_elemtype;
@@ -1163,7 +1163,7 @@ _bt_saoparray_shrink(IndexScanDesc scan, ScanKey arraysk, ScanKey skey,
 		 * as its tupdatum/lefthand argument (rhs arg is for array elements).
 		 */
 		arraysk_elemtype = arraysk->sk_subtype;
-		if (arraysk_elemtype == InvalidOid)
+		if (!OidIsValid(arraysk_elemtype))
 			arraysk_elemtype = rel->rd_opcintype[arraysk->sk_attno - 1];
 		cmp_proc = get_opfamily_proc(rel->rd_opfamily[arraysk->sk_attno - 1],
 									 skey->sk_subtype, arraysk_elemtype,
@@ -1421,7 +1421,7 @@ _bt_skiparray_strat_decrement(IndexScanDesc scan, ScanKey arraysk,
 	 * index attribute's input opclass type
 	 */
 	if (high_compare->sk_subtype != opcintype &&
-		high_compare->sk_subtype != InvalidOid)
+		OidIsValid(high_compare->sk_subtype))
 		return;
 
 	/* Decrement, handling underflow by marking the qual unsatisfiable */
@@ -1479,7 +1479,7 @@ _bt_skiparray_strat_increment(IndexScanDesc scan, ScanKey arraysk,
 	 * index attribute's input opclass type
 	 */
 	if (low_compare->sk_subtype != opcintype &&
-		low_compare->sk_subtype != InvalidOid)
+		OidIsValid(low_compare->sk_subtype))
 		return;
 
 	/* Increment, handling overflow by marking the qual unsatisfiable */
@@ -2053,7 +2053,7 @@ _bt_preprocess_array_keys(IndexScanDesc scan, int *new_numberOfKeys)
 		 * ScanKeyInit().
 		 */
 		elemtype = cur->sk_subtype;
-		if (elemtype == InvalidOid)
+		if (!OidIsValid(elemtype))
 			elemtype = rel->rd_opcintype[cur->sk_attno - 1];
 
 		/*
@@ -2266,7 +2266,7 @@ _bt_preprocess_array_keys_final(IndexScanDesc scan, int *keyDataMap)
 				continue;
 
 			elemtype = outkey->sk_subtype;
-			if (elemtype == InvalidOid)
+			if (!OidIsValid(elemtype))
 				elemtype = rel->rd_opcintype[outkey->sk_attno - 1];
 
 			_bt_setup_array_cmp(scan, outkey, elemtype,
diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c
index 0605356ec9f..e23657ba275 100644
--- a/src/backend/access/nbtree/nbtsearch.c
+++ b/src/backend/access/nbtree/nbtsearch.c
@@ -1401,7 +1401,7 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
 		 * opclass input type; this hack simplifies life for ScanKeyInit().
 		 */
 		if (bkey->sk_subtype == rel->rd_opcintype[i] ||
-			bkey->sk_subtype == InvalidOid)
+			!OidIsValid(bkey->sk_subtype))
 		{
 			FmgrInfo   *procinfo;
 
diff --git a/src/backend/access/table/tableamapi.c b/src/backend/access/table/tableamapi.c
index 476663b66aa..86aeea3f9ab 100644
--- a/src/backend/access/table/tableamapi.c
+++ b/src/backend/access/table/tableamapi.c
@@ -120,7 +120,7 @@ check_default_table_access_method(char **newval, void **extra, GucSource source)
 	 * cannot do the catalog access necessary to verify the method.  Must
 	 * accept the value on faith.
 	 */
-	if (IsTransactionState() && MyDatabaseId != InvalidOid)
+	if (IsTransactionState() && OidIsValid(MyDatabaseId))
 	{
 		if (!OidIsValid(get_table_am_oid(*newval, true)))
 		{
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..60b168e668c 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -566,7 +566,7 @@ DefineAttr(char *name, char *type, int attnum, int nullness)
 		attrtypes[attnum]->attcompression = InvalidCompressionMethod;
 		attrtypes[attnum]->attcollation = TypInfo[typeoid].collation;
 		/* if an array type, assume 1-dimensional attribute */
-		if (TypInfo[typeoid].elem != InvalidOid &&
+		if (OidIsValid(TypInfo[typeoid].elem) &&
 			attrtypes[attnum]->attlen < 0)
 			attrtypes[attnum]->attndims = 1;
 		else
diff --git a/src/backend/catalog/aclchk.c b/src/backend/catalog/aclchk.c
index cd139bd65a6..e3a0a544cc3 100644
--- a/src/backend/catalog/aclchk.c
+++ b/src/backend/catalog/aclchk.c
@@ -2972,7 +2972,8 @@ aclcheck_error_type(AclResult aclerr, Oid typeOid)
 {
 	Oid			element_type = get_element_type(typeOid);
 
-	aclcheck_error(aclerr, OBJECT_TYPE, format_type_be(element_type ? element_type : typeOid));
+	aclcheck_error(aclerr, OBJECT_TYPE,
+				   format_type_be(OidIsValid(element_type) ? element_type : typeOid));
 }
 
 
diff --git a/src/backend/catalog/catalog.c b/src/backend/catalog/catalog.c
index 59caae8f1bc..7a4697a4795 100644
--- a/src/backend/catalog/catalog.c
+++ b/src/backend/catalog/catalog.c
@@ -583,7 +583,7 @@ GetNewRelFileNumber(Oid reltablespace, Relation pg_class, char relpersistence)
 	}
 
 	/* This logic should match RelationInitPhysicalAddr */
-	rlocator.locator.spcOid = reltablespace ? reltablespace : MyDatabaseTableSpace;
+	rlocator.locator.spcOid = OidIsValid(reltablespace) ? reltablespace : MyDatabaseTableSpace;
 	rlocator.locator.dbOid =
 		(rlocator.locator.spcOid == GLOBALTABLESPACE_OID) ?
 		InvalidOid : MyDatabaseId;
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index fd6537567ea..cb16141597c 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -396,7 +396,7 @@ heap_create(const char *relname,
 	 * protected by the existence of a physical file; but for relations with
 	 * no files, add a pg_shdepend entry to account for that.
 	 */
-	if (!create_storage && reltablespace != InvalidOid)
+	if (!create_storage && OidIsValid(reltablespace))
 		recordDependencyOnTablespace(RelationRelationId, relid,
 									 reltablespace);
 
@@ -746,7 +746,7 @@ InsertPgAttributeTuples(Relation pg_attribute_rel,
 		memset(slot[slotCount]->tts_isnull, false,
 			   slot[slotCount]->tts_tupleDescriptor->natts * sizeof(bool));
 
-		if (new_rel_oid != InvalidOid)
+		if (OidIsValid(new_rel_oid))
 			slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_rel_oid);
 		else
 			slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(attrs->attrelid);
@@ -1024,7 +1024,7 @@ AddNewRelationTuple(Relation pg_class_desc,
 	new_rel_reltup->relispartition = false;
 
 	/* fill rd_att's type ID with something sane even if reltype is zero */
-	new_rel_desc->rd_att->tdtypeid = new_type_oid ? new_type_oid : RECORDOID;
+	new_rel_desc->rd_att->tdtypeid = OidIsValid(new_type_oid) ? new_type_oid : RECORDOID;
 	new_rel_desc->rd_att->tdtypmod = -1;
 
 	/* Now build and insert the tuple */
@@ -1173,7 +1173,7 @@ heap_create_with_catalog(const char *relname,
 	 * by catching it here we can emit a nicer error message.
 	 */
 	existing_relid = get_relname_relid(relname, relnamespace);
-	if (existing_relid != InvalidOid)
+	if (OidIsValid(existing_relid))
 		ereport(ERROR,
 				(errcode(ERRCODE_DUPLICATE_TABLE),
 				 errmsg("relation \"%s\" already exists", relname)));
@@ -1411,7 +1411,7 @@ heap_create_with_catalog(const char *relname,
 	else
 	{
 		/* Caller should not be expecting a type to be created. */
-		Assert(reltypeid == InvalidOid);
+		Assert(!OidIsValid(reltypeid));
 		Assert(typaddress == NULL);
 
 		new_type_oid = InvalidOid;
@@ -1477,7 +1477,7 @@ heap_create_with_catalog(const char *relname,
 		ObjectAddressSet(referenced, NamespaceRelationId, relnamespace);
 		add_exact_object_address(&referenced, addrs);
 
-		if (reloftypeid)
+		if (OidIsValid(reloftypeid))
 		{
 			ObjectAddressSet(referenced, TypeRelationId, reloftypeid);
 			add_exact_object_address(&referenced, addrs);
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 5d9db167e59..120d7ad641c 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -823,7 +823,7 @@ index_create(Relation heapRelation,
 		Oid			collation = collationIds[i];
 		Oid			opclass = opclassIds[i];
 
-		if (collation)
+		if (OidIsValid(collation))
 		{
 			if ((opclass == TEXT_BTREE_PATTERN_OPS_OID ||
 				 opclass == VARCHAR_BTREE_PATTERN_OPS_OID ||
diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index d23474da4fb..696d8f5f5ec 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -3891,8 +3891,8 @@ void
 SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
 {
 	/* Worker should not have created its own namespaces ... */
-	Assert(myTempNamespace == InvalidOid);
-	Assert(myTempToastNamespace == InvalidOid);
+	Assert(!OidIsValid(myTempNamespace));
+	Assert(!OidIsValid(myTempToastNamespace));
 	Assert(myTempNamespaceSubID == InvalidSubTransactionId);
 
 	/* Assign same namespace OIDs that leader has */
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..699ac03b676 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -1129,7 +1129,7 @@ get_object_address(ObjectType objtype, Node *object,
 				/* no default, to let compiler warn about missing case */
 		}
 
-		if (!address.classId)
+		if (!OidIsValid(address.classId))
 			elog(ERROR, "unrecognized object type: %d", (int) objtype);
 
 		/*
@@ -2038,7 +2038,7 @@ get_object_address_defacl(List *object, bool missing_ok)
 	if (schema)
 	{
 		schemaid = get_namespace_oid(schema, true);
-		if (schemaid == InvalidOid)
+		if (!OidIsValid(schemaid))
 			goto not_found;
 	}
 	else
diff --git a/src/backend/catalog/partition.c b/src/backend/catalog/partition.c
index 93d72157a46..995f9d8cf22 100644
--- a/src/backend/catalog/partition.c
+++ b/src/backend/catalog/partition.c
@@ -160,7 +160,7 @@ get_partition_ancestors_worker(Relation inhRel, Oid relid, List **ancestors)
 	 * when the partition is being detached.
 	 */
 	parentOid = get_partition_parent_worker(inhRel, relid, &detach_pending);
-	if (parentOid == InvalidOid || detach_pending)
+	if (!OidIsValid(parentOid) || detach_pending)
 		return;
 
 	*ancestors = lappend_oid(*ancestors, parentOid);
diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c
index a1cb5719a0c..8717659b874 100644
--- a/src/backend/catalog/pg_aggregate.c
+++ b/src/backend/catalog/pg_aggregate.c
@@ -213,7 +213,7 @@ AggregateCreate(const char *aggName,
 		else
 		{
 			/* special case with VARIADIC last arg */
-			Assert(variadicArgType != InvalidOid);
+			Assert(OidIsValid(variadicArgType));
 			nargs_transfn = 2;
 		}
 		fnArgs[0] = aggTransType;
diff --git a/src/backend/catalog/pg_inherits.c b/src/backend/catalog/pg_inherits.c
index 929bb53b620..c46ad6f61ed 100644
--- a/src/backend/catalog/pg_inherits.c
+++ b/src/backend/catalog/pg_inherits.c
@@ -415,10 +415,10 @@ typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
 
 	/* We need to work with the associated relation OIDs */
 	subclassRelid = typeOrDomainTypeRelid(subclassTypeId);
-	if (subclassRelid == InvalidOid)
+	if (!OidIsValid(subclassRelid))
 		return false;			/* not a complex type or domain over one */
 	superclassRelid = typeidTypeRelid(superclassTypeId);
-	if (superclassRelid == InvalidOid)
+	if (!OidIsValid(superclassRelid))
 		return false;			/* not a complex type */
 
 	/* No point in searching if the superclass has no subclasses */
diff --git a/src/backend/catalog/pg_operator.c b/src/backend/catalog/pg_operator.c
index 44d2ccb6788..2263a428afc 100644
--- a/src/backend/catalog/pg_operator.c
+++ b/src/backend/catalog/pg_operator.c
@@ -239,7 +239,7 @@ OperatorShellMake(const char *operatorName,
 	values[Anum_pg_operator_oprname - 1] = NameGetDatum(&oname);
 	values[Anum_pg_operator_oprnamespace - 1] = ObjectIdGetDatum(operatorNamespace);
 	values[Anum_pg_operator_oprowner - 1] = ObjectIdGetDatum(GetUserId());
-	values[Anum_pg_operator_oprkind - 1] = CharGetDatum(leftTypeId ? 'b' : 'l');
+	values[Anum_pg_operator_oprkind - 1] = CharGetDatum(OidIsValid(leftTypeId) ? 'b' : 'l');
 	values[Anum_pg_operator_oprcanmerge - 1] = BoolGetDatum(false);
 	values[Anum_pg_operator_oprcanhash - 1] = BoolGetDatum(false);
 	values[Anum_pg_operator_oprleft - 1] = ObjectIdGetDatum(leftTypeId);
@@ -462,7 +462,7 @@ OperatorCreate(const char *operatorName,
 	values[Anum_pg_operator_oprname - 1] = NameGetDatum(&oname);
 	values[Anum_pg_operator_oprnamespace - 1] = ObjectIdGetDatum(operatorNamespace);
 	values[Anum_pg_operator_oprowner - 1] = ObjectIdGetDatum(GetUserId());
-	values[Anum_pg_operator_oprkind - 1] = CharGetDatum(leftTypeId ? 'b' : 'l');
+	values[Anum_pg_operator_oprkind - 1] = CharGetDatum(OidIsValid(leftTypeId) ? 'b' : 'l');
 	values[Anum_pg_operator_oprcanmerge - 1] = BoolGetDatum(canMerge);
 	values[Anum_pg_operator_oprcanhash - 1] = BoolGetDatum(canHash);
 	values[Anum_pg_operator_oprleft - 1] = ObjectIdGetDatum(leftTypeId);
@@ -479,7 +479,7 @@ OperatorCreate(const char *operatorName,
 	/*
 	 * If we are replacing an operator shell, update; else insert
 	 */
-	if (operatorObjectId)
+	if (OidIsValid(operatorObjectId))
 	{
 		isUpdate = true;
 
diff --git a/src/backend/catalog/pg_shdepend.c b/src/backend/catalog/pg_shdepend.c
index 16e3e5c7457..2f0f1ace7a3 100644
--- a/src/backend/catalog/pg_shdepend.c
+++ b/src/backend/catalog/pg_shdepend.c
@@ -395,7 +395,7 @@ changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
 	sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
 
 	if (newTablespaceId != DEFAULTTABLESPACE_OID &&
-		newTablespaceId != InvalidOid)
+		OidIsValid(newTablespaceId))
 		shdepChangeDep(sdepRel,
 					   classId, objectId, 0,
 					   TableSpaceRelationId, newTablespaceId,
diff --git a/src/backend/catalog/pg_tablespace.c b/src/backend/catalog/pg_tablespace.c
index 6aca24c231e..3b3fade8c42 100644
--- a/src/backend/catalog/pg_tablespace.c
+++ b/src/backend/catalog/pg_tablespace.c
@@ -39,7 +39,7 @@ get_tablespace_location(Oid tablespaceOid)
 	 * "the database's default tablespace".  So, rather than throwing an error
 	 * for zero, we choose to assume that's what is meant.
 	 */
-	if (tablespaceOid == InvalidOid)
+	if (!OidIsValid(tablespaceOid))
 		tablespaceOid = MyDatabaseTableSpace;
 
 	/*
diff --git a/src/backend/catalog/toasting.c b/src/backend/catalog/toasting.c
index 874a8fc89ad..e42bb2a2082 100644
--- a/src/backend/catalog/toasting.c
+++ b/src/backend/catalog/toasting.c
@@ -265,7 +265,7 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
 										   true,
 										   OIDOldToast,
 										   NULL);
-	Assert(toast_relid != InvalidOid);
+	Assert(OidIsValid(toast_relid));
 
 	/* make the toast relation visible, else table_open will fail */
 	CommandCounterIncrement();
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index 4268adfe787..97376cecf3e 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -320,7 +320,7 @@ DefineAggregate(ParseState *pstate,
 		/* Parameter defaults are not currently allowed by the grammar */
 		Assert(parameterDefaults == NIL);
 		/* There shouldn't have been any OUT parameters, either */
-		Assert(requiredResultType == InvalidOid);
+		Assert(!OidIsValid(requiredResultType));
 	}
 
 	/*
diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index b55221d44cd..d8990930145 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -776,7 +776,7 @@ make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod,
 										  true,
 										  OIDOldHeap,
 										  NULL);
-	Assert(OIDNewHeap != InvalidOid);
+	Assert(OidIsValid(OIDNewHeap));
 
 	ReleaseSysCache(tuple);
 
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index cef452584e5..24caa59e037 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -844,7 +844,7 @@ BeginCopyTo(ParseState *pstate,
 		 * the relation again, we double-check here to make sure it found the
 		 * same one that we have locked.
 		 */
-		if (queryRelId != InvalidOid)
+		if (OidIsValid(queryRelId))
 		{
 			/*
 			 * Note that with RLS involved there may be multiple relations,
diff --git a/src/backend/commands/event_trigger.c b/src/backend/commands/event_trigger.c
index f34868da5ab..31ec353139d 100644
--- a/src/backend/commands/event_trigger.c
+++ b/src/backend/commands/event_trigger.c
@@ -1623,7 +1623,7 @@ pg_event_trigger_table_rewrite_oid(PG_FUNCTION_ARGS)
 	 * Protect this function from being called out of context
 	 */
 	if (!currentEventTriggerState ||
-		currentEventTriggerState->table_rewrite_oid == InvalidOid)
+		!OidIsValid(currentEventTriggerState->table_rewrite_oid))
 		ereport(ERROR,
 				(errcode(ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED),
 				 errmsg("%s can only be called in a table_rewrite event trigger function",
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index 93ef1ad106f..43a5642fd10 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -3234,7 +3234,7 @@ AlterExtensionNamespace(const char *extensionName, const char *newschema, Oid *o
 		 * If not all the objects had the same old namespace (ignoring any
 		 * that are not in namespaces or are dependent types), complain.
 		 */
-		if (dep_oldNspOid != InvalidOid && dep_oldNspOid != oldNspOid)
+		if (OidIsValid(dep_oldNspOid) && dep_oldNspOid != oldNspOid)
 			ereport(ERROR,
 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 					 errmsg("extension \"%s\" does not support SET SCHEMA",
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 0335e982b31..e6b1aa9b414 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -1160,7 +1160,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
 			Oid			elt = get_base_element_type(typeid);
 			Oid			transformid;
 
-			typeid = elt ? elt : typeid;
+			typeid = OidIsValid(elt) ? elt : typeid;
 			transformid = get_transform_oid(typeid, languageOid, false);
 			trftypes_list = lappend_oid(trftypes_list, typeid);
 			trfoids_list = lappend_oid(trfoids_list, transformid);
@@ -1188,7 +1188,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
 	if (stmt->is_procedure)
 	{
 		Assert(!stmt->returnType);
-		prorettype = requiredResultType ? requiredResultType : VOIDOID;
+		prorettype = OidIsValid(requiredResultType) ? requiredResultType : VOIDOID;
 		returnsSet = false;
 	}
 	else if (stmt->returnType)
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 5712fac3697..9b23db79be6 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -1049,7 +1049,7 @@ DefineIndex(Oid tableId,
 						else if (exclusion)
 							idx_eqop = indexInfo->ii_ExclusionOps[j];
 
-						if (!idx_eqop)
+						if (!OidIsValid(idx_eqop))
 							ereport(ERROR,
 									errcode(ERRCODE_UNDEFINED_OBJECT),
 									errmsg("could not identify an equality operator for type %s", format_type_be(idx_opcintype)),
@@ -1441,12 +1441,12 @@ DefineIndex(Oid tableId,
 						 * is no such constraint, this index is no good, so
 						 * keep looking.
 						 */
-						if (createdConstraintId != InvalidOid)
+						if (OidIsValid(createdConstraintId))
 						{
 							cldConstrOid =
 								get_relation_idx_constraint_oid(childRelid,
 																cldidxid);
-							if (cldConstrOid == InvalidOid)
+							if (!OidIsValid(cldConstrOid))
 							{
 								index_close(cldidx, lockmode);
 								continue;
@@ -1455,7 +1455,7 @@ DefineIndex(Oid tableId,
 
 						/* Attach index to parent and we're done. */
 						IndexSetParentIndex(cldidx, indexRelationId);
-						if (createdConstraintId != InvalidOid)
+						if (OidIsValid(createdConstraintId))
 							ConstraintSetParentConstraint(cldConstrOid,
 														  createdConstraintId,
 														  childRelid);
@@ -4470,7 +4470,7 @@ IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
 
 	if (!HeapTupleIsValid(tuple))
 	{
-		if (parentOid == InvalidOid)
+		if (!OidIsValid(parentOid))
 		{
 			/*
 			 * No pg_inherits row, and no parent wanted: nothing to do in this
@@ -4488,7 +4488,7 @@ IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
 	{
 		Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
 
-		if (parentOid == InvalidOid)
+		if (!OidIsValid(parentOid))
 		{
 			/*
 			 * There exists a pg_inherits row, which we want to clear; do so.
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index 8d671b7a29d..9373b118059 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -211,7 +211,7 @@ DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
 
 	address = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);
 	seqoid = address.objectId;
-	Assert(seqoid != InvalidOid);
+	Assert(OidIsValid(seqoid));
 
 	rel = sequence_open(seqoid, AccessExclusiveLock);
 	tupDesc = RelationGetDescr(rel);
@@ -462,7 +462,7 @@ AlterSequence(ParseState *pstate, AlterSeqStmt *stmt)
 									 stmt->missing_ok ? RVR_MISSING_OK : 0,
 									 RangeVarCallbackOwnsRelation,
 									 NULL);
-	if (relid == InvalidOid)
+	if (!OidIsValid(relid))
 	{
 		ereport(NOTICE,
 				(errmsg("relation \"%s\" does not exist, skipping",
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..4fed5e5e99a 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -276,7 +276,7 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 
 			/* Disallow data types without a less-than operator */
 			type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
-			if (type->lt_opr == InvalidOid)
+			if (!OidIsValid(type->lt_opr))
 				ereport(ERROR,
 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 						 errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
@@ -305,7 +305,7 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 
 			/* Disallow data types without a less-than operator */
 			type = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR);
-			if (type->lt_opr == InvalidOid)
+			if (!OidIsValid(type->lt_opr))
 				ereport(ERROR,
 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 						 errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
@@ -355,7 +355,7 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			{
 				atttype = exprType(expr);
 				type = lookup_type_cache(atttype, TYPECACHE_LT_OPR);
-				if (type->lt_opr == InvalidOid)
+				if (!OidIsValid(type->lt_opr))
 					ereport(ERROR,
 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 							 errmsg("expression cannot be used in multivariate statistics because its type %s has no default btree operator class",
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 23ebaa3f230..1118a5fc437 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -3692,7 +3692,7 @@ CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
 	 */
 	oldTableSpaceId = rel->rd_rel->reltablespace;
 	if (newTableSpaceId == oldTableSpaceId ||
-		(newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
+		(newTableSpaceId == MyDatabaseTableSpace && !OidIsValid(oldTableSpaceId)))
 		return false;
 
 	/*
@@ -4050,9 +4050,9 @@ rename_constraint_internal(Oid myrelid,
 	Form_pg_constraint con;
 	ObjectAddress address;
 
-	Assert(!myrelid || !mytypid);
+	Assert(!OidIsValid(myrelid) || !OidIsValid(mytypid));
 
-	if (mytypid)
+	if (OidIsValid(mytypid))
 	{
 		constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
 	}
@@ -4075,7 +4075,7 @@ rename_constraint_internal(Oid myrelid,
 			 constraintOid);
 	con = (Form_pg_constraint) GETSTRUCT(tuple);
 
-	if (myrelid &&
+	if (OidIsValid(myrelid) &&
 		(con->contype == CONSTRAINT_CHECK ||
 		 con->contype == CONSTRAINT_NOTNULL) &&
 		!con->connoinherit)
@@ -5917,7 +5917,7 @@ ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
 			 * Select destination tablespace (same as original unless user
 			 * requested a change)
 			 */
-			if (tab->newTableSpace)
+			if (OidIsValid(tab->newTableSpace))
 				NewTableSpace = tab->newTableSpace;
 			else
 				NewTableSpace = OldHeap->rd_rel->reltablespace;
@@ -6018,7 +6018,7 @@ ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
 			 * If we had SET TABLESPACE but no reason to reconstruct tuples,
 			 * just do a block-by-block copy.
 			 */
-			if (tab->newTableSpace)
+			if (OidIsValid(tab->newTableSpace))
 				ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
 		}
 
@@ -12090,12 +12090,12 @@ GetForeignKeyActionTriggers(Relation trigrel,
 			continue;
 		if (TRIGGER_FOR_DELETE(trgform->tgtype))
 		{
-			Assert(*deleteTriggerOid == InvalidOid);
+			Assert(!OidIsValid(*deleteTriggerOid));
 			*deleteTriggerOid = trgform->oid;
 		}
 		else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
 		{
-			Assert(*updateTriggerOid == InvalidOid);
+			Assert(!OidIsValid(*updateTriggerOid));
 			*updateTriggerOid = trgform->oid;
 		}
 #ifndef USE_ASSERT_CHECKING
@@ -12151,12 +12151,12 @@ GetForeignKeyCheckTriggers(Relation trigrel,
 			continue;
 		if (TRIGGER_FOR_INSERT(trgform->tgtype))
 		{
-			Assert(*insertTriggerOid == InvalidOid);
+			Assert(!OidIsValid(*insertTriggerOid));
 			*insertTriggerOid = trgform->oid;
 		}
 		else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
 		{
-			Assert(*updateTriggerOid == InvalidOid);
+			Assert(!OidIsValid(*updateTriggerOid));
 			*updateTriggerOid = trgform->oid;
 		}
 #ifndef USE_ASSERT_CHECKING
@@ -17112,7 +17112,7 @@ AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
 		ereport(NOTICE,
 				(errcode(ERRCODE_NO_DATA_FOUND),
 				 errmsg("no matching relations in tablespace \"%s\" found",
-						orig_tablespaceoid == InvalidOid ? "(database default)" :
+						!OidIsValid(orig_tablespaceoid) ? "(database default)" :
 						get_tablespace_name(orig_tablespaceoid))));
 
 	/* Everything is locked, loop through and move all of the relations. */
diff --git a/src/backend/commands/tablespace.c b/src/backend/commands/tablespace.c
index df31eace47a..b328411d70a 100644
--- a/src/backend/commands/tablespace.c
+++ b/src/backend/commands/tablespace.c
@@ -1095,7 +1095,7 @@ check_default_tablespace(char **newval, void **extra, GucSource source)
 	 * cannot do the catalog accesses necessary to verify the name.  Must
 	 * accept the value on faith.
 	 */
-	if (IsTransactionState() && MyDatabaseId != InvalidOid)
+	if (IsTransactionState() && OidIsValid(MyDatabaseId))
 	{
 		if (**newval != '\0' &&
 			!OidIsValid(get_tablespace_oid(*newval, true)))
@@ -1219,7 +1219,7 @@ check_temp_tablespaces(char **newval, void **extra, GucSource source)
 	 * accept the value on faith. Fortunately, there's then also no need to
 	 * pass the data to fd.c.
 	 */
-	if (IsTransactionState() && MyDatabaseId != InvalidOid)
+	if (IsTransactionState() && OidIsValid(MyDatabaseId))
 	{
 		temp_tablespaces_extra *myextra;
 		Oid		   *tblSpcs;
@@ -1249,7 +1249,7 @@ check_temp_tablespaces(char **newval, void **extra, GucSource source)
 			 * nonexistent tablespace, only a NOTICE.  See comments in guc.h.
 			 */
 			curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
-			if (curoid == InvalidOid)
+			if (!OidIsValid(curoid))
 			{
 				if (source == PGC_S_TEST)
 					ereport(NOTICE,
@@ -1383,7 +1383,7 @@ PrepareTempTablespaces(void)
 
 		/* Else verify that name is a valid tablespace name */
 		curoid = get_tablespace_oid(curname, true);
-		if (curoid == InvalidOid)
+		if (!OidIsValid(curoid))
 		{
 			/* Skip any bad list elements */
 			continue;
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..28dab16d239 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -2335,7 +2335,7 @@ ExecCallTriggerFunc(TriggerData *trigdata,
 	 * We cache fmgr lookup info, to avoid making the lookup again on each
 	 * call.
 	 */
-	if (finfo->fn_oid == InvalidOid)
+	if (!OidIsValid(finfo->fn_oid))
 		fmgr_info(trigdata->tg_trigger->tgfoid, finfo);
 
 	Assert(finfo->fn_oid == trigdata->tg_trigger->tgfoid);
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index 5979580139f..341c1b7f574 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -529,28 +529,28 @@ DefineType(ParseState *pstate, List *names, List *parameters)
 	 * findTypeInputFunction et al, where they could be shared by AlterType.
 	 */
 #ifdef NOT_USED
-	if (inputOid && !object_ownercheck(ProcedureRelationId, inputOid, GetUserId()))
+	if (OidIsValid(inputOid) && !object_ownercheck(ProcedureRelationId, inputOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(inputName));
-	if (outputOid && !object_ownercheck(ProcedureRelationId, outputOid, GetUserId()))
+	if (OidIsValid(outputOid) && !object_ownercheck(ProcedureRelationId, outputOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(outputName));
-	if (receiveOid && !object_ownercheck(ProcedureRelationId, receiveOid, GetUserId()))
+	if (OidIsValid(receiveOid) && !object_ownercheck(ProcedureRelationId, receiveOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(receiveName));
-	if (sendOid && !object_ownercheck(ProcedureRelationId, sendOid, GetUserId()))
+	if (OidIsValid(sendOid) && !object_ownercheck(ProcedureRelationId, sendOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(sendName));
-	if (typmodinOid && !object_ownercheck(ProcedureRelationId, typmodinOid, GetUserId()))
+	if (OidIsValid(typmodinOid) && !object_ownercheck(ProcedureRelationId, typmodinOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(typmodinName));
-	if (typmodoutOid && !object_ownercheck(ProcedureRelationId, typmodoutOid, GetUserId()))
+	if (OidIsValid(typmodoutOid) && !object_ownercheck(ProcedureRelationId, typmodoutOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(typmodoutName));
-	if (analyzeOid && !object_ownercheck(ProcedureRelationId, analyzeOid, GetUserId()))
+	if (OidIsValid(analyzeOid) && !object_ownercheck(ProcedureRelationId, analyzeOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(analyzeName));
-	if (subscriptOid && !object_ownercheck(ProcedureRelationId, subscriptOid, GetUserId()))
+	if (OidIsValid(subscriptOid) && !object_ownercheck(ProcedureRelationId, subscriptOid, GetUserId()))
 		aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
 					   NameListToString(subscriptName));
 #endif
@@ -1592,7 +1592,7 @@ DefineRange(ParseState *pstate, CreateRangeStmt *stmt)
 				   0,			/* Array dimensions of typbasetype */
 				   false,		/* Type NOT NULL */
 				   InvalidOid); /* type's collation (ranges never have one) */
-	Assert(typoid == InvalidOid || typoid == address.objectId);
+	Assert(!OidIsValid(typoid) || typoid == address.objectId);
 	typoid = address.objectId;
 
 	/* Create the multirange that goes with it */
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index e785dd55ce5..27873557c0f 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -2320,7 +2320,7 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params,
 	 * the toaster always uses hardcoded index access and statistics are
 	 * totally unimportant for toast relations.
 	 */
-	if (toast_relid != InvalidOid)
+	if (OidIsValid(toast_relid))
 	{
 		/*
 		 * Force VACOPT_PROCESS_MAIN so vacuum_rel() processes it.  Likewise,
diff --git a/src/backend/commands/view.c b/src/backend/commands/view.c
index 6f0301555e0..f02c80de0fd 100644
--- a/src/backend/commands/view.c
+++ b/src/backend/commands/view.c
@@ -245,7 +245,7 @@ DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace,
 		 */
 		address = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid, NULL,
 								 NULL);
-		Assert(address.objectId != InvalidOid);
+		Assert(OidIsValid(address.objectId));
 
 		/* Make the new view relation visible */
 		CommandCounterIncrement();
diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c
index fdc65c2b42b..9b0ee5427aa 100644
--- a/src/backend/executor/execUtils.c
+++ b/src/backend/executor/execUtils.c
@@ -1495,5 +1495,5 @@ ExecGetResultRelCheckAsUser(ResultRelInfo *relInfo, EState *estate)
 		elog(ERROR, "no RTEPermissionInfo found for result relation with OID %u",
 			 RelationGetRelid(relInfo->ri_RelationDesc));
 
-	return perminfo->checkAsUser ? perminfo->checkAsUser : GetUserId();
+	return OidIsValid(perminfo->checkAsUser) ? perminfo->checkAsUser : GetUserId();
 }
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 630d708d2a3..ae4cc1a8f43 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -286,7 +286,7 @@ prepare_sql_fn_parse_info(HeapTuple procedureTuple,
 			if (IsPolymorphicType(argtype))
 			{
 				argtype = get_call_expr_argtype(call_expr, argnum);
-				if (argtype == InvalidOid)
+				if (!OidIsValid(argtype))
 					ereport(ERROR,
 							(errcode(ERRCODE_DATATYPE_MISMATCH),
 							 errmsg("could not determine actual type of argument declared %s",
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index ede838cd40c..5b11184bd0b 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -1241,12 +1241,12 @@ exprSetCollation(Node *expr, Oid collation)
 		case T_SQLValueFunction:
 			Assert((((SQLValueFunction *) expr)->type == NAMEOID) ?
 				   (collation == C_COLLATION_OID) :
-				   (collation == InvalidOid));
+				   (!OidIsValid(collation)));
 			break;
 		case T_XmlExpr:
 			Assert((((XmlExpr *) expr)->op == IS_XMLSERIALIZE) ?
 				   (collation == DEFAULT_COLLATION_OID) :
-				   (collation == InvalidOid));
+				   (!OidIsValid(collation)));
 			break;
 		case T_JsonValueExpr:
 			exprSetCollation((Node *) ((JsonValueExpr *) expr)->formatted_expr,
@@ -1867,7 +1867,7 @@ fix_opfuncids_walker(Node *node, void *context)
 void
 set_opfuncid(OpExpr *opexpr)
 {
-	if (opexpr->opfuncid == InvalidOid)
+	if (!OidIsValid(opexpr->opfuncid))
 		opexpr->opfuncid = get_opcode(opexpr->opno);
 }
 
@@ -1878,7 +1878,7 @@ set_opfuncid(OpExpr *opexpr)
 void
 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
 {
-	if (opexpr->opfuncid == InvalidOid)
+	if (!OidIsValid(opexpr->opfuncid))
 		opexpr->opfuncid = get_opcode(opexpr->opno);
 }
 
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 8335cf5b5c5..6915c2be08a 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -6270,7 +6270,7 @@ set_rel_width(PlannerInfo *root, RelOptInfo *rel)
 			}
 
 			/* Try to get column width from statistics */
-			if (reloid != InvalidOid && var->varattno > 0)
+			if (OidIsValid(reloid) && var->varattno > 0)
 			{
 				item_width = get_attavgwidth(reloid, var->varattno);
 				if (item_width > 0)
@@ -6333,7 +6333,7 @@ set_rel_width(PlannerInfo *root, RelOptInfo *rel)
 	{
 		int64		wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
 
-		if (reloid != InvalidOid)
+		if (OidIsValid(reloid))
 		{
 			/* Real relation, so estimate true tuple width */
 			wholerow_width += get_relation_data_width(reloid,
diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c
index edc6d2ac1d3..62a6642222b 100644
--- a/src/backend/optimizer/path/indxpath.c
+++ b/src/backend/optimizer/path/indxpath.c
@@ -3258,7 +3258,7 @@ match_rowcompare_to_indexcol(PlannerInfo *root,
 	{
 		/* indexkey is on right, so commute the operator */
 		expr_op = get_commutator(expr_op);
-		if (expr_op == InvalidOid)
+		if (!OidIsValid(expr_op))
 			return NULL;
 		var_on_left = false;
 	}
@@ -3585,7 +3585,7 @@ expand_indexqual_rowcompare(PlannerInfo *root,
 		{
 			/* indexkey is on right, so commute the operator */
 			expr_op = get_commutator(expr_op);
-			if (expr_op == InvalidOid)
+			if (!OidIsValid(expr_op))
 				break;			/* operator is not usable */
 		}
 		if (bms_is_member(index->rel->relid, pull_varnos(root, constop)))
@@ -3903,7 +3903,7 @@ match_clause_to_ordering_op(IndexOptInfo *index,
 	{
 		/* Might match, but we need a commuted operator */
 		expr_op = get_commutator(expr_op);
-		if (expr_op == InvalidOid)
+		if (!OidIsValid(expr_op))
 			return NULL;
 		commuted = true;
 	}
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index ea5b6415186..0bddd63a613 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -2155,7 +2155,7 @@ hash_inner_and_outer(PlannerInfo *root,
 			continue;
 
 		if (!restrictinfo->can_join ||
-			restrictinfo->hashjoinoperator == InvalidOid)
+			!OidIsValid(restrictinfo->hashjoinoperator))
 			continue;			/* not hashjoinable */
 
 		/*
diff --git a/src/backend/optimizer/prep/prepqual.c b/src/backend/optimizer/prep/prepqual.c
index 008dce2478c..f8a60f429ee 100644
--- a/src/backend/optimizer/prep/prepqual.c
+++ b/src/backend/optimizer/prep/prepqual.c
@@ -95,7 +95,7 @@ negate_clause(Node *node)
 				OpExpr	   *opexpr = (OpExpr *) node;
 				Oid			negator = get_negator(opexpr->opno);
 
-				if (negator)
+				if (OidIsValid(negator))
 				{
 					OpExpr	   *newopexpr = makeNode(OpExpr);
 
@@ -120,7 +120,7 @@ negate_clause(Node *node)
 				ScalarArrayOpExpr *saopexpr = (ScalarArrayOpExpr *) node;
 				Oid			negator = get_negator(saopexpr->opno);
 
-				if (negator)
+				if (OidIsValid(negator))
 				{
 					ScalarArrayOpExpr *newopexpr = makeNode(ScalarArrayOpExpr);
 
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index a01f781bca8..f244d53d709 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -822,7 +822,7 @@ infer_arbiter_indexes(PlannerInfo *root)
 	 * that already).
 	 */
 	if (onconflict->arbiterElems == NIL &&
-		onconflict->constraint == InvalidOid)
+		!OidIsValid(onconflict->constraint))
 		return NIL;
 
 	/*
@@ -869,11 +869,11 @@ infer_arbiter_indexes(PlannerInfo *root)
 	 * Lookup named constraint's index.  This is not immediately returned
 	 * because some additional sanity checks are required.
 	 */
-	if (onconflict->constraint != InvalidOid)
+	if (OidIsValid(onconflict->constraint))
 	{
 		indexOidFromConstraint = get_constraint_index(onconflict->constraint);
 
-		if (indexOidFromConstraint == InvalidOid)
+		if (!OidIsValid(indexOidFromConstraint))
 			ereport(ERROR,
 					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
 					 errmsg("constraint in ON CONFLICT clause has no associated index")));
@@ -934,7 +934,7 @@ infer_arbiter_indexes(PlannerInfo *root)
 			table_close(relation, NoLock);
 			return results;
 		}
-		else if (indexOidFromConstraint != InvalidOid)
+		else if (OidIsValid(indexOidFromConstraint))
 		{
 			/* No point in further work for index in named constraint case */
 			goto next;
@@ -1003,8 +1003,8 @@ infer_arbiter_indexes(PlannerInfo *root)
 			 * Otherwise, check that element expression appears in cataloged
 			 * index definition.
 			 */
-			if (elem->infercollid != InvalidOid ||
-				elem->inferopclass != InvalidOid ||
+			if (OidIsValid(elem->infercollid) ||
+				OidIsValid(elem->inferopclass) ||
 				list_member(idxExprs, elem->expr))
 				continue;
 
@@ -1088,13 +1088,13 @@ infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
 	 * If inference specification element lacks collation/opclass, then no
 	 * need to check for exact match.
 	 */
-	if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
+	if (!OidIsValid(elem->infercollid) && !OidIsValid(elem->inferopclass))
 		return true;
 
 	/*
 	 * Lookup opfamily and input type, for matching indexes
 	 */
-	if (elem->inferopclass)
+	if (OidIsValid(elem->inferopclass))
 	{
 		inferopfamily = get_opclass_family(elem->inferopclass);
 		inferopcinputtype = get_opclass_input_type(elem->inferopclass);
@@ -1110,14 +1110,14 @@ infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
 		if (attno != 0)
 			nplain++;
 
-		if (elem->inferopclass != InvalidOid &&
+		if (OidIsValid(elem->inferopclass) &&
 			(inferopfamily != opfamily || inferopcinputtype != opcinputtype))
 		{
 			/* Attribute needed to match opclass, but didn't */
 			continue;
 		}
 
-		if (elem->infercollid != InvalidOid &&
+		if (OidIsValid(elem->infercollid) &&
 			elem->infercollid != collation)
 		{
 			/* Attribute needed to match collation, but didn't */
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index ca26f6f61f2..abf44a9beb8 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -3709,7 +3709,7 @@ targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
 		SortGroupClause *scl = (SortGroupClause *) lfirst(l);
 
 		if (scl->tleSortGroupRef == ref &&
-			(sortop == InvalidOid ||
+			(!OidIsValid(sortop) ||
 			 sortop == scl->sortop ||
 			 sortop == get_commutator(scl->sortop)))
 			return true;
diff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c
index 78b1e366ad7..d112aaf4464 100644
--- a/src/backend/parser/parse_coerce.c
+++ b/src/backend/parser/parse_coerce.c
@@ -3242,8 +3242,8 @@ find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
 			Oid			targetElem;
 			Oid			sourceElem;
 
-			if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
-				(sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
+			if (OidIsValid((targetElem = get_element_type(targetTypeId))) &&
+				OidIsValid((sourceElem = get_element_type(sourceTypeId))))
 			{
 				CoercionPathType elempathtype;
 				Oid			elemfuncid;
@@ -3383,7 +3383,7 @@ typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
 	Oid			relid = typeOrDomainTypeRelid(reltypeId);
 	bool		result = false;
 
-	if (relid)
+	if (OidIsValid(relid))
 	{
 		HeapTuple	tp;
 		Form_pg_class reltup;
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 32d6ae918ca..47b4ba2ccf2 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -1199,7 +1199,7 @@ transformAExprIn(ParseState *pstate, A_Expr *a)
 			array_type = get_array_type(scalar_type);
 		else
 			array_type = InvalidOid;
-		if (array_type != InvalidOid)
+		if (OidIsValid(array_type))
 		{
 			/*
 			 * OK: coerce all the right-hand non-Var inputs to the common type
@@ -2047,7 +2047,7 @@ transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
 									  element_type,
 									  typmod);
 			/* we certainly have an array here */
-			Assert(array_type == InvalidOid || array_type == exprType(newe));
+			Assert(!OidIsValid(array_type) || array_type == exprType(newe));
 			newa->multidims = true;
 		}
 		else
@@ -2752,7 +2752,7 @@ transformTypeCast(ParseState *pstate, TypeCast *tc)
 		expr = transformExprRecurse(pstate, arg);
 
 	inputType = exprType(expr);
-	if (inputType == InvalidOid)
+	if (!OidIsValid(inputType))
 		return expr;			/* do nothing if NULL input */
 
 	/*
diff --git a/src/backend/parser/parse_oper.c b/src/backend/parser/parse_oper.c
index 7bd7a336fd6..7daebbde586 100644
--- a/src/backend/parser/parse_oper.c
+++ b/src/backend/parser/parse_oper.c
@@ -266,12 +266,12 @@ binary_oper_exact(List *opname, Oid arg1, Oid arg2)
 	bool		was_unknown = false;
 
 	/* Unspecified type for one of the arguments? then use the other */
-	if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
+	if ((arg1 == UNKNOWNOID) && (OidIsValid(arg2)))
 	{
 		arg1 = arg2;
 		was_unknown = true;
 	}
-	else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
+	else if ((arg2 == UNKNOWNOID) && (OidIsValid(arg1)))
 	{
 		arg2 = arg1;
 		was_unknown = true;
@@ -417,9 +417,9 @@ oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId,
 			 */
 			Oid			inputOids[2];
 
-			if (rtypeId == InvalidOid)
+			if (!OidIsValid(rtypeId))
 				rtypeId = ltypeId;
-			else if (ltypeId == InvalidOid)
+			else if (!OidIsValid(ltypeId))
 				ltypeId = rtypeId;
 			inputOids[0] = ltypeId;
 			inputOids[1] = rtypeId;
@@ -641,7 +641,7 @@ op_error(ParseState *pstate, List *op,
 				(errcode(ERRCODE_UNDEFINED_FUNCTION),
 				 errmsg("operator does not exist: %s",
 						op_signature_string(op, arg1, arg2)),
-				 oper_lookup_failure_details(fgc_flags, (!arg1 || !arg2)),
+				 oper_lookup_failure_details(fgc_flags, (!OidIsValid(arg1) || !OidIsValid(arg2))),
 				 parser_errposition(pstate, location)));
 }
 
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..281e01de843 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -775,7 +775,7 @@ transformAssignmentIndirection(ParseState *pstate,
 			baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
 
 			typrelid = typeidTypeRelid(baseTypeId);
-			if (!typrelid)
+			if (!OidIsValid(typrelid))
 				ereport(ERROR,
 						(errcode(ERRCODE_DATATYPE_MISMATCH),
 						 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
diff --git a/src/backend/parser/parse_type.c b/src/backend/parser/parse_type.c
index 7713bdc6af0..c0ddd714db0 100644
--- a/src/backend/parser/parse_type.c
+++ b/src/backend/parser/parse_type.c
@@ -357,7 +357,7 @@ typenameTypeMod(ParseState *pstate, const TypeName *typeName, Type typ)
 
 	typmodin = ((Form_pg_type) GETSTRUCT(typ))->typmodin;
 
-	if (typmodin == InvalidOid)
+	if (!OidIsValid(typmodin))
 		ereport(ERROR,
 				(errcode(ERRCODE_SYNTAX_ERROR),
 				 errmsg("type modifier is not allowed for type \"%s\"",
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index e96b38a59d5..36894527bd4 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -525,7 +525,7 @@ generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column,
 	 * clause, the "redundant options" error will point to their occurrence,
 	 * not our synthetic one.
 	 */
-	if (seqtypid)
+	if (OidIsValid(seqtypid))
 		seqstmt->options = lcons(makeDefElem("as",
 											 (Node *) makeTypeNameFromOid(seqtypid, -1),
 											 -1),
@@ -3746,7 +3746,7 @@ transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
 
 					seq_relid = getIdentitySequence(rel, attnum, true);
 
-					if (seq_relid)
+					if (OidIsValid(seq_relid))
 					{
 						AlterSeqStmt *seqstmt;
 
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index 239641bfbb6..40f4a4878df 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -1105,7 +1105,7 @@ libpqrcv_exec(WalReceiverConn *conn, const char *query,
 	WalRcvExecResult *walres = palloc0(sizeof(WalRcvExecResult));
 	char	   *diag_sqlstate;
 
-	if (MyDatabaseId == InvalidOid)
+	if (!OidIsValid(MyDatabaseId))
 		ereport(ERROR,
 				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 				 errmsg("the query interface requires a database connection")));
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index cc03f0706e9..fd3906b2d18 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -1306,7 +1306,7 @@ DecodeTXNNeedSkip(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
 				  Oid txn_dbid, RepOriginId origin_id)
 {
 	if (SnapBuildXactNeedsSkip(ctx->snapshot_builder, buf->origptr) ||
-		(txn_dbid != InvalidOid && txn_dbid != ctx->slot->data.database) ||
+		(OidIsValid(txn_dbid) && txn_dbid != ctx->slot->data.database) ||
 		FilterByOrigin(ctx, origin_id))
 		return true;
 
diff --git a/src/backend/replication/logical/logical.c b/src/backend/replication/logical/logical.c
index 866f92cf799..b304f2f8906 100644
--- a/src/backend/replication/logical/logical.c
+++ b/src/backend/replication/logical/logical.c
@@ -122,7 +122,7 @@ CheckLogicalDecodingRequirements(void)
 				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 				 errmsg("logical decoding requires \"wal_level\" >= \"logical\"")));
 
-	if (MyDatabaseId == InvalidOid)
+	if (!OidIsValid(MyDatabaseId))
 		ereport(ERROR,
 				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 				 errmsg("logical decoding requires a database connection")));
diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 745fd3bab64..9059f7faf73 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -69,7 +69,7 @@ logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
 	if (LogicalRepRelMap == NULL)
 		return;
 
-	if (reloid != InvalidOid)
+	if (OidIsValid(reloid))
 	{
 		HASH_SEQ_STATUS status;
 
@@ -540,7 +540,7 @@ logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
 	if (LogicalRepPartMap == NULL)
 		return;
 
-	if (reloid != InvalidOid)
+	if (OidIsValid(reloid))
 	{
 		HASH_SEQ_STATUS status;
 
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index eb6a84554b7..c1c13f43918 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2342,11 +2342,11 @@ ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
 					 * whether the table should be logically logged without
 					 * mapping the relfilenumber to the oid.
 					 */
-					if (reloid == InvalidOid &&
+					if (!OidIsValid(reloid) &&
 						change->data.tp.newtuple == NULL &&
 						change->data.tp.oldtuple == NULL)
 						goto change_done;
-					else if (reloid == InvalidOid)
+					else if (!OidIsValid(reloid))
 						elog(ERROR, "could not map filenumber \"%s\" to relation OID",
 							 relpathperm(change->data.tp.rlocator,
 										 MAIN_FORKNUM).str);
diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 942e1abdb58..7063dfdab21 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -2231,7 +2231,7 @@ get_rel_sync_entry(PGOutputData *data, Relation relation)
 															   ancestors,
 															   &level);
 
-					if (ancestor != InvalidOid)
+					if (OidIsValid(ancestor))
 					{
 						ancestor_published = true;
 						if (pub->pubviaroot)
diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
index 1ec1e997b27..6d8dccb89f1 100644
--- a/src/backend/replication/slot.c
+++ b/src/backend/replication/slot.c
@@ -1763,7 +1763,7 @@ DetermineSlotInvalidationCause(uint32 possible_causes, ReplicationSlot *s,
 	{
 		/* invalid DB oid signals a shared relation */
 		if (SlotIsLogical(s) &&
-			(dboid == InvalidOid || dboid == s->data.database))
+			(!OidIsValid(dboid) || dboid == s->data.database))
 		{
 			TransactionId effective_xmin = s->effective_xmin;
 			TransactionId catalog_effective_xmin = s->effective_catalog_xmin;
@@ -2637,7 +2637,7 @@ RestoreSlotFromDisk(const char *name)
 	 * NB: Changing the requirements here also requires adapting
 	 * CheckSlotRequirements() and CheckLogicalDecodingRequirements().
 	 */
-	if (cp.slotdata.database != InvalidOid)
+	if (OidIsValid(cp.slotdata.database))
 	{
 		if (wal_level < WAL_LEVEL_LOGICAL)
 			ereport(FATAL,
diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c
index 0478fc9c977..cf25bcfcd22 100644
--- a/src/backend/replication/slotfuncs.c
+++ b/src/backend/replication/slotfuncs.c
@@ -275,17 +275,17 @@ pg_get_replication_slots(PG_FUNCTION_ARGS)
 		i = 0;
 		values[i++] = NameGetDatum(&slot_contents.data.name);
 
-		if (slot_contents.data.database == InvalidOid)
+		if (!OidIsValid(slot_contents.data.database))
 			nulls[i++] = true;
 		else
 			values[i++] = NameGetDatum(&slot_contents.data.plugin);
 
-		if (slot_contents.data.database == InvalidOid)
+		if (!OidIsValid(slot_contents.data.database))
 			values[i++] = CStringGetTextDatum("physical");
 		else
 			values[i++] = CStringGetTextDatum("logical");
 
-		if (slot_contents.data.database == InvalidOid)
+		if (!OidIsValid(slot_contents.data.database))
 			nulls[i++] = true;
 		else
 			values[i++] = ObjectIdGetDatum(slot_contents.data.database);
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index fc8f8559073..8945290e685 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -324,7 +324,7 @@ InitWalSender(void)
 	 * databases.  This allows physical replication clients to send hot
 	 * standby feedback that will delay vacuum cleanup in all databases.
 	 */
-	if (MyDatabaseId == InvalidOid)
+	if (!OidIsValid(MyDatabaseId))
 	{
 		Assert(MyProc->xmin == InvalidTransactionId);
 		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
@@ -428,7 +428,7 @@ IdentifySystem(void)
 
 	snprintf(xloc, sizeof(xloc), "%X/%08X", LSN_FORMAT_ARGS(logptr));
 
-	if (MyDatabaseId != InvalidOid)
+	if (OidIsValid(MyDatabaseId))
 	{
 		MemoryContext cur = CurrentMemoryContext;
 
@@ -2062,7 +2062,7 @@ exec_replication_command(const char *cmd_string)
 		MemoryContextReset(cmd_context);
 
 		/* XXX this is a pretty random place to make this check */
-		if (MyDatabaseId == InvalidOid)
+		if (!OidIsValid(MyDatabaseId))
 			ereport(ERROR,
 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 					 errmsg("cannot execute SQL commands in WAL sender for physical replication")));
@@ -3067,7 +3067,7 @@ InitWalSenderSlot(void)
 			 * StartLogicalReplication() and CREATE_REPLICATION_SLOT but it
 			 * seems better to set it on one place.
 			 */
-			if (MyDatabaseId == InvalidOid)
+			if (!OidIsValid(MyDatabaseId))
 				walsnd->kind = REPLICATION_KIND_PHYSICAL;
 			else
 				walsnd->kind = REPLICATION_KIND_LOGICAL;
diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c
index adc9e7600e1..80e9077d28f 100644
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -4518,7 +4518,7 @@ build_generation_expression(Relation rel, int attrno)
 	 * expression.
 	 */
 	attcollid = att_tup->attcollation;
-	if (attcollid && attcollid != exprCollation(defexpr))
+	if (OidIsValid(attcollid) && attcollid != exprCollation(defexpr))
 	{
 		CollateExpr *ce = makeNode(CollateExpr);
 
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index 6f63b4f3ffb..4b7234fef4e 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -261,7 +261,7 @@ dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency)
 		TypeCacheEntry *type;
 
 		type = lookup_type_cache(colstat->attrtypid, TYPECACHE_LT_OPR);
-		if (type->lt_opr == InvalidOid) /* shouldn't happen */
+		if (!OidIsValid(type->lt_opr))	/* shouldn't happen */
 			elog(ERROR, "cache lookup failed for ordering operator for type %u",
 				 colstat->attrtypid);
 
diff --git a/src/backend/statistics/mcv.c b/src/backend/statistics/mcv.c
index f59fb821543..e531f74796c 100644
--- a/src/backend/statistics/mcv.c
+++ b/src/backend/statistics/mcv.c
@@ -359,7 +359,7 @@ build_mss(StatsBuildData *data)
 		TypeCacheEntry *type;
 
 		type = lookup_type_cache(colstat->attrtypid, TYPECACHE_LT_OPR);
-		if (type->lt_opr == InvalidOid) /* shouldn't happen */
+		if (!OidIsValid(type->lt_opr))	/* shouldn't happen */
 			elog(ERROR, "cache lookup failed for ordering operator for type %u",
 				 colstat->attrtypid);
 
diff --git a/src/backend/statistics/mvdistinct.c b/src/backend/statistics/mvdistinct.c
index fe452f53ae4..dc2b801b30e 100644
--- a/src/backend/statistics/mvdistinct.c
+++ b/src/backend/statistics/mvdistinct.c
@@ -387,7 +387,7 @@ ndistinct_for_combination(double totalrows, StatsBuildData *data,
 		collid = colstat->attrcollid;
 
 		type = lookup_type_cache(typid, TYPECACHE_LT_OPR);
-		if (type->lt_opr == InvalidOid) /* shouldn't happen */
+		if (!OidIsValid(type->lt_opr))	/* shouldn't happen */
 			elog(ERROR, "cache lookup failed for ordering operator for type %u",
 				 typid);
 
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 327ddb7adc8..a7355ed57a7 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -3449,7 +3449,7 @@ BufferSync(int flags)
 		 * Grow array of per-tablespace status structs, every time a new
 		 * tablespace is found.
 		 */
-		if (last_tsid == InvalidOid || last_tsid != cur_tsid)
+		if (!OidIsValid(last_tsid) || last_tsid != cur_tsid)
 		{
 			Size		sz;
 
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index e9eaaf9c829..cca2be29899 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -1758,7 +1758,7 @@ OpenTemporaryFile(bool interXact)
 	 * here, but just in case it isn't, fall back to pg_default tablespace.
 	 */
 	if (file <= 0)
-		file = OpenTemporaryFileInTablespace(MyDatabaseTableSpace ?
+		file = OpenTemporaryFileInTablespace(OidIsValid(MyDatabaseTableSpace) ?
 											 MyDatabaseTableSpace :
 											 DEFAULTTABLESPACE_OID,
 											 true);
@@ -1784,7 +1784,7 @@ TempTablespacePath(char *path, Oid tablespace)
 	 *
 	 * If someone tries to specify pg_global, use pg_default instead.
 	 */
-	if (tablespace == InvalidOid ||
+	if (!OidIsValid(tablespace) ||
 		tablespace == DEFAULTTABLESPACE_OID ||
 		tablespace == GLOBALTABLESPACE_OID)
 		snprintf(path, MAXPGPATH, "base/%s", PG_TEMP_FILES_DIR);
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index 200f72c6e25..7d81ac78264 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -1803,7 +1803,7 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
 		 * machinery.
 		 */
 		if (proc->databaseId == MyDatabaseId ||
-			MyDatabaseId == InvalidOid ||
+			!OidIsValid(MyDatabaseId) ||
 			(statusFlags & PROC_AFFECTS_ALL_HORIZONS) ||
 			in_recovery)
 		{
@@ -3631,7 +3631,7 @@ CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 		int			pgprocno = arrayP->pgprocnos[index];
 		PGPROC	   *proc = &allProcs[pgprocno];
 
-		if (databaseid == InvalidOid || proc->databaseId == databaseid)
+		if (!OidIsValid(databaseid) || proc->databaseId == databaseid)
 		{
 			VirtualTransactionId procvxid;
 			pid_t		pid;
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 4cc7f645c31..de5829fc368 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -268,7 +268,7 @@ int			FastPathLockGroupsPerBackend = 0;
 	((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
 	(locktag)->locktag_type == LOCKTAG_RELATION && \
 	(locktag)->locktag_field1 == MyDatabaseId && \
-	MyDatabaseId != InvalidOid && \
+	OidIsValid(MyDatabaseId) && \
 	(mode) < ShareUpdateExclusiveLock)
 #define ConflictsWithRelationFastPath(locktag, mode) \
 	((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
diff --git a/src/backend/storage/lmgr/predicate.c b/src/backend/storage/lmgr/predicate.c
index bb807d8c9cd..c983f7fce52 100644
--- a/src/backend/storage/lmgr/predicate.c
+++ b/src/backend/storage/lmgr/predicate.c
@@ -2971,7 +2971,7 @@ DropAllPredicateLocksFromTable(Relation relation, bool transfer)
 		isIndex = true;
 		heapId = relation->rd_index->indrelid;
 	}
-	Assert(heapId != InvalidOid);
+	Assert(OidIsValid(heapId));
 	Assert(transfer || !isIndex);	/* index OID only makes sense with
 									 * transfer */
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 7dd75a490aa..19e00b1d259 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -733,7 +733,7 @@ pg_analyze_and_rewrite_varparams(RawStmt *parsetree,
 	{
 		Oid			ptype = (*paramTypes)[i];
 
-		if (ptype == InvalidOid || ptype == UNKNOWNOID)
+		if (!OidIsValid(ptype) || ptype == UNKNOWNOID)
 			ereport(ERROR,
 					(errcode(ERRCODE_INDETERMINATE_DATATYPE),
 					 errmsg("could not determine data type of parameter $%d",
diff --git a/src/backend/tsearch/ts_parse.c b/src/backend/tsearch/ts_parse.c
index cba421892bf..540c3f70703 100644
--- a/src/backend/tsearch/ts_parse.c
+++ b/src/backend/tsearch/ts_parse.c
@@ -177,7 +177,7 @@ LexizeExec(LexizeData *ld, ParsedLex **correspondLexem)
 	TSDictionaryCacheEntry *dict;
 	TSLexeme   *res;
 
-	if (ld->curDictId == InvalidOid)
+	if (!OidIsValid(ld->curDictId))
 	{
 		/*
 		 * usual mode: dictionary wants only one word, but we should keep in
diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c
index 7ef06150df7..b16ba5aebaa 100644
--- a/src/backend/utils/activity/pgstat.c
+++ b/src/backend/utils/activity/pgstat.c
@@ -1156,7 +1156,7 @@ pgstat_build_snapshot(void)
 		 * relations).
 		 */
 		if (p->key.dboid != MyDatabaseId &&
-			p->key.dboid != InvalidOid &&
+			OidIsValid(p->key.dboid) &&
 			!kind_info->accessed_across_databases)
 			continue;
 
diff --git a/src/backend/utils/adt/array_selfuncs.c b/src/backend/utils/adt/array_selfuncs.c
index 4dab35b0057..fe72f25a20d 100644
--- a/src/backend/utils/adt/array_selfuncs.c
+++ b/src/backend/utils/adt/array_selfuncs.c
@@ -296,7 +296,7 @@ arraycontsel(PG_FUNCTION_ARGS)
 	 * we'd rather just return a default estimate.)
 	 */
 	element_typeid = get_base_element_type(((Const *) other)->consttype);
-	if (element_typeid != InvalidOid &&
+	if (OidIsValid(element_typeid) &&
 		element_typeid == get_base_element_type(vardata.vartype))
 	{
 		selec = calc_arraycontsel(&vardata, ((Const *) other)->constvalue,
diff --git a/src/backend/utils/adt/array_userfuncs.c b/src/backend/utils/adt/array_userfuncs.c
index 8eb342e3382..0f655af6e0f 100644
--- a/src/backend/utils/adt/array_userfuncs.c
+++ b/src/backend/utils/adt/array_userfuncs.c
@@ -559,7 +559,7 @@ array_agg_transfn(PG_FUNCTION_ARGS)
 	ArrayBuildState *state;
 	Datum		elem;
 
-	if (arg1_typeid == InvalidOid)
+	if (!OidIsValid(arg1_typeid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
@@ -936,7 +936,7 @@ array_agg_array_transfn(PG_FUNCTION_ARGS)
 	MemoryContext aggcontext;
 	ArrayBuildStateArr *state;
 
-	if (arg1_typeid == InvalidOid)
+	if (!OidIsValid(arg1_typeid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
diff --git a/src/backend/utils/adt/enum.c b/src/backend/utils/adt/enum.c
index fcc6981632b..4c2a456c12a 100644
--- a/src/backend/utils/adt/enum.c
+++ b/src/backend/utils/adt/enum.c
@@ -445,7 +445,7 @@ enum_first(PG_FUNCTION_ARGS)
 	 * examined at all; in particular it might be NULL.
 	 */
 	enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (enumtypoid == InvalidOid)
+	if (!OidIsValid(enumtypoid))
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("could not determine actual enum type")));
@@ -474,7 +474,7 @@ enum_last(PG_FUNCTION_ARGS)
 	 * examined at all; in particular it might be NULL.
 	 */
 	enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (enumtypoid == InvalidOid)
+	if (!OidIsValid(enumtypoid))
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("could not determine actual enum type")));
@@ -514,7 +514,7 @@ enum_range_bounds(PG_FUNCTION_ARGS)
 	 * both are of the same type.
 	 */
 	enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (enumtypoid == InvalidOid)
+	if (!OidIsValid(enumtypoid))
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("could not determine actual enum type")));
@@ -534,7 +534,7 @@ enum_range_all(PG_FUNCTION_ARGS)
 	 * examined at all; in particular it might be NULL.
 	 */
 	enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (enumtypoid == InvalidOid)
+	if (!OidIsValid(enumtypoid))
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("could not determine actual enum type")));
diff --git a/src/backend/utils/adt/format_type.c b/src/backend/utils/adt/format_type.c
index 9948c26e76c..4b7f7cdae3a 100644
--- a/src/backend/utils/adt/format_type.c
+++ b/src/backend/utils/adt/format_type.c
@@ -118,7 +118,7 @@ format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
 	char	   *buf;
 	bool		with_typemod;
 
-	if (type_oid == InvalidOid)
+	if (!OidIsValid(type_oid))
 	{
 		if ((flags & FORMAT_TYPE_INVALID_AS_NULL) != 0)
 			return NULL;
@@ -375,7 +375,7 @@ printTypmod(const char *typname, int32 typmod, Oid typmodout)
 	/* Shouldn't be called if typmod is -1 */
 	Assert(typmod >= 0);
 
-	if (typmodout == InvalidOid)
+	if (!OidIsValid(typmodout))
 	{
 		/* Default behavior: just print the integer typmod with parens */
 		res = psprintf("%s(%d)", typname, (int) typmod);
diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 06dd62f0008..6316b7a4fab 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -606,7 +606,7 @@ add_json(Datum val, bool is_null, StringInfo result,
 	JsonTypeCategory tcategory;
 	Oid			outfuncoid;
 
-	if (val_type == InvalidOid)
+	if (!OidIsValid(val_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
@@ -744,7 +744,7 @@ to_json(PG_FUNCTION_ARGS)
 	JsonTypeCategory tcategory;
 	Oid			outfuncoid;
 
-	if (val_type == InvalidOid)
+	if (!OidIsValid(val_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
@@ -795,7 +795,7 @@ json_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null)
 	{
 		Oid			arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine input data type")));
@@ -1039,7 +1039,7 @@ json_object_agg_transfn_worker(FunctionCallInfo fcinfo,
 
 		arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine data type for argument %d", 1)));
@@ -1049,7 +1049,7 @@ json_object_agg_transfn_worker(FunctionCallInfo fcinfo,
 
 		arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine data type for argument %d", 2)));
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index 9399cdb491a..a9e21aa5008 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -1020,7 +1020,7 @@ add_jsonb(Datum val, bool is_null, JsonbInState *result,
 	JsonTypeCategory tcategory;
 	Oid			outfuncoid;
 
-	if (val_type == InvalidOid)
+	if (!OidIsValid(val_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
@@ -1093,7 +1093,7 @@ to_jsonb(PG_FUNCTION_ARGS)
 	JsonTypeCategory tcategory;
 	Oid			outfuncoid;
 
-	if (val_type == InvalidOid)
+	if (!OidIsValid(val_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("could not determine input data type")));
@@ -1525,7 +1525,7 @@ jsonb_agg_transfn_worker(FunctionCallInfo fcinfo, bool absent_on_null)
 	{
 		Oid			arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine input data type")));
@@ -1713,7 +1713,7 @@ jsonb_object_agg_transfn_worker(FunctionCallInfo fcinfo,
 
 		arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine input data type")));
@@ -1723,7 +1723,7 @@ jsonb_object_agg_transfn_worker(FunctionCallInfo fcinfo,
 
 		arg_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
 
-		if (arg_type == InvalidOid)
+		if (!OidIsValid(arg_type))
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("could not determine input data type")));
diff --git a/src/backend/utils/adt/like_support.c b/src/backend/utils/adt/like_support.c
index 999f23f86d5..5dbb2f57b4b 100644
--- a/src/backend/utils/adt/like_support.c
+++ b/src/backend/utils/adt/like_support.c
@@ -405,7 +405,7 @@ match_pattern_prefix(Node *leftop,
 	 *
 	 * expr_coll is not set for a non-collation-aware data type such as bytea.
 	 */
-	if (expr_coll && !get_collation_isdeterministic(expr_coll))
+	if (OidIsValid(expr_coll) && !get_collation_isdeterministic(expr_coll))
 		return NIL;
 
 	/*
diff --git a/src/backend/utils/adt/misc.c b/src/backend/utils/adt/misc.c
index a365c432d34..8d84efc42c3 100644
--- a/src/backend/utils/adt/misc.c
+++ b/src/backend/utils/adt/misc.c
@@ -284,7 +284,7 @@ pg_tablespace_databases(PG_FUNCTION_ARGS)
 		bool		nulls[1];
 
 		/* this test skips . and .., but is awfully weak */
-		if (!datOid)
+		if (!OidIsValid(datOid))
 			continue;
 
 		/* if database subdir is empty, don't report tablespace as used */
@@ -593,7 +593,7 @@ pg_collation_for(PG_FUNCTION_ARGS)
 	Oid			collid;
 
 	typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (!typeid)
+	if (!OidIsValid(typeid))
 		PG_RETURN_NULL();
 	if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
 		ereport(ERROR,
@@ -602,7 +602,7 @@ pg_collation_for(PG_FUNCTION_ARGS)
 						format_type_be(typeid))));
 
 	collid = PG_GET_COLLATION();
-	if (!collid)
+	if (!OidIsValid(collid))
 		PG_RETURN_NULL();
 	PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
 }
@@ -761,7 +761,7 @@ pg_input_is_valid_common(FunctionCallInfo fcinfo,
 	 * If the typname argument is constant, we only need to parse it the first
 	 * time through.
 	 */
-	if (my_extra->typoid == InvalidOid || !my_extra->typname_constant)
+	if (!OidIsValid(my_extra->typoid) || !my_extra->typname_constant)
 	{
 		char	   *typnamestr = text_to_cstring(typname);
 		Oid			typoid;
diff --git a/src/backend/utils/adt/multirangetypes_selfuncs.c b/src/backend/utils/adt/multirangetypes_selfuncs.c
index 21f0205d803..d5cd6adc2bc 100644
--- a/src/backend/utils/adt/multirangetypes_selfuncs.c
+++ b/src/backend/utils/adt/multirangetypes_selfuncs.c
@@ -183,7 +183,7 @@ multirangesel(PG_FUNCTION_ARGS)
 	{
 		/* we have other Op var, commute to make var Op other */
 		operator = get_commutator(operator);
-		if (!operator)
+		if (!OidIsValid(operator))
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
diff --git a/src/backend/utils/adt/network.c b/src/backend/utils/adt/network.c
index 3cb0ab6829a..f0962aff0d1 100644
--- a/src/backend/utils/adt/network.c
+++ b/src/backend/utils/adt/network.c
@@ -1064,7 +1064,7 @@ match_network_subset(Node *leftop,
 	 * operator disallows equality.
 	 */
 	opr1oid = get_opfamily_member_for_cmptype(opfamily, datatype, datatype, is_eq ? COMPARE_GE : COMPARE_GT);
-	if (opr1oid == InvalidOid)
+	if (!OidIsValid(opr1oid))
 		return NIL;
 
 	opr1right = network_scan_first(rightopval);
@@ -1081,7 +1081,7 @@ match_network_subset(Node *leftop,
 	/* create clause "key <= network_scan_last( rightopval )" */
 
 	opr2oid = get_opfamily_member_for_cmptype(opfamily, datatype, datatype, COMPARE_LE);
-	if (opr2oid == InvalidOid)
+	if (!OidIsValid(opr2oid))
 		return NIL;
 
 	opr2right = network_scan_last(rightopval);
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 1521d6e2ab4..5b8727349b0 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -380,14 +380,14 @@ pg_stat_get_activity(PG_FUNCTION_ARGS)
 			continue;
 
 		/* Values available to all callers */
-		if (beentry->st_databaseid != InvalidOid)
+		if (OidIsValid(beentry->st_databaseid))
 			values[0] = ObjectIdGetDatum(beentry->st_databaseid);
 		else
 			nulls[0] = true;
 
 		values[1] = Int32GetDatum(beentry->st_procpid);
 
-		if (beentry->st_userid != InvalidOid)
+		if (OidIsValid(beentry->st_userid))
 			values[2] = ObjectIdGetDatum(beentry->st_userid);
 		else
 			nulls[2] = true;
diff --git a/src/backend/utils/adt/rangetypes_selfuncs.c b/src/backend/utils/adt/rangetypes_selfuncs.c
index d85252cafb2..f112aac5b26 100644
--- a/src/backend/utils/adt/rangetypes_selfuncs.c
+++ b/src/backend/utils/adt/rangetypes_selfuncs.c
@@ -153,7 +153,7 @@ rangesel(PG_FUNCTION_ARGS)
 	{
 		/* we have other Op var, commute to make var Op other */
 		operator = get_commutator(operator);
-		if (!operator)
+		if (!OidIsValid(operator))
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
diff --git a/src/backend/utils/adt/regproc.c b/src/backend/utils/adt/regproc.c
index 7ce61efd947..22b0319abdf 100644
--- a/src/backend/utils/adt/regproc.c
+++ b/src/backend/utils/adt/regproc.c
@@ -555,7 +555,7 @@ regoperout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	opertup;
 
-	if (oprid == InvalidOid)
+	if (!OidIsValid(oprid))
 	{
 		result = pstrdup("0");
 		PG_RETURN_CSTRING(result);
@@ -849,7 +849,7 @@ regoperatorout(PG_FUNCTION_ARGS)
 	Oid			oprid = PG_GETARG_OID(0);
 	char	   *result;
 
-	if (oprid == InvalidOid)
+	if (!OidIsValid(oprid))
 		result = pstrdup("0");
 	else
 		result = format_operator(oprid);
@@ -954,7 +954,7 @@ regclassout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	classtup;
 
-	if (classid == InvalidOid)
+	if (!OidIsValid(classid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1097,7 +1097,7 @@ regcollationout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	collationtup;
 
-	if (collationid == InvalidOid)
+	if (!OidIsValid(collationid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1258,7 +1258,7 @@ regtypeout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	typetup;
 
-	if (typid == InvalidOid)
+	if (!OidIsValid(typid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1370,7 +1370,7 @@ regconfigout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	cfgtup;
 
-	if (cfgid == InvalidOid)
+	if (!OidIsValid(cfgid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1480,7 +1480,7 @@ regdictionaryout(PG_FUNCTION_ARGS)
 	char	   *result;
 	HeapTuple	dicttup;
 
-	if (dictid == InvalidOid)
+	if (!OidIsValid(dictid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1611,7 +1611,7 @@ regroleout(PG_FUNCTION_ARGS)
 	Oid			roleoid = PG_GETARG_OID(0);
 	char	   *result;
 
-	if (roleoid == InvalidOid)
+	if (!OidIsValid(roleoid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1728,7 +1728,7 @@ regnamespaceout(PG_FUNCTION_ARGS)
 	Oid			nspid = PG_GETARG_OID(0);
 	char	   *result;
 
-	if (nspid == InvalidOid)
+	if (!OidIsValid(nspid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
@@ -1845,7 +1845,7 @@ regdatabaseout(PG_FUNCTION_ARGS)
 	Oid			dboid = PG_GETARG_OID(0);
 	char	   *result;
 
-	if (dboid == InvalidOid)
+	if (!OidIsValid(dboid))
 	{
 		result = pstrdup("-");
 		PG_RETURN_CSTRING(result);
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 556ab057e5a..1e4f57bf245 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -10425,12 +10425,12 @@ get_rule_expr(Node *node, deparse_context *context,
 
 				context->varprefix = save_varprefix;
 
-				if (iexpr->infercollid)
+				if (OidIsValid(iexpr->infercollid))
 					appendStringInfo(buf, " COLLATE %s",
 									 generate_collation_name(iexpr->infercollid));
 
 				/* Add the operator class name, if not default */
-				if (iexpr->inferopclass)
+				if (OidIsValid(iexpr->inferopclass))
 				{
 					Oid			inferopclass = iexpr->inferopclass;
 					Oid			inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 911376f79e8..6ea9b19fd27 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -1450,7 +1450,7 @@ scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
 	if (!varonleft)
 	{
 		operator = get_commutator(operator);
-		if (!operator)
+		if (!OidIsValid(operator))
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
@@ -2886,7 +2886,7 @@ neqjoinsel(PG_FUNCTION_ARGS)
 		 */
 		Oid			eqop = get_negator(operator);
 
-		if (eqop)
+		if (OidIsValid(eqop))
 		{
 			result =
 				DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
@@ -4338,7 +4338,7 @@ estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel,
 	}
 
 	/* No match? */
-	if (statOid == InvalidOid)
+	if (!OidIsValid(statOid))
 		return false;
 
 	Assert(nmatches_vars + nmatches_exprs > 1);
@@ -6116,7 +6116,7 @@ examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index,
 
 		Assert(rte->rtekind == RTE_RELATION);
 		relid = rte->relid;
-		Assert(relid != InvalidOid);
+		Assert(OidIsValid(relid));
 		colnum = index->indexkeys[indexcol];
 		vardata->rel = index->rel;
 
diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c
index 3f40c9da1a0..6e3f4e6df7f 100644
--- a/src/backend/utils/adt/varchar.c
+++ b/src/backend/utils/adt/varchar.c
@@ -994,7 +994,7 @@ hashbpchar(PG_FUNCTION_ARGS)
 	pg_locale_t mylocale;
 	Datum		result;
 
-	if (!collid)
+	if (!OidIsValid(collid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INDETERMINATE_COLLATION),
 				 errmsg("could not determine which collation to use for string hashing"),
@@ -1050,7 +1050,7 @@ hashbpcharextended(PG_FUNCTION_ARGS)
 	pg_locale_t mylocale;
 	Datum		result;
 
-	if (!collid)
+	if (!OidIsValid(collid))
 		ereport(ERROR,
 				(errcode(ERRCODE_INDETERMINATE_COLLATION),
 				 errmsg("could not determine which collation to use for string hashing"),
diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 02505c88b8e..25893fc0d78 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -647,7 +647,7 @@ RegisterRelcacheInvalidation(InvalidationInfo *info, Oid dbId, Oid relId)
 	 * invalidations for a specific database always invalidate the shared file
 	 * as well.  Also zap when we are invalidating whole relcache.
 	 */
-	if (relId == InvalidOid || RelationIdIsInInitFile(relId))
+	if (!OidIsValid(relId) || RelationIdIsInInitFile(relId))
 		info->RelcacheInitFileInval = true;
 }
 
@@ -824,7 +824,7 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
 {
 	if (msg->id >= 0)
 	{
-		if (msg->cc.dbId == MyDatabaseId || msg->cc.dbId == InvalidOid)
+		if (msg->cc.dbId == MyDatabaseId || !OidIsValid(msg->cc.dbId))
 		{
 			InvalidateCatalogSnapshot();
 
@@ -835,7 +835,7 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
 	}
 	else if (msg->id == SHAREDINVALCATALOG_ID)
 	{
-		if (msg->cat.dbId == MyDatabaseId || msg->cat.dbId == InvalidOid)
+		if (msg->cat.dbId == MyDatabaseId || !OidIsValid(msg->cat.dbId))
 		{
 			InvalidateCatalogSnapshot();
 
@@ -846,11 +846,11 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
 	}
 	else if (msg->id == SHAREDINVALRELCACHE_ID)
 	{
-		if (msg->rc.dbId == MyDatabaseId || msg->rc.dbId == InvalidOid)
+		if (msg->rc.dbId == MyDatabaseId || !OidIsValid(msg->rc.dbId))
 		{
 			int			i;
 
-			if (msg->rc.relId == InvalidOid)
+			if (!OidIsValid(msg->rc.relId))
 				RelationCacheInvalidate(false);
 			else
 				RelationCacheInvalidateEntry(msg->rc.relId);
@@ -878,7 +878,7 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
 	else if (msg->id == SHAREDINVALRELMAP_ID)
 	{
 		/* We only care about our own database and shared catalogs */
-		if (msg->rm.dbId == InvalidOid)
+		if (!OidIsValid(msg->rm.dbId))
 			RelationMapInvalidate(true);
 		else if (msg->rm.dbId == MyDatabaseId)
 			RelationMapInvalidate(false);
@@ -886,7 +886,7 @@ LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
 	else if (msg->id == SHAREDINVALSNAPSHOT_ID)
 	{
 		/* We only care about our own database and shared catalogs */
-		if (msg->sn.dbId == InvalidOid)
+		if (!OidIsValid(msg->sn.dbId))
 			InvalidateCatalogSnapshot();
 		else if (msg->sn.dbId == MyDatabaseId)
 			InvalidateCatalogSnapshot();
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index fa7cd7e06a7..1d2430d6233 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -3416,7 +3416,7 @@ get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple,
 	for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
 	{
 		if ((&stats->stakind1)[i] == reqkind &&
-			(reqop == InvalidOid || (&stats->staop1)[i] == reqop))
+			(!OidIsValid(reqop) || (&stats->staop1)[i] == reqop))
 			break;
 	}
 	if (i >= STATISTIC_NUM_SLOTS)
diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index 6661d2c6b73..54772e6c260 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -2140,7 +2140,7 @@ PlanCacheRelCallback(Datum arg, Oid relid)
 		/*
 		 * Check the dependency list for the rewritten querytree.
 		 */
-		if ((relid == InvalidOid) ? plansource->relationOids != NIL :
+		if ((!OidIsValid(relid)) ? plansource->relationOids != NIL :
 			list_member_oid(plansource->relationOids, relid))
 		{
 			/* Invalidate the querytree and generic plan */
@@ -2163,7 +2163,7 @@ PlanCacheRelCallback(Datum arg, Oid relid)
 
 				if (plannedstmt->commandType == CMD_UTILITY)
 					continue;	/* Ignore utility statements */
-				if ((relid == InvalidOid) ? plannedstmt->relationOids != NIL :
+				if ((!OidIsValid(relid)) ? plannedstmt->relationOids != NIL :
 					list_member_oid(plannedstmt->relationOids, relid))
 				{
 					/* Invalidate the generic plan only */
@@ -2186,7 +2186,7 @@ PlanCacheRelCallback(Datum arg, Oid relid)
 		if (!cexpr->is_valid)
 			continue;
 
-		if ((relid == InvalidOid) ? cexpr->relationOids != NIL :
+		if ((!OidIsValid(relid)) ? cexpr->relationOids != NIL :
 			list_member_oid(cexpr->relationOids, relid))
 		{
 			cexpr->is_valid = false;
diff --git a/src/backend/utils/cache/relfilenumbermap.c b/src/backend/utils/cache/relfilenumbermap.c
index 0b6f9cf3fa1..3abd6f03282 100644
--- a/src/backend/utils/cache/relfilenumbermap.c
+++ b/src/backend/utils/cache/relfilenumbermap.c
@@ -65,8 +65,8 @@ RelfilenumberMapInvalidateCallback(Datum arg, Oid relid)
 		 * all entries, otherwise just remove the specific relation's entry.
 		 * Always remove negative cache entries.
 		 */
-		if (relid == InvalidOid ||	/* complete reset */
-			entry->relid == InvalidOid ||	/* negative cache entry */
+		if (!OidIsValid(relid) ||	/* complete reset */
+			!OidIsValid(entry->relid) ||	/* negative cache entry */
 			entry->relid == relid)	/* individual flushed relation */
 		{
 			if (hash_search(RelfilenumberMapHash,
diff --git a/src/backend/utils/cache/spccache.c b/src/backend/utils/cache/spccache.c
index 23458599298..657f1a8f9d3 100644
--- a/src/backend/utils/cache/spccache.c
+++ b/src/backend/utils/cache/spccache.c
@@ -114,7 +114,7 @@ get_tablespace(Oid spcid)
 	 * Since spcid is always from a pg_class tuple, InvalidOid implies the
 	 * default.
 	 */
-	if (spcid == InvalidOid)
+	if (!OidIsValid(spcid))
 		spcid = MyDatabaseTableSpace;
 
 	/* Find existing cache entry, if any. */
diff --git a/src/backend/utils/cache/ts_cache.c b/src/backend/utils/cache/ts_cache.c
index e8ae53238d0..4642d175d53 100644
--- a/src/backend/utils/cache/ts_cache.c
+++ b/src/backend/utils/cache/ts_cache.c
@@ -608,7 +608,7 @@ check_default_text_search_config(char **newval, void **extra, GucSource source)
 	 * cannot do the catalog accesses necessary to verify the config name.
 	 * Must accept it on faith.
 	 */
-	if (IsTransactionState() && MyDatabaseId != InvalidOid)
+	if (IsTransactionState() && OidIsValid(MyDatabaseId))
 	{
 		ErrorSaveContext escontext = {T_ErrorSaveContext};
 		List	   *namelist;
diff --git a/src/backend/utils/cache/typcache.c b/src/backend/utils/cache/typcache.c
index 6a347698edf..6757efbfb95 100644
--- a/src/backend/utils/cache/typcache.c
+++ b/src/backend/utils/cache/typcache.c
@@ -594,7 +594,7 @@ lookup_type_cache(Oid type_id, int flags)
 	 */
 	if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO)) &&
 		!(typentry->flags & TCFLAGS_CHECKED_EQ_OPR) &&
-		typentry->btree_opf == InvalidOid)
+		!OidIsValid(typentry->btree_opf))
 		flags |= TYPECACHE_HASH_OPFAMILY;
 
 	if ((flags & (TYPECACHE_HASH_PROC | TYPECACHE_HASH_PROC_FINFO |
@@ -634,13 +634,13 @@ lookup_type_cache(Oid type_id, int flags)
 	{
 		Oid			eq_opr = InvalidOid;
 
-		if (typentry->btree_opf != InvalidOid)
+		if (OidIsValid(typentry->btree_opf))
 			eq_opr = get_opfamily_member(typentry->btree_opf,
 										 typentry->btree_opintype,
 										 typentry->btree_opintype,
 										 BTEqualStrategyNumber);
-		if (eq_opr == InvalidOid &&
-			typentry->hash_opf != InvalidOid)
+		if (!OidIsValid(eq_opr) &&
+			OidIsValid(typentry->hash_opf))
 			eq_opr = get_opfamily_member(typentry->hash_opf,
 										 typentry->hash_opintype,
 										 typentry->hash_opintype,
@@ -681,7 +681,7 @@ lookup_type_cache(Oid type_id, int flags)
 	{
 		Oid			lt_opr = InvalidOid;
 
-		if (typentry->btree_opf != InvalidOid)
+		if (OidIsValid(typentry->btree_opf))
 			lt_opr = get_opfamily_member(typentry->btree_opf,
 										 typentry->btree_opintype,
 										 typentry->btree_opintype,
@@ -706,7 +706,7 @@ lookup_type_cache(Oid type_id, int flags)
 	{
 		Oid			gt_opr = InvalidOid;
 
-		if (typentry->btree_opf != InvalidOid)
+		if (OidIsValid(typentry->btree_opf))
 			gt_opr = get_opfamily_member(typentry->btree_opf,
 										 typentry->btree_opintype,
 										 typentry->btree_opintype,
@@ -731,7 +731,7 @@ lookup_type_cache(Oid type_id, int flags)
 	{
 		Oid			cmp_proc = InvalidOid;
 
-		if (typentry->btree_opf != InvalidOid)
+		if (OidIsValid(typentry->btree_opf))
 			cmp_proc = get_opfamily_proc(typentry->btree_opf,
 										 typentry->btree_opintype,
 										 typentry->btree_opintype,
@@ -764,7 +764,7 @@ lookup_type_cache(Oid type_id, int flags)
 		 * We insist that the eq_opr, if one has been determined, match the
 		 * hash opclass; else report there is no hash function.
 		 */
-		if (typentry->hash_opf != InvalidOid &&
+		if (OidIsValid(typentry->hash_opf) &&
 			(!OidIsValid(typentry->eq_opr) ||
 			 typentry->eq_opr == get_opfamily_member(typentry->hash_opf,
 													 typentry->hash_opintype,
@@ -813,7 +813,7 @@ lookup_type_cache(Oid type_id, int flags)
 		 * We insist that the eq_opr, if one has been determined, match the
 		 * hash opclass; else report there is no hash function.
 		 */
-		if (typentry->hash_opf != InvalidOid &&
+		if (OidIsValid(typentry->hash_opf) &&
 			(!OidIsValid(typentry->eq_opr) ||
 			 typentry->eq_opr == get_opfamily_member(typentry->hash_opf,
 													 typentry->hash_opintype,
@@ -866,33 +866,33 @@ lookup_type_cache(Oid type_id, int flags)
 	 * that would cause session-lifespan memory leaks.
 	 */
 	if ((flags & TYPECACHE_EQ_OPR_FINFO) &&
-		typentry->eq_opr_finfo.fn_oid == InvalidOid &&
-		typentry->eq_opr != InvalidOid)
+		!OidIsValid(typentry->eq_opr_finfo.fn_oid) &&
+		OidIsValid(typentry->eq_opr))
 	{
 		Oid			eq_opr_func;
 
 		eq_opr_func = get_opcode(typentry->eq_opr);
-		if (eq_opr_func != InvalidOid)
+		if (OidIsValid(eq_opr_func))
 			fmgr_info_cxt(eq_opr_func, &typentry->eq_opr_finfo,
 						  CacheMemoryContext);
 	}
 	if ((flags & TYPECACHE_CMP_PROC_FINFO) &&
-		typentry->cmp_proc_finfo.fn_oid == InvalidOid &&
-		typentry->cmp_proc != InvalidOid)
+		!OidIsValid(typentry->cmp_proc_finfo.fn_oid) &&
+		OidIsValid(typentry->cmp_proc))
 	{
 		fmgr_info_cxt(typentry->cmp_proc, &typentry->cmp_proc_finfo,
 					  CacheMemoryContext);
 	}
 	if ((flags & TYPECACHE_HASH_PROC_FINFO) &&
-		typentry->hash_proc_finfo.fn_oid == InvalidOid &&
-		typentry->hash_proc != InvalidOid)
+		!OidIsValid(typentry->hash_proc_finfo.fn_oid) &&
+		OidIsValid(typentry->hash_proc))
 	{
 		fmgr_info_cxt(typentry->hash_proc, &typentry->hash_proc_finfo,
 					  CacheMemoryContext);
 	}
 	if ((flags & TYPECACHE_HASH_EXTENDED_PROC_FINFO) &&
-		typentry->hash_extended_proc_finfo.fn_oid == InvalidOid &&
-		typentry->hash_extended_proc != InvalidOid)
+		!OidIsValid(typentry->hash_extended_proc_finfo.fn_oid) &&
+		OidIsValid(typentry->hash_extended_proc))
 	{
 		fmgr_info_cxt(typentry->hash_extended_proc,
 					  &typentry->hash_extended_proc_finfo,
@@ -938,7 +938,7 @@ lookup_type_cache(Oid type_id, int flags)
 	 * If requested, get information about a domain type
 	 */
 	if ((flags & TYPECACHE_DOMAIN_BASE_INFO) &&
-		typentry->domainBaseType == InvalidOid &&
+		!OidIsValid(typentry->domainBaseType) &&
 		typentry->typtype == TYPTYPE_DOMAIN)
 	{
 		typentry->domainBaseTypmod = -1;
@@ -1678,7 +1678,7 @@ cache_record_field_properties(TypeCacheEntry *typentry)
 		TypeCacheEntry *baseentry;
 
 		/* load up basetype info if we didn't already */
-		if (typentry->domainBaseType == InvalidOid)
+		if (!OidIsValid(typentry->domainBaseType))
 		{
 			typentry->domainBaseTypmod = -1;
 			typentry->domainBaseType =
diff --git a/src/backend/utils/fmgr/funcapi.c b/src/backend/utils/fmgr/funcapi.c
index 5f2317211c9..98b88b12231 100644
--- a/src/backend/utils/fmgr/funcapi.c
+++ b/src/backend/utils/fmgr/funcapi.c
@@ -490,7 +490,7 @@ internal_get_result_type(Oid funcid,
 	{
 		Oid			newrettype = exprType(call_expr);
 
-		if (newrettype == InvalidOid)	/* this probably should not happen */
+		if (!OidIsValid(newrettype))	/* this probably should not happen */
 			ereport(ERROR,
 					(errcode(ERRCODE_DATATYPE_MISMATCH),
 					 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
diff --git a/src/backend/utils/misc/queryenvironment.c b/src/backend/utils/misc/queryenvironment.c
index 7bc72dabe67..8ae1783bc0e 100644
--- a/src/backend/utils/misc/queryenvironment.c
+++ b/src/backend/utils/misc/queryenvironment.c
@@ -127,7 +127,7 @@ ENRMetadataGetTupDesc(EphemeralNamedRelationMetadata enrmd)
 	TupleDesc	tupdesc;
 
 	/* One, and only one, of these fields must be filled. */
-	Assert((enrmd->reliddesc == InvalidOid) != (enrmd->tupdesc == NULL));
+	Assert((!OidIsValid(enrmd->reliddesc)) != (enrmd->tupdesc == NULL));
 
 	if (enrmd->tupdesc != NULL)
 		tupdesc = enrmd->tupdesc;
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 4e7303ea631..bc1d3a7adc8 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -402,7 +402,7 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 			IndxInfo   *parentidx;
 			IndexAttachInfo *attachinfo;
 
-			if (index->parentidx == 0)
+			if (!OidIsValid(index->parentidx))
 				continue;
 
 			parentidx = findIndexByOid(index->parentidx);
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index c84b017f21b..0122ec6239d 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -1518,7 +1518,7 @@ StartRestoreLO(ArchiveHandle *AH, Oid oid, bool drop)
 		if (old_lo_style)
 		{
 			loOid = lo_create(AH->connection, oid);
-			if (loOid == 0 || loOid != oid)
+			if (!OidIsValid(loOid) || loOid != oid)
 				pg_fatal("could not create large object %u: %s",
 						 oid, PQerrorMessage(AH->connection));
 		}
diff --git a/src/bin/pg_dump/pg_backup_custom.c b/src/bin/pg_dump/pg_backup_custom.c
index 2226520dffc..d2ea2397181 100644
--- a/src/bin/pg_dump/pg_backup_custom.c
+++ b/src/bin/pg_dump/pg_backup_custom.c
@@ -371,7 +371,7 @@ _StartLO(ArchiveHandle *AH, TocEntry *te, Oid oid)
 {
 	lclContext *ctx = (lclContext *) AH->formatData;
 
-	if (oid == 0)
+	if (!OidIsValid(oid))
 		pg_fatal("invalid OID for large object");
 
 	WriteInt(AH, oid);
@@ -583,7 +583,7 @@ _LoadLOs(ArchiveHandle *AH, bool drop)
 	StartRestoreLOs(AH);
 
 	oid = ReadInt(AH);
-	while (oid != 0)
+	while (OidIsValid(oid))
 	{
 		StartRestoreLO(AH, oid, drop);
 		_PrintData(AH);
@@ -606,7 +606,7 @@ _skipLOs(ArchiveHandle *AH)
 	Oid			oid;
 
 	oid = ReadInt(AH);
-	while (oid != 0)
+	while (OidIsValid(oid))
 	{
 		_skipData(AH);
 		oid = ReadInt(AH);
diff --git a/src/bin/pg_dump/pg_backup_null.c b/src/bin/pg_dump/pg_backup_null.c
index a3257f4fc84..a3bc2f93605 100644
--- a/src/bin/pg_dump/pg_backup_null.c
+++ b/src/bin/pg_dump/pg_backup_null.c
@@ -139,7 +139,7 @@ _StartLO(ArchiveHandle *AH, TocEntry *te, Oid oid)
 {
 	bool		old_lo_style = (AH->version < K_VERS_1_12);
 
-	if (oid == 0)
+	if (!OidIsValid(oid))
 		pg_fatal("invalid OID for large object");
 
 	/* With an old archive we must do drop and create logic here */
diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c
index b5ba3b46dd9..991ec51137e 100644
--- a/src/bin/pg_dump/pg_backup_tar.c
+++ b/src/bin/pg_dump/pg_backup_tar.c
@@ -678,7 +678,7 @@ _LoadLOs(ArchiveHandle *AH, TocEntry *te)
 		if (strncmp(th->targetFile, "blob_", 5) == 0)
 		{
 			oid = atooid(&th->targetFile[5]);
-			if (oid != 0)
+			if (OidIsValid(oid))
 			{
 				pg_log_info("restoring large object with OID %u", oid);
 
@@ -899,7 +899,7 @@ _StartLO(ArchiveHandle *AH, TocEntry *te, Oid oid)
 	lclTocEntry *tctx = (lclTocEntry *) te->formatData;
 	char		fname[255];
 
-	if (oid == 0)
+	if (!OidIsValid(oid))
 		pg_fatal("invalid OID for large object (%u)", oid);
 
 	if (AH->compression_spec.algorithm != PG_COMPRESSION_NONE)
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index a00918bacb4..253c2369897 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -8120,7 +8120,7 @@ getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 				NULL, NULL
 			};
 
-			if (indxinfo[j].parentidx == 0)
+			if (!OidIsValid(indxinfo->parentidx))
 				indexkind = RELKIND_INDEX;
 			else
 				indexkind = RELKIND_PARTITIONED_INDEX;
@@ -8397,7 +8397,7 @@ getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
 		{
 			Oid			indexOid = atooid(PQgetvalue(res, j, i_conindid));
 
-			if (indexOid != InvalidOid)
+			if (OidIsValid(indexOid))
 			{
 				for (int k = 0; k < reftable->numIndexes; k++)
 				{
@@ -10633,7 +10633,7 @@ getDefaultACLs(Archive *fout)
 		/* cheesy ... is it worth coming up with a better object name? */
 		daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
 
-		if (nspid != InvalidOid)
+		if (OidIsValid(nspid))
 			daclinfo[i].dobj.namespace = findNamespace(nspid);
 		else
 			daclinfo[i].dobj.namespace = NULL;
@@ -14005,10 +14005,10 @@ dumpTransform(Archive *fout, const TransformInfo *transform)
 	appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
 					  transformType, lanname);
 
-	if (!transform->trffromsql && !transform->trftosql)
+	if (!OidIsValid(transform->trffromsql) && !OidIsValid(transform->trftosql))
 		pg_log_warning("bogus transform definition, at least one of trffromsql and trftosql should be nonzero");
 
-	if (transform->trffromsql)
+	if (OidIsValid(transform->trffromsql))
 	{
 		if (fromsqlFuncInfo)
 		{
@@ -14026,9 +14026,9 @@ dumpTransform(Archive *fout, const TransformInfo *transform)
 			pg_log_warning("bogus value in pg_transform.trffromsql field");
 	}
 
-	if (transform->trftosql)
+	if (OidIsValid(transform->trftosql))
 	{
-		if (transform->trffromsql)
+		if (OidIsValid(transform->trffromsql))
 			appendPQExpBufferStr(defqry, ", ");
 
 		if (tosqlFuncInfo)
@@ -15738,7 +15738,7 @@ dumpTSParser(Archive *fout, const TSParserInfo *prsinfo)
 					  convertTSFunction(fout, prsinfo->prstoken));
 	appendPQExpBuffer(q, "    END = %s,\n",
 					  convertTSFunction(fout, prsinfo->prsend));
-	if (prsinfo->prsheadline != InvalidOid)
+	if (OidIsValid(prsinfo->prsheadline))
 		appendPQExpBuffer(q, "    HEADLINE = %s,\n",
 						  convertTSFunction(fout, prsinfo->prsheadline));
 	appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
@@ -15876,7 +15876,7 @@ dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo)
 	appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
 					  fmtQualifiedDumpable(tmplinfo));
 
-	if (tmplinfo->tmplinit != InvalidOid)
+	if (OidIsValid(tmplinfo->tmplinit))
 		appendPQExpBuffer(q, "    INIT = %s,\n",
 						  convertTSFunction(fout, tmplinfo->tmplinit));
 	appendPQExpBuffer(q, "    LEXIZE = %s );\n",
@@ -17788,7 +17788,7 @@ dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
 			appendStringLiteralAH(q, qualrelname, fout);
 			appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
 
-			if (tbinfo->toast_oid)
+			if (OidIsValid(tbinfo->toast_oid))
 			{
 				/*
 				 * The toast table will have the same OID at restore, so we
@@ -18361,7 +18361,7 @@ dumpIndex(Archive *fout, const IndxInfo *indxinfo)
 		 * But that's fine, and even if you think it's not, the backend won't
 		 * let us do differently.)
 		 */
-		if (indxinfo->parentidx == 0)
+		if (!OidIsValid(indxinfo->parentidx))
 			appendPQExpBuffer(delq, "DROP INDEX %s;\n", qqindxname);
 
 		if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
@@ -20357,7 +20357,7 @@ getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
 	PQExpBuffer query;
 	PGresult   *res;
 
-	if (oid == 0)
+	if (!OidIsValid(oid))
 	{
 		if ((opts & zeroAsStar) != 0)
 			return "*";
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index a31e7643cf0..ebdbffc1336 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -236,7 +236,7 @@ main(int argc, char *argv[])
 					pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 					exit(1);
 				}
-				if (set_oid == 0)
+				if (!OidIsValid(set_oid))
 					pg_fatal("OID (-o) must not be 0");
 				break;
 
@@ -456,7 +456,7 @@ main(int argc, char *argv[])
 	if (set_newest_commit_ts_xid != 0)
 		ControlFile.checkPointCopy.newestCommitTsXid = set_newest_commit_ts_xid;
 
-	if (set_oid != 0)
+	if (OidIsValid(set_oid))
 		ControlFile.checkPointCopy.nextOid = set_oid;
 
 	if (mxid_given)
@@ -829,7 +829,7 @@ PrintNewControlValues(void)
 			   ControlFile.checkPointCopy.nextMultiOffset);
 	}
 
-	if (set_oid != 0)
+	if (OidIsValid(set_oid))
 	{
 		printf(_("NextOID:                              %u\n"),
 			   ControlFile.checkPointCopy.nextOid);
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..94e1c774f6f 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -3693,7 +3693,7 @@ add_tablespace_footer(printTableContent *const cont, char relkind,
 		 * We ignore the database default tablespace so that users not using
 		 * tablespaces don't need to know about them.
 		 */
-		if (tablespace != 0)
+		if (OidIsValid(tablespace))
 		{
 			PGresult   *result = NULL;
 			PQExpBufferData buf;
diff --git a/src/bin/psql/large_obj.c b/src/bin/psql/large_obj.c
index 28f8c414b67..22032ec2c92 100644
--- a/src/bin/psql/large_obj.c
+++ b/src/bin/psql/large_obj.c
@@ -187,7 +187,7 @@ do_lo_import(const char *filename_arg, const char *comment_arg)
 	loid = lo_import(pset.db, filename_arg);
 	ResetCancelConn();
 
-	if (loid == InvalidOid)
+	if (!OidIsValid(loid))
 	{
 		pg_log_info("%s", PQerrorMessage(pset.db));
 		return fail_lo_xact("\\lo_import", own_transaction);
diff --git a/src/common/relpath.c b/src/common/relpath.c
index 7dcf987afcd..786f915a788 100644
--- a/src/common/relpath.c
+++ b/src/common/relpath.c
@@ -112,7 +112,7 @@ GetDatabasePath(Oid dbOid, Oid spcOid)
 	if (spcOid == GLOBALTABLESPACE_OID)
 	{
 		/* Shared system relations live in {datadir}/global */
-		Assert(dbOid == 0);
+		Assert(!OidIsValid(dbOid));
 		return pstrdup("global");
 	}
 	else if (spcOid == DEFAULTTABLESPACE_OID)
@@ -148,7 +148,7 @@ GetRelationPath(Oid dbOid, Oid spcOid, RelFileNumber relNumber,
 	if (spcOid == GLOBALTABLESPACE_OID)
 	{
 		/* Shared system relations live in {datadir}/global */
-		Assert(dbOid == 0);
+		Assert(!OidIsValid(dbOid));
 		Assert(procNumber == INVALID_PROC_NUMBER);
 		if (forkNumber != MAIN_FORKNUM)
 			sprintf(rp.str, "global/%u_%s",
diff --git a/src/interfaces/libpq/fe-lobj.c b/src/interfaces/libpq/fe-lobj.c
index 05e17bed508..b1c1dfbe146 100644
--- a/src/interfaces/libpq/fe-lobj.c
+++ b/src/interfaces/libpq/fe-lobj.c
@@ -139,7 +139,7 @@ lo_truncate(PGconn *conn, int fd, size_t len)
 		return -1;
 
 	/* Must check this on-the-fly because it's not there pre-8.3 */
-	if (conn->lobjfuncs->fn_lo_truncate == 0)
+	if (!OidIsValid(conn->lobjfuncs->fn_lo_truncate))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_truncate");
@@ -202,7 +202,7 @@ lo_truncate64(PGconn *conn, int fd, int64_t len)
 	if (lo_initialize(conn) < 0)
 		return -1;
 
-	if (conn->lobjfuncs->fn_lo_truncate64 == 0)
+	if (!OidIsValid(conn->lobjfuncs->fn_lo_truncate64))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_truncate64");
@@ -392,7 +392,7 @@ lo_lseek64(PGconn *conn, int fd, int64_t offset, int whence)
 	if (lo_initialize(conn) < 0)
 		return -1;
 
-	if (conn->lobjfuncs->fn_lo_lseek64 == 0)
+	if (!OidIsValid(conn->lobjfuncs->fn_lo_lseek64))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_lseek64");
@@ -482,7 +482,7 @@ lo_create(PGconn *conn, Oid lobjId)
 		return InvalidOid;
 
 	/* Must check this on-the-fly because it's not there pre-8.1 */
-	if (conn->lobjfuncs->fn_lo_create == 0)
+	if (!OidIsValid(conn->lobjfuncs->fn_lo_create))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_create");
@@ -555,7 +555,7 @@ lo_tell64(PGconn *conn, int fd)
 	if (lo_initialize(conn) < 0)
 		return -1;
 
-	if (conn->lobjfuncs->fn_lo_tell64 == 0)
+	if (!OidIsValid(conn->lobjfuncs->fn_lo_tell64))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_tell64");
@@ -674,12 +674,12 @@ lo_import_internal(PGconn *conn, const char *filename, Oid oid)
 	/*
 	 * create an inversion object
 	 */
-	if (oid == InvalidOid)
+	if (!OidIsValid(oid))
 		lobjOid = lo_creat(conn, INV_READ | INV_WRITE);
 	else
 		lobjOid = lo_create(conn, oid);
 
-	if (lobjOid == InvalidOid)
+	if (!OidIsValid(lobjOid))
 	{
 		/* we assume lo_create() already set a suitable error message */
 		(void) close(fd);
@@ -951,56 +951,56 @@ lo_initialize(PGconn *conn)
 	 * (ones that have been added later than the stone age are instead checked
 	 * only if used)
 	 */
-	if (lobjfuncs->fn_lo_open == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_open))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_open");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_close == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_close))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_close");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_creat == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_creat))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_creat");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_unlink == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_unlink))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_unlink");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_lseek == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_lseek))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_lseek");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_tell == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_tell))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lo_tell");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_read == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_read))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"loread");
 		free(lobjfuncs);
 		return -1;
 	}
-	if (lobjfuncs->fn_lo_write == 0)
+	if (!OidIsValid(lobjfuncs->fn_lo_write))
 	{
 		libpq_append_conn_error(conn, "cannot determine OID of function %s",
 								"lowrite");
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index 73ba1748fe0..f25216ddfeb 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -1270,7 +1270,7 @@ plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
 	int			i;
 
 	elemtypid = get_element_type(typid);
-	if (!elemtypid)
+	if (!OidIsValid(elemtypid))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATATYPE_MISMATCH),
 				 errmsg("cannot convert Perl array to non-array type %s",
@@ -1352,7 +1352,7 @@ plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
 		/* must call typinput in case it wants to reject NULL */
 		return InputFunctionCall(finfo, NULL, typioparam, typmod);
 	}
-	else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
+	else if (OidIsValid((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes))))
 		return OidFunctionCall1(funcid, PointerGetDatum(sv));
 	else if (SvROK(sv))
 	{
@@ -1612,7 +1612,7 @@ make_array_ref(plperl_array_info *info, int first, int last)
 		{
 			Datum		itemvalue = info->elements[i];
 
-			if (info->transform_proc.fn_oid)
+			if (OidIsValid(info->transform_proc.fn_oid))
 				av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
 			else if (info->elem_is_rowtype)
 				/* Handle composite type elements */
@@ -2195,7 +2195,7 @@ plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
 	EXTEND(sp, desc->nargs);
 
 	/* Get signature for true functions; inline blocks have no args. */
-	if (fcinfo->flinfo->fn_oid)
+	if (OidIsValid(fcinfo->flinfo->fn_oid))
 		get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
 	Assert(nargs == desc->nargs);
 
@@ -2494,7 +2494,7 @@ plperl_func_handler(PG_FUNCTION_ARGS)
 		}
 		retval = (Datum) 0;
 	}
-	else if (prodesc->result_oid)
+	else if (OidIsValid(prodesc->result_oid))
 	{
 		retval = plperl_sv_to_datum(perlret,
 									prodesc->result_oid,
@@ -3378,7 +3378,7 @@ plperl_return_next_internal(SV *sv)
 
 		tuplestore_puttuple(current_call_data->tuple_store, tuple);
 	}
-	else if (prodesc->result_oid)
+	else if (OidIsValid(prodesc->result_oid))
 	{
 		Datum		ret[1];
 		bool		isNull[1];
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index d19425b7a71..28e616cacfb 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -3083,11 +3083,11 @@ exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
 	 * coerce values of different types.  But it seems worthwhile to complain
 	 * if the array-ness of the loop variable is not right.
 	 */
-	if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
+	if (stmt->slice > 0 && !OidIsValid(loop_var_elem_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATATYPE_MISMATCH),
 				 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
-	if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
+	if (stmt->slice == 0 && OidIsValid(loop_var_elem_type))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATATYPE_MISMATCH),
 				 errmsg("FOREACH loop variable must not be of an array type")));
diff --git a/src/pl/plpython/plpy_procedure.c b/src/pl/plpython/plpy_procedure.c
index 655ab1d09ee..03567e15620 100644
--- a/src/pl/plpython/plpy_procedure.c
+++ b/src/pl/plpython/plpy_procedure.c
@@ -77,7 +77,7 @@ PLy_procedure_get(Oid fn_oid, Oid fn_rel, PLyTrigType is_trigger)
 	PLyProcedure *volatile proc = NULL;
 	bool		found = false;
 
-	if (is_trigger == PLPY_TRIGGER && fn_rel == InvalidOid)
+	if (is_trigger == PLPY_TRIGGER && !OidIsValid(fn_rel))
 		use_cache = false;
 	else
 		use_cache = true;
diff --git a/src/pl/plpython/plpy_typeio.c b/src/pl/plpython/plpy_typeio.c
index d88d10068f3..1b7882d35db 100644
--- a/src/pl/plpython/plpy_typeio.c
+++ b/src/pl/plpython/plpy_typeio.c
@@ -367,9 +367,7 @@ PLy_output_setup_func(PLyObToDatum *arg, MemoryContext arg_mcxt,
 							  typentry->typelem, typmod,
 							  proc);
 	}
-	else if ((trfuncid = get_transform_tosql(typeOid,
-											 proc->langid,
-											 proc->trftypes)))
+	else if (OidIsValid((trfuncid = get_transform_tosql(typeOid, proc->langid, proc->trftypes))))
 	{
 		arg->func = PLyObject_ToTransform;
 		fmgr_info_cxt(trfuncid, &arg->transform.typtransform, arg_mcxt);
@@ -482,9 +480,7 @@ PLy_input_setup_func(PLyDatumToOb *arg, MemoryContext arg_mcxt,
 							 typentry->typelem, typmod,
 							 proc);
 	}
-	else if ((trfuncid = get_transform_fromsql(typeOid,
-											   proc->langid,
-											   proc->trftypes)))
+	else if (OidIsValid((trfuncid = get_transform_fromsql(typeOid, proc->langid, proc->trftypes))))
 	{
 		arg->func = PLyObject_FromTransform;
 		fmgr_info_cxt(trfuncid, &arg->transform.typtransform, arg_mcxt);
diff --git a/src/test/examples/testlo.c b/src/test/examples/testlo.c
index 2277000eddb..6f53908e4bf 100644
--- a/src/test/examples/testlo.c
+++ b/src/test/examples/testlo.c
@@ -53,7 +53,7 @@ importFile(PGconn *conn, char *filename)
 	 * create the large object
 	 */
 	lobjId = lo_creat(conn, INV_READ | INV_WRITE);
-	if (lobjId == 0)
+	if (!OidIsValid(lobjId))
 		fprintf(stderr, "cannot create large object");
 
 	lobj_fd = lo_open(conn, lobjId, INV_WRITE);
@@ -245,7 +245,7 @@ main(int argc, char **argv)
 	printf("importing file \"%s\" ...\n", in_filename);
 /*	lobjOid = importFile(conn, in_filename); */
 	lobjOid = lo_import(conn, in_filename);
-	if (lobjOid == 0)
+	if (!OidIsValid(lobjOid))
 		fprintf(stderr, "%s\n", PQerrorMessage(conn));
 	else
 	{
diff --git a/src/test/examples/testlo64.c b/src/test/examples/testlo64.c
index c303db92e5b..2b8bb1fa0f7 100644
--- a/src/test/examples/testlo64.c
+++ b/src/test/examples/testlo64.c
@@ -54,7 +54,7 @@ importFile(PGconn *conn, char *filename)
 	 * create the large object
 	 */
 	lobjId = lo_creat(conn, INV_READ | INV_WRITE);
-	if (lobjId == 0)
+	if (!OidIsValid(lobjId))
 		fprintf(stderr, "cannot create large object");
 
 	lobj_fd = lo_open(conn, lobjId, INV_WRITE);
@@ -270,7 +270,7 @@ main(int argc, char **argv)
 	printf("importing file \"%s\" ...\n", in_filename);
 /*	lobjOid = importFile(conn, in_filename); */
 	lobjOid = lo_import(conn, in_filename);
-	if (lobjOid == 0)
+	if (!OidIsValid(lobjOid))
 		fprintf(stderr, "%s\n", PQerrorMessage(conn));
 	else
 	{
-- 
2.34.1

