public inbox for [email protected]  
help / color / mirror / Atom feed
Cleanup shadows variable warnings, round 1
30+ messages / 10 participants
[nested] [flat]

* Cleanup shadows variable warnings, round 1
@ 2025-11-28 08:16  Chao Li <[email protected]>
  0 siblings, 3 replies; 30+ messages in thread

From: Chao Li @ 2025-11-28 08:16 UTC (permalink / raw)
  To: Postgres hackers <[email protected]>

Hi Hackers,

While reviewing [1], it makes me recall an experience where I had a patch
ready locally, but CommitFest CI failed with a shadows-variable warning.
Now I understand that -Wall doesn't by default enable -Wshadows with some
compilers like clang.

I did a clean build with manually enabling -Wshadow and surprisingly found
there are a lot of such warnings in the current code base, roughly ~200
occurrences.

As there are too many, I plan to fix them all in 3-4 rounds. For round 1
patch, I'd see any objection, then decide if to proceed more rounds.

[1] https://postgr.es/m/CAHut+PsF8R0Bt4J3c92+T2F0mun0rRfK=-
[email protected]

Best regards,
Chao Li (Evan)
---------------------
HighGo Software Co., Ltd.
https://www.highgo.com/


Attachments:

  [application/octet-stream] v1-0001-Cleanup-shadows-variable-warnings-round-1.patch (55.0K, 3-v1-0001-Cleanup-shadows-variable-warnings-round-1.patch)
  download | inline diff:
From 38b3ca4610fae4dc222e2aa10dc5d065163722f8 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Fri, 28 Nov 2025 16:04:40 +0800
Subject: [PATCH v1] Cleanup shadows variable warnings, round 1

Author: Chao Li <[email protected]>
---
 src/backend/access/brin/brin.c              |  8 +--
 src/backend/access/gist/gistbuild.c         | 10 +--
 src/backend/access/rmgrdesc/xlogdesc.c      | 12 ++--
 src/backend/access/transam/xlogrecovery.c   | 74 ++++++++++-----------
 src/backend/backup/basebackup_incremental.c |  5 +-
 src/backend/bootstrap/bootstrap.c           |  8 +--
 src/backend/catalog/objectaddress.c         | 18 ++---
 src/backend/catalog/pg_constraint.c         | 32 ++++-----
 src/backend/commands/extension.c            |  6 +-
 src/backend/commands/schemacmds.c           |  4 +-
 src/backend/commands/statscmds.c            |  6 +-
 src/backend/commands/tablecmds.c            | 28 ++++----
 src/backend/commands/trigger.c              | 14 ++--
 src/backend/commands/wait.c                 | 12 ++--
 src/backend/executor/execExprInterp.c       |  6 +-
 src/backend/executor/nodeAgg.c              | 16 ++---
 src/backend/executor/nodeValuesscan.c       |  4 +-
 src/backend/libpq/be-secure-common.c        | 12 ++--
 src/backend/main/main.c                     | 14 ++--
 src/backend/optimizer/path/equivclass.c     | 10 +--
 src/backend/optimizer/plan/createplan.c     | 44 ++++++------
 src/backend/parser/parse_target.c           | 10 ++-
 src/backend/partitioning/partdesc.c         |  6 +-
 src/backend/statistics/dependencies.c       | 26 ++++----
 src/backend/statistics/extended_stats.c     |  8 +--
 src/backend/storage/aio/read_stream.c       | 14 ++--
 src/backend/storage/buffer/bufmgr.c         |  6 +-
 src/backend/utils/adt/date.c                | 18 ++---
 src/backend/utils/adt/datetime.c            | 20 +++---
 src/backend/utils/adt/formatting.c          |  8 +--
 src/common/controldata_utils.c              |  8 +--
 src/timezone/pgtz.c                         | 16 ++---
 32 files changed, 240 insertions(+), 243 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..7d975652ad3 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1158,7 +1158,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		i = 0;
 		foreach(lc, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
+			GISTPageSplitInfo *si = lfirst(lc);
 
 			/*
 			 * Remember the parent of each new child page in our parent map.
@@ -1169,7 +1169,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1179,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..689e05174ed 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wallevel
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int wallevel)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == wallevel)
 		{
 			wal_level_str = entry->name;
 			break;
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			wallevel;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&wallevel, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wallevel));
 	}
 }
 
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..93db9f19590 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *xlogReader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = xlogReader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(xlogReader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(xlogReader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(xlogReader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *xlogPrefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *xlogReader = XLogPrefetcherGetReader(xlogPrefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogReader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(xlogReader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(xlogPrefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(xlogReader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = xlogReader->abortedRecPtr;
+				missingContrecPtr = xlogReader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, xlogReader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(xlogReader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(xlogReader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(xlogReader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, xlogReader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, xlogReader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   xlogReader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(xlogReader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(xlogReader->EndRecPtr, replayTLI);
+				minRecoveryPoint = xlogReader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *xlogReader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) xlogReader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			xlogReader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											xlogReader->EndRecPtr,
+											xlogReader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	xlogReader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *xlogPrefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(xlogPrefetcher, RecPtr);
+	record = ReadRecord(xlogPrefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..cb96b8915ec 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -596,16 +596,15 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 			while (1)
 			{
 				unsigned	nblocks;
-				unsigned	i;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned n = 0; n < nblocks; ++n)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
-												   forknum, blocks[i]);
+												   forknum, blocks[n]);
 			}
 		}
 		DestroyBlockRefTableReader(reader);
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..83dc275d1ce 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *progName = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 progName);
 				proc_exit(1);
 				break;
 		}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", progName);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, progName))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..bbf59418f5f 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2118,8 +2118,8 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	Node	   *objnode = NULL;
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
-	Datum		values[3];
-	bool		nulls[3];
+	Datum		values3[3];
+	bool		nulls3[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2371,14 +2371,14 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
 		elog(ERROR, "return type must be a row type");
 
-	values[0] = ObjectIdGetDatum(addr.classId);
-	values[1] = ObjectIdGetDatum(addr.objectId);
-	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	values3[0] = ObjectIdGetDatum(addr.classId);
+	values3[1] = ObjectIdGetDatum(addr.objectId);
+	values3[2] = Int32GetDatum(addr.objectSubId);
+	nulls3[0] = false;
+	nulls3[1] = false;
+	nulls3[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values3, nulls3);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..ee44de9ae86 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -844,22 +844,22 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		if (cooked)
 		{
-			CookedConstraint *cooked;
-
-			cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
-
-			cooked->contype = CONSTR_NOTNULL;
-			cooked->conoid = conForm->oid;
-			cooked->name = pstrdup(NameStr(conForm->conname));
-			cooked->attnum = colnum;
-			cooked->expr = NULL;
-			cooked->is_enforced = true;
-			cooked->skip_validation = !conForm->convalidated;
-			cooked->is_local = true;
-			cooked->inhcount = 0;
-			cooked->is_no_inherit = conForm->connoinherit;
-
-			notnulls = lappend(notnulls, cooked);
+			CookedConstraint *cc;
+
+			cc = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+
+			cc->contype = CONSTR_NOTNULL;
+			cc->conoid = conForm->oid;
+			cc->name = pstrdup(NameStr(conForm->conname));
+			cc->attnum = colnum;
+			cc->expr = NULL;
+			cc->is_enforced = true;
+			cc->skip_validation = !conForm->convalidated;
+			cc->is_local = true;
+			cc->inhcount = 0;
+			cc->is_no_inherit = conForm->connoinherit;
+
+			notnulls = lappend(notnulls, cc);
 		}
 		else
 		{
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..948a939f667 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *schemaname = get_namespace_name(reqschema);
+			const char *qSchemaName = quote_identifier(schemaname);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1284,7 +1284,7 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											t_sql,
 											CStringGetTextDatum(repltoken),
 											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+			if (t_sql != old && strpbrk(schemaname, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..01a3f98275c 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -205,14 +205,14 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 */
 	foreach(parsetree_item, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
+		Node	   *pstmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = pstmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..9b113839108 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnumsbms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnumsbms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnumsbms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 23ebaa3f230..348d414a1dd 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *c = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (c->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, c->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					c->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], c);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (c->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, c->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					c->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], c);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) c->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *c = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				c->subtype = AT_ReAddDomainConstraint;
+				c->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], c);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..faf1fb4b5be 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *pqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			pqual = copyObject(whenClause);
+			pqual = (Node *)
+				map_partition_varattnos((List *) pqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			pqual = (Node *)
+				map_partition_varattnos((List *) pqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, pqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..50369c8e0d2 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		d;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &d, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			d = rint(d);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(d) || !FLOAT8_FITS_IN_INT64(d)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (d < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) d;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 0e1a74976f7..478b9be5839 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const dispatchtable[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(dispatchtable) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(dispatchtable);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..f09a29b66b4 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase phs = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!phs->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (phs->aggstrategy == AGG_PLAIN ||
+				 phs->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (phs->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		phs->evaltrans = ExecBuildAggTrans(aggstate, phs, dosort, dohash,
+										   false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		phs->evaltrans_cache[0][0] = phs->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..0d366546966 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -141,11 +141,11 @@ ValuesNext(ValuesScanState *node)
 		resind = 0;
 		foreach(lc, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
+			ExprState  *exprstate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..13f13393acc 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *progName)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 progName, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *progName)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), progName);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), progName);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *progName)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 progName);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..385179f147c 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -876,22 +876,22 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 
 		while ((i = bms_next_member(newec->ec_relids, i)) > 0)
 		{
-			RelOptInfo *rel = root->simple_rel_array[i];
+			RelOptInfo *relinfo = root->simple_rel_array[i];
 
 			/* ignore the RTE_GROUP RTE */
 			if (i == root->group_rtindex)
 				continue;
 
-			if (rel == NULL)	/* must be an outer join */
+			if (relinfo == NULL)	/* must be an outer join */
 			{
 				Assert(bms_is_member(i, root->outer_join_rels));
 				continue;
 			}
 
-			Assert(rel->reloptkind == RELOPT_BASEREL);
+			Assert(relinfo->reloptkind == RELOPT_BASEREL);
 
-			rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
-												 ec_index);
+			relinfo->eclass_indexes = bms_add_member(relinfo->eclass_indexes,
+													 ec_index);
 		}
 	}
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..4372135a8f5 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *pplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		pplan = (Plan *) make_one_row_result(tlist,
+											 (Node *) list_make1(makeBoolConst(false,
+																			   false)),
+											 best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(pplan, (Path *) best_path);
 
-		return plan;
+		return pplan;
 	}
 
 	/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *pplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		pplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		pplan = (Plan *) make_limit(pplan,
+									subparse->limitOffset,
+									subparse->limitCount,
+									subparse->limitOption,
+									0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		pplan->disabled_nodes = mminfo->path->disabled_nodes;
+		pplan->startup_cost = mminfo->path->startup_cost;
+		pplan->total_cost = mminfo->pathcost;
+		pplan->plan_rows = 1;
+		pplan->plan_width = mminfo->path->pathtarget->width;
+		pplan->parallel_aware = false;
+		pplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, pplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..6249b9e86f2 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index lvlsup = 0; lvlsup < netlevelsup; lvlsup++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index lvlsup = 0;
+						 lvlsup < rte->ctelevelsup + netlevelsup;
+						 lvlsup++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..7bed0127676 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -226,15 +226,15 @@ retry:
 		{
 			Relation	pg_class;
 			SysScanDesc scan;
-			ScanKeyData key[1];
+			ScanKeyData k[1];
 
 			pg_class = table_open(RelationRelationId, AccessShareLock);
-			ScanKeyInit(&key[0],
+			ScanKeyInit(&k[0],
 						Anum_pg_class_oid,
 						BTEqualStrategyNumber, F_OIDEQ,
 						ObjectIdGetDatum(inhrelid));
 			scan = systable_beginscan(pg_class, ClassOidIndexId, true,
-									  NULL, 1, key);
+									  NULL, 1, k);
 
 			/*
 			 * We could get one tuple from the scan (the normal case), or zero
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index 6f63b4f3ffb..5c224bd4817 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *opexpr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(opexpr->args)))
+			clause_expr = linitial(opexpr->args);
+		else if (is_pseudo_constant_clause(linitial(opexpr->args)))
+			clause_expr = lsecond(opexpr->args);
 		else
 			return false;
 
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!opexpr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(opexpr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(opexpr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 3c3d2d315c6..0d93b0af7e2 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -1041,7 +1041,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 		for (j = 0; j < numattrs; j++)
 		{
 			Datum		value;
-			bool		isnull;
+			bool		is_null;
 			int			attlen;
 			AttrNumber	attnum = attnums[j];
 
@@ -1057,7 +1057,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 			Assert(idx < data->nattnums);
 
 			value = data->values[idx][i];
-			isnull = data->nulls[idx][i];
+			is_null = data->nulls[idx][i];
 			attlen = typlen[idx];
 
 			/*
@@ -1069,7 +1069,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 			 * on the assumption that those are small (below WIDTH_THRESHOLD)
 			 * and will be discarded at the end of analyze.
 			 */
-			if ((!isnull) && (attlen == -1))
+			if ((!is_null) && (attlen == -1))
 			{
 				if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
 				{
@@ -1081,7 +1081,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 			}
 
 			items[nrows].values[j] = value;
-			items[nrows].isnull[j] = isnull;
+			items[nrows].isnull[j] = is_null;
 		}
 
 		if (toowide)
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..89408e8f428 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -961,19 +961,19 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	 */
 	if (stream->per_buffer_data)
 	{
-		void	   *per_buffer_data;
+		void	   *data;
 
-		per_buffer_data = get_per_buffer_data(stream,
-											  oldest_buffer_index == 0 ?
-											  stream->queue_size - 1 :
-											  oldest_buffer_index - 1);
+		data = get_per_buffer_data(stream,
+								   oldest_buffer_index == 0 ?
+								   stream->queue_size - 1 :
+								   oldest_buffer_index - 1);
 
 #if defined(CLOBBER_FREED_MEMORY)
 		/* This also tells Valgrind the memory is "noaccess". */
-		wipe_mem(per_buffer_data, stream->per_buffer_data_size);
+		wipe_mem(data, stream->per_buffer_data_size);
 #elif defined(USE_VALGRIND)
 		/* Tell it ourselves. */
-		VALGRIND_MAKE_MEM_NOACCESS(per_buffer_data,
+		VALGRIND_MAKE_MEM_NOACCESS(data,
 								   stream->per_buffer_data_size);
 #endif
 	}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f373cead95f..ad7d721e639 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		flag = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			flag |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flag);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 344f58b92f7..af6c1ec8dbe 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -569,16 +569,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		nday = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + nday;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((nday >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -593,13 +593,13 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		nday = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - nday;
 
 	/* Check for integer overflow and out-of-allowed-range */
 	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
@@ -3210,7 +3210,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3218,9 +3218,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3233,7 +3233,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..c54f1507b59 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			nday;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &nday) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, nday, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..7a8c7aaf742 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *nmonth;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						nmonth = rm_months_upper;
 					else
-						months = rm_months_lower;
+						nmonth = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							nmonth[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..3a9006b2116 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *tz_name)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(tz_name) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*tz_name)
+		*p++ = pg_toupper((unsigned char) *tz_name++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		tz_name[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(tz_name, sizeof(tz_name), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(tz_name, sizeof(tz_name), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(tz_name);
 }
 
 
-- 
2.39.5 (Apple Git-154)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-11-28 09:11  Heikki Linnakangas <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 1 reply; 30+ messages in thread

From: Heikki Linnakangas @ 2025-11-28 09:11 UTC (permalink / raw)
  To: Chao Li <[email protected]>; Postgres hackers <[email protected]>

On 28/11/2025 10:16, Chao Li wrote:
> Hi Hackers,
> 
> While reviewing [1], it makes me recall an experience where I had a 
> patch ready locally, but CommitFest CI failed with a shadows-variable 
> warning. Now I understand that -Wall doesn't by default enable -Wshadows 
> with some compilers like clang.
> 
> I did a clean build with manually enabling -Wshadow and 
> surprisingly found there are a lot of such warnings in the current code 
> base, roughly ~200 occurrences.
> 
> As there are too many, I plan to fix them all in 3-4 rounds. For round 1 
> patch, I'd see any objection, then decide if to proceed more rounds.

I don't know if we've agreed on a goal of getting rid of all shadowing, 
it's a lot of code churn. I agree shadowing is often confusing and 
error-prone, so maybe it's worth it.

On the patch itself:

In some of the cases, I think we should rename the global / outer-scoped 
variable instead of the local variable. For example, it's pretty insane 
that we apparently have a global variable called 'days'. :-)

Let's think a little harder about the new names. For example:

> @@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
>  			Datum		old = t_sql;
>  			char	   *reqextname = (char *) lfirst(lc);
>  			Oid			reqschema = lfirst_oid(lc2);
> -			char	   *schemaName = get_namespace_name(reqschema);
> -			const char *qSchemaName = quote_identifier(schemaName);
> +			char	   *schemaname = get_namespace_name(reqschema);
> +			const char *qSchemaName = quote_identifier(schemaname);
>  			char	   *repltoken;
>  
>  			repltoken = psprintf("@extschema:%s@", reqextname);

Having two local variables that only differ in case is also confusing. 
We're using the 'req*' prefix here for the other variables, so I think 
e.g. 'reqSchemaName' would be a good name here.

(I didn't go through the whole patch, these were just a few things that 
caught my eye at quick glance)

- Heikki






^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-11-28 13:39  Chao Li <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2025-11-28 13:39 UTC (permalink / raw)
  To: Postgres hackers <[email protected]>



> On Nov 28, 2025, at 16:16, Chao Li <[email protected]> wrote:
> 
> Hi Hackers,
> 
> While reviewing [1], it makes me recall an experience where I had a patch ready locally, but CommitFest CI failed with a shadows-variable warning. Now I understand that -Wall doesn't by default enable -Wshadows with some compilers like clang.
> 
> I did a clean build with manually enabling -Wshadow and surprisingly found there are a lot of such warnings in the current code base, roughly ~200 occurrences.
> 
> As there are too many, I plan to fix them all in 3-4 rounds. For round 1 patch, I'd see any objection, then decide if to proceed more rounds.
> 
> [1] https://postgr.es/m/CAHut+PsF8R0Bt4J3c92+T2F0mun0rRfK=-GH+iBv2s-O8ahJJw@mail.gmail.com
> 

CF entry added: https://commitfest.postgresql.org/patch/6262/

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-11-29 15:29  Peter Eisentraut <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 1 reply; 30+ messages in thread

From: Peter Eisentraut @ 2025-11-29 15:29 UTC (permalink / raw)
  To: Chao Li <[email protected]>; Postgres hackers <[email protected]>

On 28.11.25 09:16, Chao Li wrote:
> Hi Hackers,
> 
> While reviewing [1], it makes me recall an experience where I had a 
> patch ready locally, but CommitFest CI failed with a shadows-variable 
> warning. Now I understand that -Wall doesn't by default enable -Wshadows 
> with some compilers like clang.
> 
> I did a clean build with manually enabling -Wshadow and 
> surprisingly found there are a lot of such warnings in the current code 
> base, roughly ~200 occurrences.
> 
> As there are too many, I plan to fix them all in 3-4 rounds. For round 1 
> patch, I'd see any objection, then decide if to proceed more rounds.

See 
<https://www.postgresql.org/message-id/flat/20220817145434.GC26426%40telsasoft.com; 
for a previous long thread on this, which led to the addition of the 
-Wshadow=compatible-local flag.

I think this is a slightly unsatisfactory state, because that is a 
gcc-specific option, and maybe you are using clang or something else. 
So maybe some further cleanup is useful, but please check the previous 
discussions.






^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 02:28  Chao Li <[email protected]>
  parent: Peter Eisentraut <[email protected]>
  0 siblings, 3 replies; 30+ messages in thread

From: Chao Li @ 2025-12-03 02:28 UTC (permalink / raw)
  To: Peter Eisentraut <[email protected]>; +Cc: Postgres hackers <[email protected]>

Hi Peter,

On Nov 29, 2025, at 23:29, Peter Eisentraut <[email protected]> wrote:

On 28.11.25 09:16, Chao Li wrote:

Hi Hackers,
While reviewing [1], it makes me recall an experience where I had a patch
ready locally, but CommitFest CI failed with a shadows-variable warning.
Now I understand that -Wall doesn't by default enable -Wshadows with some
compilers like clang.
I did a clean build with manually enabling -Wshadow and surprisingly found
there are a lot of such warnings in the current code base, roughly ~200
occurrences.
As there are too many, I plan to fix them all in 3-4 rounds. For round 1
patch, I'd see any objection, then decide if to proceed more rounds.


See <
https://www.postgresql.org/message-id/flat/20220817145434.GC26426%40telsasoft.com;
for a previous long thread on this, which led to the addition of the
-Wshadow=compatible-local flag.


Thanks for pointing out the previous discussion. I have read through the
discussion. Looks like there was no objection on the direction of cleaning
up the shadow-variable warnings, folks were discussing how to do the
cleanup. I think my v1 patch has already taken the “saner” way as Micheal
suggested: renaming inter local variables.

I counted all warnings, there are totally 167 occurrences, seems a
manageable number. Instead of randomly splitting all fixes into several
commits as v1 did, which would really discourage reviewers and committers,
in v2, I tried to categorize all warnings to different types, and put fixes
of different types into different commits, which should make reviews a lot
easier. All commits are self-contained, each of them can be reviewed and
pushed independently.


I think this is a slightly unsatisfactory state, because that is a
gcc-specific option, and maybe you are using clang or something else. So
maybe some further cleanup is useful, but please check the previous
discussions.


I know -Wshadow=compatible-local is not supported by all compilers, some
compilers may fallback to -Wshadow and some may just ignore it. This patch
set has cleaned up all shadow-variable warnings, once the cleanup is done,
in theory, we should be able to enable -Wshadow.

0001 - simple cases of local variable shadowing local variable by changing
inner variable to for loop variable (also need to rename the for loop var)
0002 - simple cases of local variable shadowing local variable by renaming
 inner variable
0003 - simple cases of local variable shadowing local variable by renaming
outer variable. In this commit, outer local variables are used much less
than inner variables, thus renaming outer is simpler than renaming inner.
0004 -  still local shadows local, but caused by a macro definition, only
in inval.c
0005 - cases of global wal_level and wal_segment_size shadow local ones,
fixed by renaming local variables
0006 - in xlogrecovery.c, some static file-scope variables shadow local
variables, fixed by renaming local variables
0007 - cases of global progname shadows local, fixed by renaming local to
myprogname
0008 - in file_ops.c, some static file-scope variables shadow local, fixed
by renaming local variables
0009 - simple cases of local variables are shadowed by global, fixed by
renaming local variables
0010 - a few more cases of static file-scope variables shadow local
variables, fixed by renaming local variables
0011 - cases of global conn shadows local variables, fixed by renaming
local conn to myconn
0012 - fixed shadowing in ecpg.header
0013 - fixed shadowing in all time-related modules. Heikki had a concern
where there is a global named “days”, so there could be some discussions
for this commit. For now, I just renamed local variables to avoid shadowing.

With this patch set, building postgres with “-Wshadow” won’t get any
warning. Note, this patch set doesn’t cover contrib.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/


Attachments:

  [application/octet-stream] v2-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.5K, 3-v2-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From 0cddee282a08c79214fa72a21a548b73cc6256fe Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v2 05/13] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 18 +++++++++---------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 3 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..6241d87c647 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,24 +34,24 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wallevel
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int wallevel)
 {
 	const struct config_enum_entry *entry;
-	const char *wal_level_str = "?";
+	const char *wallevel_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == wallevel)
 		{
-			wal_level_str = entry->name;
+			wallevel_str = entry->name;
 			break;
 		}
 	}
 
-	return wal_level_str;
+	return wallevel_str;
 }
 
 void
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			wallevel;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&wallevel, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wallevel));
 	}
 }
 
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 9cc7488e892..0ae4e05f8f2 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 30ad46912e1..a2b8739cb96 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel wallevel)
 {
-	switch (wal_level)
+	switch (wallevel)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (2.9K, 4-v2-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
  download | inline diff:
From 0bed684defef19ea88dc64c2266cddb7166b4de0 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v2 01/13] cleanup: rename loop variables to avoid local
 shadowing

This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/backup/basebackup_incremental.c |  5 ++---
 src/backend/parser/parse_target.c           | 10 ++++------
 2 files changed, 6 insertions(+), 9 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..44f8de6fdac 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -596,16 +596,15 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 			while (1)
 			{
 				unsigned	nblocks;
-				unsigned	i;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned u = 0; u < nblocks; ++u)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
-												   forknum, blocks[i]);
+												   forknum, blocks[u]);
 			}
 		}
 		DestroyBlockRefTableReader(reader);
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..046f96d4132 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index level = 0; level < netlevelsup; level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index level = 0;
+						 level < rte->ctelevelsup + netlevelsup;
+						 level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (37.3K, 5-v2-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 81d622cb4c7e36dbb39572bf4a00947ddf823446 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v2 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 10 ++---
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  4 +-
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/subscriptioncmds.c    |  8 ++--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  4 +-
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/statistics/extended_stats.c    |  6 +--
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 24 files changed, 158 insertions(+), 156 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..7d975652ad3 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1158,7 +1158,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		i = 0;
 		foreach(lc, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
+			GISTPageSplitInfo *si = lfirst(lc);
 
 			/*
 			 * Remember the parent of each new child page in our parent map.
@@ -1169,7 +1169,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1179,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..0ef657bf919 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1283,8 +1283,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..bc8e8fb1eaa 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -205,14 +205,14 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 */
 	foreach(parsetree_item, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
+		Node	   *substmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..dc3500b8fa5 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnumsbm = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnumsbm);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnumsbm, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 24b70234b35..bb5fdc782e4 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -1122,10 +1122,10 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data,
 		 * to be at the end because otherwise if there is an error while doing
 		 * the database operations we won't be able to rollback dropped slots.
 		 */
-		foreach_ptr(SubRemoveRels, rel, sub_remove_rels)
+		foreach_ptr(SubRemoveRels, subrel, sub_remove_rels)
 		{
-			if (rel->state != SUBREL_STATE_READY &&
-				rel->state != SUBREL_STATE_SYNCDONE)
+			if (subrel->state != SUBREL_STATE_READY &&
+				subrel->state != SUBREL_STATE_SYNCDONE)
 			{
 				char		syncslotname[NAMEDATALEN] = {0};
 
@@ -1139,7 +1139,7 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data,
 				 * dropped slots and fail. For these reasons, we allow
 				 * missing_ok = true for the drop.
 				 */
-				ReplicationSlotNameForTablesync(sub->oid, rel->relid,
+				ReplicationSlotNameForTablesync(sub->oid, subrel->relid,
 												syncslotname, sizeof(syncslotname));
 				ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
 			}
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 23ebaa3f230..b2a9322c495 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..45d41adf570 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..e93d9e19de7 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..e4c539e3917 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..0d366546966 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -141,11 +141,11 @@ ValuesNext(ValuesScanState *node)
 		resind = 0;
 		foreach(lc, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
+			ExprState  *exprstate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..92e46a31898 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index 6f63b4f3ffb..5c224bd4817 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *opexpr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(opexpr->args)))
+			clause_expr = linitial(opexpr->args);
+		else if (is_pseudo_constant_clause(linitial(opexpr->args)))
+			clause_expr = lsecond(opexpr->args);
 		else
 			return false;
 
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!opexpr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(opexpr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(opexpr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 3c3d2d315c6..7df8403577c 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -991,7 +991,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1011,7 +1011,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1022,7 +1022,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f373cead95f..887c7d4d337 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 8156695e97e..4b837ff0766 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList foundJV = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &foundJV, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&foundJV);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4136,20 +4136,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc(sizeof(*var));
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index a4f8b4faa90..cfaa8f8a3b7 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 3894457ab40..84f6074f0f5 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3273,14 +3273,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4899,7 +4899,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4911,12 +4911,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..9836d872aec 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 68774a59efd..48cb5636908 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..472cd2b782b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 59a2ceee07a..941fa894910 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -200,11 +200,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 					/* pipeline status */
 				case 'P':
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -372,10 +372,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 4d97ad2ddeb..94ea4dffea3 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c3a2448dce5..24185a2602d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3999,7 +3999,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4198,9 +4198,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4217,7 +4217,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (6.4K, 6-v2-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From b2a049c0388cdb8a52911831389fdd8426479c07 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v2 03/13] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  4 ++--
 6 files changed, 18 insertions(+), 18 deletions(-)

diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..296de7647bc 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2119,7 +2119,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2374,11 +2374,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..b86f93aeb4f 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -814,7 +814,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -842,7 +842,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..d350aa8a3b0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..6fd46cf2c91 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..edc2279ead4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 46e553dce4b..785bf7b11dc 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 7-v2-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From 43ef22a0ff759c9e93a0edd1e21d9fc7e5fab29a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v2 04/13] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 06f736cab45..30bf79fb1c1 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1955,10 +1955,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 8-v2-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From acdadd47c9f8a6eb2c4230ced0c428dca0eee17f Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v2 09/13] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c     | 12 ++++-----
 src/common/controldata_utils.c           |  8 +++---
 src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 9-v2-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 1b97c1cb3fb7c051884d32287da3dd975b9b251f Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v2 06/13] cleanup: avoid local variables shadowed by static
 file-scope ones in xlogrecovery.c

This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
 1 file changed, 50 insertions(+), 50 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..903e2afe5ed 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -1991,7 +1991,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2007,10 +2007,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2018,7 +2018,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2028,8 +2028,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2079,7 +2079,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3503,18 +3503,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3526,7 +3526,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 10-v2-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From dce6fe7963108aaef4879249ac0337b4136ad36a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v2 08/13] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 55659ce201f..3867233e8a8 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.4K, 11-v2-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 41a71659672488711287f618c7b0fddf3361cc97 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v2 07/13] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 88 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  6 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 +++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 114 insertions(+), 114 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..f649c00113d 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..eeb64d09608 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 92fe2f531f7..d8e95ca2fe1 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1046,14 +1046,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2137,7 +2137,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2152,7 +2152,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2196,14 +2196,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2211,11 +2211,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2227,9 +2227,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2259,11 +2259,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2511,11 +2511,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2591,14 +2591,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 2b1fd566c35..06a97712e18 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index cc4be5d6ef4..8461143155c 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -363,32 +363,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index d55d53dbeea..a2a1bad254b 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index a00918bacb4..6b68e767434 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1649,7 +1649,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1685,7 +1685,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1708,7 +1708,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1738,7 +1738,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1812,7 +1812,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1884,7 +1884,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10870,8 +10870,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10891,16 +10891,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10913,17 +10913,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
 		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10932,7 +10932,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11388,8 +11388,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11402,21 +11402,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11466,8 +11466,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13116,8 +13116,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13131,11 +13131,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13146,14 +13146,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13162,7 +13162,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13187,8 +13187,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index c9776306c5c..5f778ec9e77 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -517,11 +517,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index e9364d04f76..4bacd9e9d34 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 3f0f10e654a..525988a2302 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 12-v2-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From a707a5a7d9b4c9795441221d42ed01f805bb5eef Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v2 10/13] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c | 6 +++---
 src/bin/pg_ctl/pg_ctl.c               | 6 +++---
 src/bin/pg_dump/pg_dumpall.c          | 6 +++---
 src/bin/pg_resetwal/pg_resetwal.c     | 6 +++---
 src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
 5 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 0e1a74976f7..0ee4322ffe1 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 4f666d91036..d2b8d83d1ca 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index bb451c1bae1..5dc06b4d2b9 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1814,20 +1814,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 8d5d9805279..5b5249537e6 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -719,15 +719,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 0060ea15902..d393b0ecfb0 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -625,10 +625,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 13-v2-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 367b67d57ae6d791298ea796c0d6cd173357911c Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v2 13/13] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/timezone/pgtz.c                | 16 +++---
 6 files changed, 97 insertions(+), 97 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..6afbfbabccb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..d8240beafc2 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..d385591b53e 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 156a4830ffd..8d545613596 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = (Interval *) palloc(sizeof(Interval));
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2521,20 +2521,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6219,7 +6219,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6242,9 +6242,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6308,7 +6308,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6321,9 +6321,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6338,7 +6338,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6599,7 +6599,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6610,9 +6610,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6625,7 +6625,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..97d55e19c13 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..a44bd230d80 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 14-v2-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From f03d8dcf3bc6efd7c030c8013ffa13c582be883a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v2 11/13] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 4 files changed, 111 insertions(+), 111 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..5a57c64dcd1 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 14ad1504678..7801623fec9 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1045,13 +1045,13 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	if (!OutputFsync(*now))
 		return false;
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1062,11 +1062,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1077,12 +1077,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..9ec1eee088b 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index e5a7cb6e5b1..342ad2cbd4f 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v2-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 15-v2-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From e72575d67fb2360ff047cd091ecc06d1e0696096 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v2 12/13] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.39.5 (Apple Git-154)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 06:42  Peter Smith <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 2 replies; 30+ messages in thread

From: Peter Smith @ 2025-12-03 06:42 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

Hi Chao.

I always build with the shadow warnings enabled, so I am happy someone
has taken up the challenge to try to clean them up. You probably found
an old thread where I tried to do the same very thing several years
ago/. I had fixed most of them in my local environment, but the thread
became stalled due to
(a) IIUC, there was some push-back about causing too much churn, and
(b) I didn't know how to break it into manageable chunks.

So I wish you better luck this time. I have just started to look at
your patches:

======

Patch v2-0001.

src/backend/backup/basebackup_incremental.c:
PrepareForIncrementalBackup:

Instead of changing the var name from 'i' to 'u', you can fix this one
by changing all the for loops to declare 'i' within the 'for ('.
That way kills two birds with one stone: it removes the shadow warning
and at the same time improves the scope of the loop variables.


-       int                     i;

-       for (i = 0; i < num_wal_ranges; ++i)
+       for (int i = 0; i < num_wal_ranges; ++i)

-       for (i = 0; i < num_wal_ranges; ++i)
+       for (int i = 0; i < num_wal_ranges; ++i)

-       unsigned        i;

-               for (i = 0; i < nblocks; ++i)
+               for (unsigned i = 0; i < nblocks; ++i)


======

I will continue to look at the rest of the patches as time permits.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 06:52  Chao Li <[email protected]>
  parent: Peter Smith <[email protected]>
  1 sibling, 1 reply; 30+ messages in thread

From: Chao Li @ 2025-12-03 06:52 UTC (permalink / raw)
  To: Peter Smith <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>



> On Dec 3, 2025, at 14:42, Peter Smith <[email protected]> wrote:
> 
> Patch v2-0001.
> 
> src/backend/backup/basebackup_incremental.c:
> PrepareForIncrementalBackup:
> 
> Instead of changing the var name from 'i' to 'u', you can fix this one
> by changing all the for loops to declare 'i' within the 'for ('.
> That way kills two birds with one stone: it removes the shadow warning
> and at the same time improves the scope of the loop variables.
> 
> 
> -       int                     i;
> 
> -       for (i = 0; i < num_wal_ranges; ++i)
> +       for (int i = 0; i < num_wal_ranges; ++i)
> 
> -       for (i = 0; i < num_wal_ranges; ++i)
> +       for (int i = 0; i < num_wal_ranges; ++i)
> 
> -       unsigned        i;
> 
> -               for (i = 0; i < nblocks; ++i)
> +               for (unsigned i = 0; i < nblocks; ++i)

Unfortunately that doesn’t work for my compiler (clang on MacOS), that’s why I renamed “I" to “u”.

By the way, Peter (S), thank you very much for reviewing.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 10:56  Chao Li <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2025-12-03 10:56 UTC (permalink / raw)
  To: Peter Eisentraut <[email protected]>; +Cc: Postgres hackers <[email protected]>

On Wed, Dec 3, 2025 at 10:28 AM Chao Li <[email protected]> wrote:

>
> 0001 - simple cases of local variable shadowing local variable by changing
> inner variable to for loop variable (also need to rename the for loop var)
> 0002 - simple cases of local variable shadowing local variable by renaming
>  inner variable
> 0003 - simple cases of local variable shadowing local variable by renaming
> outer variable. In this commit, outer local variables are used much less
> than inner variables, thus renaming outer is simpler than renaming inner.
> 0004 -  still local shadows local, but caused by a macro definition, only
> in inval.c
> 0005 - cases of global wal_level and wal_segment_size shadow local ones,
> fixed by renaming local variables
> 0006 - in xlogrecovery.c, some static file-scope variables shadow local
> variables, fixed by renaming local variables
> 0007 - cases of global progname shadows local, fixed by renaming local to
> myprogname
> 0008 - in file_ops.c, some static file-scope variables shadow local, fixed
> by renaming local variables
> 0009 - simple cases of local variables are shadowed by global, fixed by
> renaming local variables
> 0010 - a few more cases of static file-scope variables shadow local
> variables, fixed by renaming local variables
> 0011 - cases of global conn shadows local variables, fixed by renaming
> local conn to myconn
> 0012 - fixed shadowing in ecpg.header
> 0013 - fixed shadowing in all time-related modules. Heikki had a concern
> where there is a global named “days”, so there could be some discussions
> for this commit. For now, I just renamed local variables to avoid shadowing.
>
>
c252d37d8 fixed one shadow warning individually, which caused a conflict to
this patch, thus rebased to v3.

Best regards,
Chao Li (Evan)
---------------------
HighGo Software Co., Ltd.
https://www.highgo.com/


Attachments:

  [application/octet-stream] v3-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (2.9K, 3-v3-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
  download | inline diff:
From efb7eac54f959791ea777df79586f0a724ea9edf Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v3 01/13] cleanup: rename loop variables to avoid local
 shadowing

This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/backup/basebackup_incremental.c |  5 ++---
 src/backend/parser/parse_target.c           | 10 ++++------
 2 files changed, 6 insertions(+), 9 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..44f8de6fdac 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -596,16 +596,15 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 			while (1)
 			{
 				unsigned	nblocks;
-				unsigned	i;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned u = 0; u < nblocks; ++u)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
-												   forknum, blocks[i]);
+												   forknum, blocks[u]);
 			}
 		}
 		DestroyBlockRefTableReader(reader);
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..046f96d4132 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index level = 0; level < netlevelsup; level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index level = 0;
+						 level < rte->ctelevelsup + netlevelsup;
+						 level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (36.0K, 4-v3-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 49168b135728edbe0f558802e9038d6467db829c Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v3 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 10 ++---
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  4 +-
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  4 +-
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/statistics/extended_stats.c    |  6 +--
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 23 files changed, 154 insertions(+), 152 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..7d975652ad3 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1158,7 +1158,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		i = 0;
 		foreach(lc, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
+			GISTPageSplitInfo *si = lfirst(lc);
 
 			/*
 			 * Remember the parent of each new child page in our parent map.
@@ -1169,7 +1169,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1179,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..0ef657bf919 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1283,8 +1283,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..bc8e8fb1eaa 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -205,14 +205,14 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 */
 	foreach(parsetree_item, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
+		Node	   *substmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..dc3500b8fa5 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnumsbm = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnumsbm);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnumsbm, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 07e5b95782e..5173038cdf0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..45d41adf570 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..e93d9e19de7 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..e4c539e3917 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..0d366546966 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -141,11 +141,11 @@ ValuesNext(ValuesScanState *node)
 		resind = 0;
 		foreach(lc, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
+			ExprState  *exprstate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..92e46a31898 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index d7bf6b7e846..28e05d5adc0 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *opexpr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(opexpr->args)))
+			clause_expr = linitial(opexpr->args);
+		else if (is_pseudo_constant_clause(linitial(opexpr->args)))
+			clause_expr = lsecond(opexpr->args);
 		else
 			return false;
 
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!opexpr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(opexpr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(opexpr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index f003d7b4a73..ae2c82475d4 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -991,7 +991,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1011,7 +1011,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1022,7 +1022,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f373cead95f..887c7d4d337 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 8156695e97e..4b837ff0766 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList foundJV = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &foundJV, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&foundJV);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4136,20 +4136,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc(sizeof(*var));
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index a4f8b4faa90..cfaa8f8a3b7 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 3894457ab40..84f6074f0f5 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3273,14 +3273,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4899,7 +4899,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4911,12 +4911,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..9836d872aec 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 68774a59efd..48cb5636908 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..472cd2b782b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 59a2ceee07a..941fa894910 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -200,11 +200,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 					/* pipeline status */
 				case 'P':
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -372,10 +372,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 4d97ad2ddeb..94ea4dffea3 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c3a2448dce5..24185a2602d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3999,7 +3999,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4198,9 +4198,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4217,7 +4217,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (6.4K, 5-v3-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 577993ffe3636007b54f5072dc58e82dd160947a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v3 03/13] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  4 ++--
 6 files changed, 18 insertions(+), 18 deletions(-)

diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..296de7647bc 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2119,7 +2119,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2374,11 +2374,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..b86f93aeb4f 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -814,7 +814,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -842,7 +842,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..d350aa8a3b0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..6fd46cf2c91 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..edc2279ead4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 46e553dce4b..785bf7b11dc 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.5K, 6-v3-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From 15d5d809f4e663528fd97a6d71f1aee99fffd286 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v3 05/13] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 18 +++++++++---------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 3 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..6241d87c647 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,24 +34,24 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wallevel
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int wallevel)
 {
 	const struct config_enum_entry *entry;
-	const char *wal_level_str = "?";
+	const char *wallevel_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == wallevel)
 		{
-			wal_level_str = entry->name;
+			wallevel_str = entry->name;
 			break;
 		}
 	}
 
-	return wal_level_str;
+	return wallevel_str;
 }
 
 void
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			wallevel;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&wallevel, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wallevel));
 	}
 }
 
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 9cc7488e892..0ae4e05f8f2 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 30ad46912e1..a2b8739cb96 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel wallevel)
 {
-	switch (wal_level)
+	switch (wallevel)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 7-v3-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From e3510c5acf1ba51398186c700ecfe2d743d20ff3 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v3 04/13] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 06f736cab45..30bf79fb1c1 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1955,10 +1955,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 8-v3-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 78e9d85f97471b3c53b5a21f1759233c191d3012 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v3 08/13] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 55659ce201f..3867233e8a8 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 9-v3-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 6fc98a884a665e59b17be0d4e24de36ec1bca160 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v3 06/13] cleanup: avoid local variables shadowed by static
 file-scope ones in xlogrecovery.c

This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
 1 file changed, 50 insertions(+), 50 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..903e2afe5ed 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -1991,7 +1991,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2007,10 +2007,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2018,7 +2018,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2028,8 +2028,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2079,7 +2079,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3503,18 +3503,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3526,7 +3526,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 10-v3-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 6fa9e6fd42d6727a2e0aba73a677f156d4cd4808 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v3 09/13] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c     | 12 ++++-----
 src/common/controldata_utils.c           |  8 +++---
 src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.4K, 11-v3-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 260c621dfbee9e02b0933522f2c02cebe2b60ab1 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v3 07/13] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 88 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  6 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 +++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 114 insertions(+), 114 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..f649c00113d 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..eeb64d09608 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 92fe2f531f7..d8e95ca2fe1 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1046,14 +1046,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2137,7 +2137,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2152,7 +2152,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2196,14 +2196,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2211,11 +2211,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2227,9 +2227,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2259,11 +2259,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2511,11 +2511,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2591,14 +2591,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 2b1fd566c35..06a97712e18 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index cc4be5d6ef4..8461143155c 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -363,32 +363,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index d55d53dbeea..a2a1bad254b 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 2445085dbbd..bde96f272ec 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1649,7 +1649,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1685,7 +1685,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1708,7 +1708,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1738,7 +1738,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1812,7 +1812,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1884,7 +1884,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10870,8 +10870,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10891,16 +10891,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10913,17 +10913,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
 		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10932,7 +10932,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11388,8 +11388,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11402,21 +11402,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11466,8 +11466,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13116,8 +13116,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13131,11 +13131,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13146,14 +13146,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13162,7 +13162,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13187,8 +13187,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index c9776306c5c..5f778ec9e77 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -517,11 +517,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index e9364d04f76..4bacd9e9d34 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 3f0f10e654a..525988a2302 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 12-v3-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 5be1a882633994f3a4e0630feeb6d013118c6491 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v3 10/13] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c | 6 +++---
 src/bin/pg_ctl/pg_ctl.c               | 6 +++---
 src/bin/pg_dump/pg_dumpall.c          | 6 +++---
 src/bin/pg_resetwal/pg_resetwal.c     | 6 +++---
 src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
 5 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 5e7bd933afc..da8a7609d86 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 4f666d91036..d2b8d83d1ca 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index bb451c1bae1..5dc06b4d2b9 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1814,20 +1814,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 8d5d9805279..5b5249537e6 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -719,15 +719,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 0060ea15902..d393b0ecfb0 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -625,10 +625,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 13-v3-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 1eaf3daed46b0d186244c84c5023044001447f39 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v3 11/13] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 4 files changed, 111 insertions(+), 111 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..5a57c64dcd1 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 14ad1504678..7801623fec9 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1045,13 +1045,13 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	if (!OutputFsync(*now))
 		return false;
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1062,11 +1062,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1077,12 +1077,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..9ec1eee088b 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index e5a7cb6e5b1..342ad2cbd4f 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 14-v3-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 1436b628a7f3ff391281d1b770a3577a9ac32e0d Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v3 12/13] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v3-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 15-v3-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From aa27a907193ace9a1b06a825f90adbddfc8363d4 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v3 13/13] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/timezone/pgtz.c                | 16 +++---
 6 files changed, 97 insertions(+), 97 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..6afbfbabccb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..d8240beafc2 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..d385591b53e 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 2dc90a2b8a9..027711a99ca 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = (Interval *) palloc(sizeof(Interval));
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2524,20 +2524,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..97d55e19c13 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..a44bd230d80 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.39.5 (Apple Git-154)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 14:36  Álvaro Herrera <[email protected]>
  parent: Chao Li <[email protected]>
  0 siblings, 2 replies; 30+ messages in thread

From: Álvaro Herrera @ 2025-12-03 14:36 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Peter Smith <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

On 2025-Dec-03, Chao Li wrote:

> Unfortunately that doesn’t work for my compiler (clang on MacOS),
> that’s why I renamed “I" to “u”.

I think you're missing his point.  He's suggesting to change not only
this variable, but also the other uses of "i" in this function.

I'd also change "unsigned" to "unsigned int", just because I dislike
using unadorned "unsigned" as a type name (I know it's a legal type
name.)  This could be left alone, I guess -- not important.

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..322d8997400 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -270,7 +270,6 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	ListCell   *lc;
 	TimeLineHistoryEntry **tlep;
 	int			num_wal_ranges;
-	int			i;
 	bool		found_backup_start_tli = false;
 	TimeLineID	earliest_wal_range_tli = 0;
 	XLogRecPtr	earliest_wal_range_start_lsn = InvalidXLogRecPtr;
@@ -312,7 +311,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 */
 	expectedTLEs = readTimeLineHistory(backup_state->starttli);
 	tlep = palloc0(num_wal_ranges * sizeof(TimeLineHistoryEntry *));
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 		bool		saw_earliest_wal_range_tli = false;
@@ -400,7 +399,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 * anything here. However, if there's a problem staring us right in the
 	 * face, it's best to report it, so we do.
 	 */
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 
@@ -595,15 +594,14 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 
 			while (1)
 			{
-				unsigned	nblocks;
-				unsigned	i;
+				unsigned int	nblocks;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned int i = 0; i < nblocks; ++i)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
 												   forknum, blocks[i]);
 			}

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 15:17  Andres Freund <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 0 replies; 30+ messages in thread

From: Andres Freund @ 2025-12-03 15:17 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

Hi,

On 2025-12-03 10:28:36 +0800, Chao Li wrote:
> I know -Wshadow=compatible-local is not supported by all compilers, some
> compilers may fallback to -Wshadow and some may just ignore it. This patch
> set has cleaned up all shadow-variable warnings, once the cleanup is done,
> in theory, we should be able to enable -Wshadow.
> 
> 0001 - simple cases of local variable shadowing local variable by changing
> inner variable to for loop variable (also need to rename the for loop var)
> 0002 - simple cases of local variable shadowing local variable by renaming
>  inner variable
> 0003 - simple cases of local variable shadowing local variable by renaming
> outer variable. In this commit, outer local variables are used much less
> than inner variables, thus renaming outer is simpler than renaming inner.
> 0004 -  still local shadows local, but caused by a macro definition, only
> in inval.c
> 0005 - cases of global wal_level and wal_segment_size shadow local ones,
> fixed by renaming local variables
> 0006 - in xlogrecovery.c, some static file-scope variables shadow local
> variables, fixed by renaming local variables
> 0007 - cases of global progname shadows local, fixed by renaming local to
> myprogname
> 0008 - in file_ops.c, some static file-scope variables shadow local, fixed
> by renaming local variables
> 0009 - simple cases of local variables are shadowed by global, fixed by
> renaming local variables
> 0010 - a few more cases of static file-scope variables shadow local
> variables, fixed by renaming local variables
> 0011 - cases of global conn shadows local variables, fixed by renaming
> local conn to myconn
> 0012 - fixed shadowing in ecpg.header
> 0013 - fixed shadowing in all time-related modules. Heikki had a concern
> where there is a global named “days”, so there could be some discussions
> for this commit. For now, I just renamed local variables to avoid shadowing.

This seems like a *lot* of noise / backpatching pain for relatively little
gain.



> From 0cddee282a08c79214fa72a21a548b73cc6256fe Mon Sep 17 00:00:00 2001
> From: "Chao Li (Evan)" <[email protected]>
> Date: Tue, 2 Dec 2025 13:45:05 +0800
> Subject: [PATCH v2 05/13] cleanup: avoid local wal_level and wal_segment_size
>  being shadowed by globals
> 
> This commit fixes cases where local variables named wal_level and
> wal_segment_size were shadowed by global identifiers of the same names.
> The local variables are renamed so they are no longer shadowed by the
> globals.
> 
> Author: Chao Li <[email protected]>
> Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
> ---
>  src/backend/access/rmgrdesc/xlogdesc.c  | 18 +++++++++---------
>  src/backend/access/transam/xlogreader.c |  4 ++--
>  src/bin/pg_controldata/pg_controldata.c |  4 ++--
>  3 files changed, 13 insertions(+), 13 deletions(-)
> 
> diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
> index cd6c2a2f650..6241d87c647 100644
> --- a/src/backend/access/rmgrdesc/xlogdesc.c
> +++ b/src/backend/access/rmgrdesc/xlogdesc.c
> @@ -34,24 +34,24 @@ const struct config_enum_entry wal_level_options[] = {
>  };
>  
>  /*
> - * Find a string representation for wal_level
> + * Find a string representation for wallevel
>   */
>  static const char *
> -get_wal_level_string(int wal_level)
> +get_wal_level_string(int wallevel)
>  {
>  	const struct config_enum_entry *entry;
> -	const char *wal_level_str = "?";
> +	const char *wallevel_str = "?";

This sounds like it's talking about walls not, the WAL.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 21:00  Peter Smith <[email protected]>
  parent: Álvaro Herrera <[email protected]>
  1 sibling, 1 reply; 30+ messages in thread

From: Peter Smith @ 2025-12-03 21:00 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Chao Li <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

On Thu, Dec 4, 2025 at 1:36 AM Álvaro Herrera <[email protected]> wrote:
>
> On 2025-Dec-03, Chao Li wrote:
>
> > Unfortunately that doesn’t work for my compiler (clang on MacOS),
> > that’s why I renamed “I" to “u”.
>
> I think you're missing his point.  He's suggesting to change not only
> this variable, but also the other uses of "i" in this function.
>

Exactly. I should have posted the larger diff, as you did. Thanks for
clarifying.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 23:04  Chao Li <[email protected]>
  parent: Peter Smith <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2025-12-03 23:04 UTC (permalink / raw)
  To: Peter Smith <[email protected]>; +Cc: Álvaro Herrera <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>



> On Dec 4, 2025, at 05:00, Peter Smith <[email protected]> wrote:
> 
> On Thu, Dec 4, 2025 at 1:36 AM Álvaro Herrera <[email protected]> wrote:
>> 
>> On 2025-Dec-03, Chao Li wrote:
>> 
>>> Unfortunately that doesn’t work for my compiler (clang on MacOS),
>>> that’s why I renamed “I" to “u”.
>> 
>> I think you're missing his point.  He's suggesting to change not only
>> this variable, but also the other uses of "i" in this function.
>> 
> 
> Exactly. I should have posted the larger diff, as you did. Thanks for
> clarifying.
> 

Sorry for misunderstanding you. I guess I read your message too quickly yesterday. Will fix it in v4.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-03 23:24  Chao Li <[email protected]>
  parent: Álvaro Herrera <[email protected]>
  1 sibling, 1 reply; 30+ messages in thread

From: Chao Li @ 2025-12-03 23:24 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Peter Smith <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

On Wed, Dec 3, 2025 at 10:36 PM Álvaro Herrera <[email protected]> wrote:

> On 2025-Dec-03, Chao Li wrote:
>
> > Unfortunately that doesn’t work for my compiler (clang on MacOS),
> > that’s why I renamed “I" to “u”.
>
> I think you're missing his point.  He's suggesting to change not only
> this variable, but also the other uses of "i" in this function.
>
> I'd also change "unsigned" to "unsigned int", just because I dislike
> using unadorned "unsigned" as a type name (I know it's a legal type
> name.)  This could be left alone, I guess -- not important.
>
> --
> Álvaro Herrera         PostgreSQL Developer  —
> https://www.EnterpriseDB.com/


I misunderstood Peter's message yesterday. I have addressed both comments
(changing all "for" and changing "unsigned" to "unsigned int") in v4.

On Wed, Dec 3, 2025 at 11:17 PM Andres Freund <[email protected]> wrote:

>
> On 2025-12-03 10:28:36 +0800, Chao Li wrote:
> > I know -Wshadow=compatible-local is not supported by all compilers, some
> > compilers may fallback to -Wshadow and some may just ignore it. This
> patch
> > set has cleaned up all shadow-variable warnings, once the cleanup is
> done,
> > in theory, we should be able to enable -Wshadow.
> >
> > 0001 - simple cases of local variable shadowing local variable by
> changing
> > inner variable to for loop variable (also need to rename the for loop
> var)
> > 0002 - simple cases of local variable shadowing local variable by
> renaming
> >  inner variable
> > 0003 - simple cases of local variable shadowing local variable by
> renaming
> > outer variable. In this commit, outer local variables are used much less
> > than inner variables, thus renaming outer is simpler than renaming inner.
> > 0004 -  still local shadows local, but caused by a macro definition, only
> > in inval.c
> > 0005 - cases of global wal_level and wal_segment_size shadow local ones,
> > fixed by renaming local variables
> > 0006 - in xlogrecovery.c, some static file-scope variables shadow local
> > variables, fixed by renaming local variables
> > 0007 - cases of global progname shadows local, fixed by renaming local to
> > myprogname
> > 0008 - in file_ops.c, some static file-scope variables shadow local,
> fixed
> > by renaming local variables
> > 0009 - simple cases of local variables are shadowed by global, fixed by
> > renaming local variables
> > 0010 - a few more cases of static file-scope variables shadow local
> > variables, fixed by renaming local variables
> > 0011 - cases of global conn shadows local variables, fixed by renaming
> > local conn to myconn
> > 0012 - fixed shadowing in ecpg.header
> > 0013 - fixed shadowing in all time-related modules. Heikki had a concern
> > where there is a global named “days”, so there could be some discussions
> > for this commit. For now, I just renamed local variables to avoid
> shadowing.
>
> This seems like a *lot* of noise / backpatching pain for relatively little
> gain.
>

 I agree the patch set is large, which is why I split it into smaller
commits, each independent and self-contained.

The motivation is that CF’s CI currently fails on shadow-variable warnings.
If you touch a file like a.c, and that file already has a legacy shadowing
issue, CI will still fail your patch even if your changes are correct. Then
you’re forced to fix unrelated shadow-variable problems just to get a clean
CI run. I’ve run into this myself, and it’s disruptive for both patch
authors and reviewers.

By cleaning up all existing shadow-variable warnings now, they won’t
interfere with future patches, and it also allows us to enable -Wshadow by
default so new shadowing issues won’t be introduced.


On Wed, Dec 3, 2025 at 11:17 PM Andres Freund <[email protected]> wrote:

>
> >  /*
> > - * Find a string representation for wal_level
> > + * Find a string representation for wallevel
> >   */
> >  static const char *
> > -get_wal_level_string(int wal_level)
> > +get_wal_level_string(int wallevel)
> >  {
> >       const struct config_enum_entry *entry;
> > -     const char *wal_level_str = "?";
> > +     const char *wallevel_str = "?";
>
> This sounds like it's talking about walls not, the WAL.
>
>
Fixed in v4.

V4 addressed all comments received so far, and fixed a mistake that caused
CI failure.

Best regards,

Chao Li (Evan)
---------------------
HighGo Software Co., Ltd.
https://www.highgo.com/


Attachments:

  [application/octet-stream] v4-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (4.1K, 3-v4-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
  download | inline diff:
From 8ac41ad94b8feb57eed17970aa4010049a4f7d67 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v4 01/13] cleanup: rename loop variables to avoid local
 shadowing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/backup/basebackup_incremental.c | 10 ++++------
 src/backend/parser/parse_target.c           | 10 ++++------
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..844d7319c82 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -270,7 +270,6 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	ListCell   *lc;
 	TimeLineHistoryEntry **tlep;
 	int			num_wal_ranges;
-	int			i;
 	bool		found_backup_start_tli = false;
 	TimeLineID	earliest_wal_range_tli = 0;
 	XLogRecPtr	earliest_wal_range_start_lsn = InvalidXLogRecPtr;
@@ -312,7 +311,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 */
 	expectedTLEs = readTimeLineHistory(backup_state->starttli);
 	tlep = palloc0(num_wal_ranges * sizeof(TimeLineHistoryEntry *));
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 		bool		saw_earliest_wal_range_tli = false;
@@ -400,7 +399,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 * anything here. However, if there's a problem staring us right in the
 	 * face, it's best to report it, so we do.
 	 */
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 
@@ -595,15 +594,14 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 
 			while (1)
 			{
-				unsigned	nblocks;
-				unsigned	i;
+				unsigned int nblocks;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned int i = 0; i < nblocks; ++i)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
 												   forknum, blocks[i]);
 			}
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..046f96d4132 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index level = 0; level < netlevelsup; level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index level = 0;
+						 level < rte->ctelevelsup + netlevelsup;
+						 level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 4-v4-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From 714f5178e4af179cf7e1edb4aea5771cb7d4bab2 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v4 04/13] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 06f736cab45..30bf79fb1c1 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1955,10 +1955,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (6.4K, 5-v4-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 511c222fc7b2ef73bc58eb403f03fb386d44f56d Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v4 03/13] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  4 ++--
 6 files changed, 18 insertions(+), 18 deletions(-)

diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..296de7647bc 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2119,7 +2119,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2374,11 +2374,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..b86f93aeb4f 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -814,7 +814,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -842,7 +842,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..d350aa8a3b0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..6fd46cf2c91 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..edc2279ead4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 46e553dce4b..785bf7b11dc 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (36.0K, 6-v4-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 9fe96f2babd0268c8aea6da7b6882bd113cec7c9 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v4 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 10 ++---
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  4 +-
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  4 +-
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/statistics/extended_stats.c    |  6 +--
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 23 files changed, 154 insertions(+), 152 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..7d975652ad3 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1158,7 +1158,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		i = 0;
 		foreach(lc, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
+			GISTPageSplitInfo *si = lfirst(lc);
 
 			/*
 			 * Remember the parent of each new child page in our parent map.
@@ -1169,7 +1169,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1179,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..0ef657bf919 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1283,8 +1283,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..bc8e8fb1eaa 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -205,14 +205,14 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 */
 	foreach(parsetree_item, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
+		Node	   *substmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..dc3500b8fa5 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnumsbm = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnumsbm);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnumsbm, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 07e5b95782e..5173038cdf0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..45d41adf570 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..e93d9e19de7 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..e4c539e3917 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..0d366546966 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -141,11 +141,11 @@ ValuesNext(ValuesScanState *node)
 		resind = 0;
 		foreach(lc, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
+			ExprState  *exprstate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..92e46a31898 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index d7bf6b7e846..28e05d5adc0 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *opexpr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(opexpr->args)))
+			clause_expr = linitial(opexpr->args);
+		else if (is_pseudo_constant_clause(linitial(opexpr->args)))
+			clause_expr = lsecond(opexpr->args);
 		else
 			return false;
 
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!opexpr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(opexpr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(opexpr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(opexpr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(opexpr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index f003d7b4a73..ae2c82475d4 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -991,7 +991,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1011,7 +1011,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1022,7 +1022,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f373cead95f..887c7d4d337 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 8156695e97e..4b837ff0766 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList foundJV = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &foundJV, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&foundJV);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4136,20 +4136,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc(sizeof(*var));
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index a4f8b4faa90..cfaa8f8a3b7 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 3894457ab40..84f6074f0f5 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3273,14 +3273,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4899,7 +4899,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4911,12 +4911,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..9836d872aec 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 68774a59efd..48cb5636908 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..472cd2b782b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 59a2ceee07a..941fa894910 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -200,11 +200,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 					/* pipeline status */
 				case 'P':
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -372,10 +372,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 4d97ad2ddeb..94ea4dffea3 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c3a2448dce5..24185a2602d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3999,7 +3999,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4198,9 +4198,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4217,7 +4217,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.3K, 7-v4-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From 3e024391ab366ea890a2f28b7aba66ee5de9c06a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v4 05/13] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 12 ++++++------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 3 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..bf6a120af68 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == level)
 		{
 			wal_level_str = entry->name;
 			break;
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			level;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&level, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(level));
 	}
 }
 
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 9cc7488e892..0ae4e05f8f2 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 30ad46912e1..8cb56f12146 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 8-v4-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From d2e5e401831867a6a184f00c88bd569aef63a6e1 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v4 08/13] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 55659ce201f..3867233e8a8 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 9-v4-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 66cdc67b20b2c92fc7ef851e4ba01d76d2d193fe Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v4 10/13] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c | 6 +++---
 src/bin/pg_ctl/pg_ctl.c               | 6 +++---
 src/bin/pg_dump/pg_dumpall.c          | 6 +++---
 src/bin/pg_resetwal/pg_resetwal.c     | 6 +++---
 src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
 5 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 5e7bd933afc..da8a7609d86 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 4f666d91036..d2b8d83d1ca 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index bb451c1bae1..5dc06b4d2b9 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1814,20 +1814,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 8d5d9805279..5b5249537e6 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -719,15 +719,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 0060ea15902..d393b0ecfb0 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -625,10 +625,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.5K, 10-v4-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 32d1df734aaf251416e83f9f8aad958ad13fca05 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v4 07/13] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 90 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  6 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 ++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 115 insertions(+), 115 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..f649c00113d 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..eeb64d09608 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 92fe2f531f7..d8e95ca2fe1 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1046,14 +1046,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2137,7 +2137,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2152,7 +2152,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2196,14 +2196,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2211,11 +2211,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2227,9 +2227,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2259,11 +2259,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2511,11 +2511,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2591,14 +2591,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 2b1fd566c35..06a97712e18 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 43dc6ff7693..04210e60bca 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -363,32 +363,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index d55d53dbeea..a2a1bad254b 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 2445085dbbd..d2b54916a0e 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1649,7 +1649,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1685,7 +1685,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1708,7 +1708,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1738,7 +1738,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1812,7 +1812,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1884,7 +1884,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10870,8 +10870,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10891,16 +10891,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10913,17 +10913,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
-		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+		else if (strcmp(comment_items->descr, initdb_comment) == 0)
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10932,7 +10932,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11388,8 +11388,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11402,21 +11402,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11466,8 +11466,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13116,8 +13116,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13131,11 +13131,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13146,14 +13146,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13162,7 +13162,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13187,8 +13187,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index c9776306c5c..5f778ec9e77 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -517,11 +517,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index e9364d04f76..4bacd9e9d34 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 3f0f10e654a..525988a2302 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 11-v4-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 37dde5b77786e6ebd7883dff2a79efb3af8392ab Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v4 06/13] cleanup: avoid local variables shadowed by static
 file-scope ones in xlogrecovery.c

This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
 1 file changed, 50 insertions(+), 50 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..903e2afe5ed 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -1991,7 +1991,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2007,10 +2007,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2018,7 +2018,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2028,8 +2028,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2079,7 +2079,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3503,18 +3503,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3526,7 +3526,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 12-v4-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 1a8ebf5384398a32ee3c7a67f48ffc2fa21454e8 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v4 09/13] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c     | 12 ++++-----
 src/common/controldata_utils.c           |  8 +++---
 src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 13-v4-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 5a897eb7a96df958c5de4c4567dea6ad69b37894 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v4 13/13] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/timezone/pgtz.c                | 16 +++---
 6 files changed, 97 insertions(+), 97 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..6afbfbabccb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..d8240beafc2 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..d385591b53e 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 2dc90a2b8a9..027711a99ca 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = (Interval *) palloc(sizeof(Interval));
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2524,20 +2524,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..97d55e19c13 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..a44bd230d80 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 14-v4-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 4d911f497f6596a73664216d4ca59145432493c3 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v4 12/13] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v4-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 15-v4-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 7c7f53340bec5147a7b0e896c2ee649c73c75206 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v4 11/13] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 4 files changed, 111 insertions(+), 111 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..5a57c64dcd1 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 14ad1504678..7801623fec9 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1045,13 +1045,13 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	if (!OutputFsync(*now))
 		return false;
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1062,11 +1062,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1077,12 +1077,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..9ec1eee088b 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index e5a7cb6e5b1..342ad2cbd4f 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
-- 
2.39.5 (Apple Git-154)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-04 00:56  Michael Paquier <[email protected]>
  parent: Heikki Linnakangas <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Michael Paquier @ 2025-12-04 00:56 UTC (permalink / raw)
  To: Heikki Linnakangas <[email protected]>; +Cc: Chao Li <[email protected]>; Postgres hackers <[email protected]>

On Fri, Nov 28, 2025 at 11:11:04AM +0200, Heikki Linnakangas wrote:
> I don't know if we've agreed on a goal of getting rid of all shadowing, it's
> a lot of code churn. I agree shadowing is often confusing and error-prone,
> so maybe it's worth it.

(Providing my own context with more information on the matter, Peter
E. mentioning this commit upthread.)

As far as I know, the latest consensus with shadow variables was that
-Wshadow=compatible-local was OK for now, 0fe954c28584 mentioning that
we could consider a tighter -Wshadow=local later on.  I don't recall a
clear objection about doing a tighter move, just that it was a lot of
work for unclear gains especially when it comes to the extra
backpatching noise.
--
Michael


Attachments:

  [application/pgp-signature] signature.asc (833B, 2-signature.asc)
  download

^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-04 01:08  Peter Smith <[email protected]>
  parent: Peter Smith <[email protected]>
  1 sibling, 1 reply; 30+ messages in thread

From: Peter Smith @ 2025-12-04 01:08 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

FWIW... A few more review comments for v3.

//////////
Patch v3-0001.
//////////

======
src/backend/access/gist/gistbuild.c

2.1.
OK, but should you take it 1 step further?

BEFORE
foreach(lc, splitinfo)
{
  GISTPageSplitInfo *si = lfirst(lc);
AFTER
foreach_ptr(GISTPageSplitInfo, si, splitinfo)
{

======
src/backend/commands/schemacmds.c

2.2.
OK, but should you take it 1 step further?

BEFORE
foreach(parsetree_item, parsetree_list)
{
  Node    *substmt = (Node *) lfirst(parsetree_item);
AFTER
foreach_ptr(Node, substmt, parsetree_list)
{

======
src/backend/commands/statscmds.c

2.3.
OK, but I felt 'attnums_bms' might be a better replacement name than 'attnumsbm'

======
src/backend/executor/nodeValuesscan.c

2.4.
OK, but should you take it 1 step further?

BEFORE
foreach(lc, exprstatelist)
{
  ExprState  *exprstate = (ExprState *) lfirst(lc);
AFTER
foreach_ptr(ExprState, exprstate, exprstatelist)
{

======
src/backend/statistics/dependencies.c

2.5.
The other variable in other parts of this function had names like:
clause_expr
bool_expr
or_expr
stat_expr

So, perhaps your new names should be changed slightly to look more
similar to those?

======
src/backend/statistics/extended_stats.c

2.6.
This seems to be in the wrong patch because here you renamed the local
var, not the inner one, as the patch commit message says.

======
src/backend/utils/adt/jsonpath_exec.c

2.7.
Wondering if 'vals' might be a better name than 'foundJV' (there is
already another JsonValueList vals elsewhere in this code).

======
src/bin/pgbench/pgbench.c

2.8.
Wondering if 'nskipped' is a better name than 'skips'.

//////////
Patch v3-0003
//////////

LGTM.

======
Kind Regards,
Peter Smith.
Fujitsu Australia





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-04 09:10  Chao Li <[email protected]>
  parent: Peter Smith <[email protected]>
  0 siblings, 1 reply; 30+ messages in thread

From: Chao Li @ 2025-12-04 09:10 UTC (permalink / raw)
  To: Peter Smith <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

On Dec 4, 2025, at 09:08, Peter Smith <[email protected]> wrote:

FWIW... A few more review comments for v3.

//////////
Patch v3-0001.
//////////


This is actually 0002.


======
src/backend/access/gist/gistbuild.c

2.1.
OK, but should you take it 1 step further?

BEFORE
foreach(lc, splitinfo)
{
 GISTPageSplitInfo *si = lfirst(lc);
AFTER
foreach_ptr(GISTPageSplitInfo, si, splitinfo)
{

======
src/backend/commands/schemacmds.c


Fixed.

2.2.
OK, but should you take it 1 step further?

BEFORE
foreach(parsetree_item, parsetree_list)
{
 Node    *substmt = (Node *) lfirst(parsetree_item);
AFTER
foreach_ptr(Node, substmt, parsetree_list)
{


Fixed.

======
src/backend/commands/statscmds.c

2.3.
OK, but I felt 'attnums_bms' might be a better replacement name than
'attnumsbm'


Fixed.

======
src/backend/executor/nodeValuesscan.c

2.4.
OK, but should you take it 1 step further?

BEFORE
foreach(lc, exprstatelist)
{
 ExprState  *exprstate = (ExprState *) lfirst(lc);
AFTER
foreach_ptr(ExprState, exprstate, exprstatelist)
{


Fixed.

======
src/backend/statistics/dependencies.c

2.5.
The other variable in other parts of this function had names like:
clause_expr
bool_expr
or_expr
stat_expr

So, perhaps your new names should be changed slightly to look more
similar to those?


Fixed.

======
src/backend/statistics/extended_stats.c

2.6.
This seems to be in the wrong patch because here you renamed the local
var, not the inner one, as the patch commit message says.


Moved to 0003.

======
src/backend/utils/adt/jsonpath_exec.c

2.7.
Wondering if 'vals' might be a better name than 'foundJV' (there is
already another JsonValueList vals elsewhere in this code).


Fixed.

======
src/bin/pgbench/pgbench.c

2.8.
Wondering if 'nskipped' is a better name than 'skips'.


The around variables all use “s”:
```
int64 skips = 0;
int64 serialization_failures = 0;
int64 deadlock_failures = 0;
int64 other_sql_failures = 0;
int64 retried = 0;
int64 retries = 0;
```

That’s why I used the “s” form.

All fixes are in v5.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/


Attachments:

  [application/octet-stream] v5-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (7.5K, 3-v5-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 122918b57655cc16a51047ff4937a5e2e2bf943b Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v5 03/13] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/statistics/extended_stats.c |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  4 ++--
 7 files changed, 21 insertions(+), 21 deletions(-)

diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..296de7647bc 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2119,7 +2119,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2374,11 +2374,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..b86f93aeb4f 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -814,7 +814,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -842,7 +842,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..d350aa8a3b0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..6fd46cf2c91 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index f003d7b4a73..ae2c82475d4 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -991,7 +991,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1011,7 +1011,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1022,7 +1022,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..edc2279ead4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 46e553dce4b..785bf7b11dc 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 4-v5-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From a08ee8ce1112cd64313e85d95eaab693eaa23da2 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v5 04/13] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 06f736cab45..30bf79fb1c1 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1955,10 +1955,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.3K, 5-v5-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From aae008a7e90d37f70056ca1e88972a5ad4764424 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v5 05/13] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 12 ++++++------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 3 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..bf6a120af68 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == level)
 		{
 			wal_level_str = entry->name;
 			break;
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			level;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&level, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(level));
 	}
 }
 
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 9cc7488e892..0ae4e05f8f2 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 30ad46912e1..8cb56f12146 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (36.0K, 6-v5-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 31b4881011c9c1d2c29f8006c657068a77355d56 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v5 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 13 +++----
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  6 +--
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  6 +--
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 22 files changed, 151 insertions(+), 156 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..1385d08ae4d 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1129,7 +1129,6 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		int			ndownlinks,
 					i;
 		Buffer		parentBuffer;
-		ListCell   *lc;
 
 		/* Parent may have changed since we memorized this path. */
 		parentBuffer =
@@ -1156,10 +1155,8 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		ndownlinks = list_length(splitinfo);
 		downlinks = (IndexTuple *) palloc(sizeof(IndexTuple) * ndownlinks);
 		i = 0;
-		foreach(lc, splitinfo)
+		foreach_ptr(GISTPageSplitInfo, si, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
-
 			/*
 			 * Remember the parent of each new child page in our parent map.
 			 * This assumes that the downlinks fit on the parent page. If the
@@ -1169,7 +1166,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1176,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..0ef657bf919 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1283,8 +1283,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..313b1eaf018 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -55,7 +55,6 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	const char *schemaName = stmt->schemaname;
 	Oid			namespaceId;
 	List	   *parsetree_list;
-	ListCell   *parsetree_item;
 	Oid			owner_uid;
 	Oid			saved_uid;
 	int			save_sec_context;
@@ -203,16 +202,15 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 * them through parse_analyze_*() or the rewriter; we can just hand them
 	 * straight to ProcessUtility.
 	 */
-	foreach(parsetree_item, parsetree_list)
+	foreach_ptr(Node, substmt, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..f1fd0f67aa1 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnums_bms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnums_bms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnums_bms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 07e5b95782e..5173038cdf0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..45d41adf570 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..e93d9e19de7 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..e4c539e3917 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..025b84c8331 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -90,7 +90,6 @@ ValuesNext(ValuesScanState *node)
 		MemoryContext oldContext;
 		Datum	   *values;
 		bool	   *isnull;
-		ListCell   *lc;
 		int			resind;
 
 		/*
@@ -139,13 +138,12 @@ ValuesNext(ValuesScanState *node)
 		isnull = slot->tts_isnull;
 
 		resind = 0;
-		foreach(lc, exprstatelist)
+		foreach_ptr(ExprState, exprstate, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..92e46a31898 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index d7bf6b7e846..00c462621bb 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *op_expr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(op_expr->args)))
+			clause_expr = linitial(op_expr->args);
+		else if (is_pseudo_constant_clause(linitial(op_expr->args)))
+			clause_expr = lsecond(op_expr->args);
 		else
 			return false;
 
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *op_expr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!op_expr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(op_expr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(op_expr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 62f420dd344..23ea6e7dda7 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 8156695e97e..1eabf6e68de 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList vals = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &vals, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&vals);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4136,20 +4136,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc(sizeof(*var));
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index a4f8b4faa90..cfaa8f8a3b7 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 3894457ab40..84f6074f0f5 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3273,14 +3273,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4899,7 +4899,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4911,12 +4911,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..9836d872aec 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 68774a59efd..48cb5636908 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..472cd2b782b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 59a2ceee07a..941fa894910 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -200,11 +200,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 					/* pipeline status */
 				case 'P':
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -372,10 +372,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 4d97ad2ddeb..94ea4dffea3 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c3a2448dce5..24185a2602d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3999,7 +3999,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4198,9 +4198,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4217,7 +4217,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (4.1K, 7-v5-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
  download | inline diff:
From 7a6b8a5b21dafa5516418cd6d09846a89fd76476 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v5 01/13] cleanup: rename loop variables to avoid local
 shadowing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/backup/basebackup_incremental.c | 10 ++++------
 src/backend/parser/parse_target.c           | 10 ++++------
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..844d7319c82 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -270,7 +270,6 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	ListCell   *lc;
 	TimeLineHistoryEntry **tlep;
 	int			num_wal_ranges;
-	int			i;
 	bool		found_backup_start_tli = false;
 	TimeLineID	earliest_wal_range_tli = 0;
 	XLogRecPtr	earliest_wal_range_start_lsn = InvalidXLogRecPtr;
@@ -312,7 +311,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 */
 	expectedTLEs = readTimeLineHistory(backup_state->starttli);
 	tlep = palloc0(num_wal_ranges * sizeof(TimeLineHistoryEntry *));
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 		bool		saw_earliest_wal_range_tli = false;
@@ -400,7 +399,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 * anything here. However, if there's a problem staring us right in the
 	 * face, it's best to report it, so we do.
 	 */
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 
@@ -595,15 +594,14 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 
 			while (1)
 			{
-				unsigned	nblocks;
-				unsigned	i;
+				unsigned int nblocks;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned int i = 0; i < nblocks; ++i)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
 												   forknum, blocks[i]);
 			}
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..046f96d4132 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index level = 0; level < netlevelsup; level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index level = 0;
+						 level < rte->ctelevelsup + netlevelsup;
+						 level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.5K, 8-v5-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 322272db4bb9e991035cd8980c6d2a495c2166e1 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v5 07/13] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 90 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  6 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 ++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 115 insertions(+), 115 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..f649c00113d 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..eeb64d09608 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 92fe2f531f7..d8e95ca2fe1 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1046,14 +1046,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2137,7 +2137,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2152,7 +2152,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2196,14 +2196,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2211,11 +2211,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2227,9 +2227,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2259,11 +2259,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2511,11 +2511,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2591,14 +2591,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 2b1fd566c35..06a97712e18 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 43dc6ff7693..04210e60bca 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -363,32 +363,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index d55d53dbeea..a2a1bad254b 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 2445085dbbd..d2b54916a0e 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1649,7 +1649,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1685,7 +1685,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1708,7 +1708,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1738,7 +1738,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1812,7 +1812,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1884,7 +1884,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10870,8 +10870,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10891,16 +10891,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10913,17 +10913,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
-		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+		else if (strcmp(comment_items->descr, initdb_comment) == 0)
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10932,7 +10932,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11388,8 +11388,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11402,21 +11402,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11466,8 +11466,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13116,8 +13116,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13131,11 +13131,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13146,14 +13146,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13162,7 +13162,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13187,8 +13187,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index c9776306c5c..5f778ec9e77 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -517,11 +517,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index e9364d04f76..4bacd9e9d34 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 3f0f10e654a..525988a2302 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 9-v5-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 80008e8cf176a4b2dd0f358cba8943a2993560f8 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v5 06/13] cleanup: avoid local variables shadowed by static
 file-scope ones in xlogrecovery.c

This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
 1 file changed, 50 insertions(+), 50 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..903e2afe5ed 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -1991,7 +1991,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2007,10 +2007,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2018,7 +2018,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2028,8 +2028,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2079,7 +2079,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3503,18 +3503,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3526,7 +3526,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 10-v5-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 095edfd074798786f29d3b9c2af9d6494b2c2c46 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v5 10/13] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c | 6 +++---
 src/bin/pg_ctl/pg_ctl.c               | 6 +++---
 src/bin/pg_dump/pg_dumpall.c          | 6 +++---
 src/bin/pg_resetwal/pg_resetwal.c     | 6 +++---
 src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
 5 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 5e7bd933afc..da8a7609d86 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 4f666d91036..d2b8d83d1ca 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index bb451c1bae1..5dc06b4d2b9 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1814,20 +1814,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 8d5d9805279..5b5249537e6 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -719,15 +719,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 0060ea15902..d393b0ecfb0 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -625,10 +625,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 11-v5-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 108be15a7c2b7a216a82f9dffb11725e8360cfd4 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v5 08/13] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 55659ce201f..3867233e8a8 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 12-v5-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 1beb3b30a4b0fce2941044716b3756dc2319da82 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v5 09/13] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c     | 12 ++++-----
 src/common/controldata_utils.c           |  8 +++---
 src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 13-v5-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 0e15be4955b528f3d763109f4ac33aa9ff3b5d16 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v5 11/13] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 4 files changed, 111 insertions(+), 111 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..5a57c64dcd1 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 14ad1504678..7801623fec9 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1045,13 +1045,13 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	if (!OutputFsync(*now))
 		return false;
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1062,11 +1062,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1077,12 +1077,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..9ec1eee088b 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index e5a7cb6e5b1..342ad2cbd4f 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 14-v5-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From ce207a20c3c3159baf2d3988f66609014b36b63c Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v5 12/13] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.39.5 (Apple Git-154)



  [application/octet-stream] v5-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 15-v5-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From c9154040dbd27e5c9e7d7e4b685425ec1f883643 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v5 13/13] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/timezone/pgtz.c                | 16 +++---
 6 files changed, 97 insertions(+), 97 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..6afbfbabccb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..d8240beafc2 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..d385591b53e 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 2dc90a2b8a9..027711a99ca 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = (Interval *) palloc(sizeof(Interval));
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2524,20 +2524,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..97d55e19c13 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..a44bd230d80 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.39.5 (Apple Git-154)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-04 11:21  Álvaro Herrera <[email protected]>
  parent: Chao Li <[email protected]>
  0 siblings, 1 reply; 30+ messages in thread

From: Álvaro Herrera @ 2025-12-04 11:21 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Peter Smith <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

On 2025-Dec-04, Chao Li wrote:

> The motivation is that CF’s CI currently fails on shadow-variable warnings.
> If you touch a file like a.c, and that file already has a legacy shadowing
> issue, CI will still fail your patch even if your changes are correct. Then
> you’re forced to fix unrelated shadow-variable problems just to get a clean
> CI run. I’ve run into this myself, and it’s disruptive for both patch
> authors and reviewers.

Hmm, maybe that should be turned off.  It sounds seriously unhelpful.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"En las profundidades de nuestro inconsciente hay una obsesiva necesidad
de un universo lógico y coherente. Pero el universo real se halla siempre
un paso más allá de la lógica" (Irulan)





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2025-12-04 13:04  Bilal Yavuz <[email protected]>
  parent: Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Bilal Yavuz @ 2025-12-04 13:04 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Chao Li <[email protected]>; Peter Smith <[email protected]>; Peter Eisentraut <[email protected]>; Postgres hackers <[email protected]>

Hi,

On Thu, 4 Dec 2025 at 14:21, Álvaro Herrera <[email protected]> wrote:
>
> On 2025-Dec-04, Chao Li wrote:
>
> > The motivation is that CF’s CI currently fails on shadow-variable warnings.
> > If you touch a file like a.c, and that file already has a legacy shadowing
> > issue, CI will still fail your patch even if your changes are correct. Then
> > you’re forced to fix unrelated shadow-variable problems just to get a clean
> > CI run. I’ve run into this myself, and it’s disruptive for both patch
> > authors and reviewers.
>
> Hmm, maybe that should be turned off.  It sounds seriously unhelpful.

To test that I created this CI run [1], which edits the brin.c file.
That file has a legacy shadowing issue but the CI did not fail. Could
you please show an example CI run?

[1] https://cirrus-ci.com/build/5444936843132928

--
Regards,
Nazir Bilal Yavuz
Microsoft





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-03-03 09:04  Chao Li <[email protected]>
  parent: Chao Li <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2026-03-03 09:04 UTC (permalink / raw)
  To: Postgres hackers <[email protected]>; +Cc: Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Dec 4, 2025, at 17:10, Chao Li <[email protected]> wrote:
> 
> 
> 
>> On Dec 4, 2025, at 09:08, Peter Smith <[email protected]> wrote:
>> 
>> FWIW... A few more review comments for v3.
>> 
>> //////////
>> Patch v3-0001.
>> //////////
> 
> This is actually 0002.
> 
>> 
>> ======
>> src/backend/access/gist/gistbuild.c
>> 
>> 2.1.
>> OK, but should you take it 1 step further?
>> 
>> BEFORE
>> foreach(lc, splitinfo)
>> {
>>  GISTPageSplitInfo *si = lfirst(lc);
>> AFTER
>> foreach_ptr(GISTPageSplitInfo, si, splitinfo)
>> {
>> 
>> ======
>> src/backend/commands/schemacmds.c
>> 
> 
> Fixed.
> 
>> 2.2.
>> OK, but should you take it 1 step further?
>> 
>> BEFORE
>> foreach(parsetree_item, parsetree_list)
>> {
>>  Node    *substmt = (Node *) lfirst(parsetree_item);
>> AFTER
>> foreach_ptr(Node, substmt, parsetree_list)
>> {
>> 
> 
> Fixed.
> 
>> ======
>> src/backend/commands/statscmds.c
>> 
>> 2.3.
>> OK, but I felt 'attnums_bms' might be a better replacement name than 'attnumsbm'
>> 
> 
> Fixed.
> 
>> ======
>> src/backend/executor/nodeValuesscan.c
>> 2.4.
>> OK, but should you take it 1 step further?
>> 
>> BEFORE
>> foreach(lc, exprstatelist)
>> {
>>  ExprState  *exprstate = (ExprState *) lfirst(lc);
>> AFTER
>> foreach_ptr(ExprState, exprstate, exprstatelist)
>> {
>> 
> 
> Fixed.
> 
>> ======
>> src/backend/statistics/dependencies.c
>> 
>> 2.5.
>> The other variable in other parts of this function had names like:
>> clause_expr
>> bool_expr
>> or_expr
>> stat_expr
>> 
>> So, perhaps your new names should be changed slightly to look more
>> similar to those?
>> 
> 
> Fixed.
> 
>> ======
>> src/backend/statistics/extended_stats.c
>> 
>> 2.6.
>> This seems to be in the wrong patch because here you renamed the local
>> var, not the inner one, as the patch commit message says.
>> 
> 
> Moved to 0003.
> 
>> ======
>> src/backend/utils/adt/jsonpath_exec.c
>> 
>> 2.7.
>> Wondering if 'vals' might be a better name than 'foundJV' (there is
>> already another JsonValueList vals elsewhere in this code).
>> 
> 
> Fixed.
> 
>> ======
>> src/bin/pgbench/pgbench.c
>> 
>> 2.8.
>> Wondering if 'nskipped' is a better name than 'skips'.
>> 
> 
> The around variables all use “s”:
> ```
> int64 skips = 0;
> int64 serialization_failures = 0;
> int64 deadlock_failures = 0;
> int64 other_sql_failures = 0;
> int64 retried = 0;
> int64 retries = 0;
> ```
> 
> That’s why I used the “s” form.
> 
> All fixes are in v5.
> 
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
> 
> 
> 
> 
> <v5-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch><v5-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch><v5-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch><v5-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch><v5-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch><v5-0007-cleanup-rename-local-progname-variables-to-avoid-.patch><v5-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch><v5-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch><v5-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch><v5-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch><v5-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch><v5-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch><v5-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch>

Gentle ping as I saw a recent commit cdaa67565867ba443afb66b9e82023d65487dc7c that cleaned up a single occurrence in pg_trgm.

Rebased to v6.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/







Attachments:

  [application/octet-stream] v6-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (4.1K, 2-v6-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
  download | inline diff:
From 7f9049b4b1dedf3c9945ce4da42177d62b529275 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v6 01/13] cleanup: rename loop variables to avoid local
 shadowing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/backup/basebackup_incremental.c | 10 ++++------
 src/backend/parser/parse_target.c           | 10 ++++------
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index f58ed9b198a..6f3552c6a4a 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -270,7 +270,6 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	ListCell   *lc;
 	TimeLineHistoryEntry **tlep;
 	int			num_wal_ranges;
-	int			i;
 	bool		found_backup_start_tli = false;
 	TimeLineID	earliest_wal_range_tli = 0;
 	XLogRecPtr	earliest_wal_range_start_lsn = InvalidXLogRecPtr;
@@ -312,7 +311,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 */
 	expectedTLEs = readTimeLineHistory(backup_state->starttli);
 	tlep = palloc0(num_wal_ranges * sizeof(TimeLineHistoryEntry *));
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 		bool		saw_earliest_wal_range_tli = false;
@@ -400,7 +399,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 	 * anything here. However, if there's a problem staring us right in the
 	 * face, it's best to report it, so we do.
 	 */
-	for (i = 0; i < num_wal_ranges; ++i)
+	for (int i = 0; i < num_wal_ranges; ++i)
 	{
 		backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
 
@@ -595,15 +594,14 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
 
 			while (1)
 			{
-				unsigned	nblocks;
-				unsigned	i;
+				unsigned int nblocks;
 
 				nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
 													   BLOCKS_PER_READ);
 				if (nblocks == 0)
 					break;
 
-				for (i = 0; i < nblocks; ++i)
+				for (unsigned int i = 0; i < nblocks; ++i)
 					BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
 												   forknum, blocks[i]);
 			}
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index dbf5b2b5c01..3bcfc1f5e3d 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1611,10 +1611,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * subselect must have that outer level as parent.
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetRTEByRangeTablePosn did */
-					for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+					for (Index level = 0; level < netlevelsup; level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = rte->subquery->rtable;
@@ -1669,12 +1668,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
 					 * could be an outer CTE (compare SUBQUERY case above).
 					 */
 					ParseState	mypstate = {0};
-					Index		levelsup;
 
 					/* this loop must work, since GetCTEForRTE did */
-					for (levelsup = 0;
-						 levelsup < rte->ctelevelsup + netlevelsup;
-						 levelsup++)
+					for (Index level = 0;
+						 level < rte->ctelevelsup + netlevelsup;
+						 level++)
 						pstate = pstate->parentParseState;
 					mypstate.parentParseState = pstate;
 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (36.0K, 3-v6-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 718bcf8e347f4f0ca282b286c49996ae39a7937e Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v6 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 13 +++----
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  6 +--
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  6 +--
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 22 files changed, 151 insertions(+), 156 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 9cd563fd0c3..46627638176 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -696,15 +696,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 7f57c787f4c..4dba76be23d 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1129,7 +1129,6 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		int			ndownlinks,
 					i;
 		Buffer		parentBuffer;
-		ListCell   *lc;
 
 		/* Parent may have changed since we memorized this path. */
 		parentBuffer =
@@ -1156,10 +1155,8 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		ndownlinks = list_length(splitinfo);
 		downlinks = palloc_array(IndexTuple, ndownlinks);
 		i = 0;
-		foreach(lc, splitinfo)
+		foreach_ptr(GISTPageSplitInfo, si, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
-
 			/*
 			 * Remember the parent of each new child page in our parent map.
 			 * This assumes that the downlinks fit on the parent page. If the
@@ -1169,7 +1166,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1176,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index 963618a64c4..ae47fd5d480 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1452,8 +1452,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1461,8 +1461,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 4c51e920626..bcfd6562386 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -55,7 +55,6 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	const char *schemaName = stmt->schemaname;
 	Oid			namespaceId;
 	List	   *parsetree_list;
-	ListCell   *parsetree_item;
 	Oid			owner_uid;
 	Oid			saved_uid;
 	int			save_sec_context;
@@ -203,16 +202,15 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 * them through parse_analyze_*() or the rewriter; we can just hand them
 	 * straight to ProcessUtility.
 	 */
-	foreach(parsetree_item, parsetree_list)
+	foreach_ptr(Node, substmt, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index c1da79f36ba..2ea8370e69e 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnums_bms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnums_bms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnums_bms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index b04b0dbd2a0..d2fb3d1a23b 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15743,14 +15743,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15760,9 +15760,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15772,9 +15772,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15782,9 +15782,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15804,7 +15804,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15814,12 +15814,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 98d402c0a3b..a51e3ccb331 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 1290df10c6f..c2a0dac4899 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -79,7 +79,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -87,7 +87,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -100,20 +100,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 7d487a165fa..a4f6765142a 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4065,12 +4065,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4091,13 +4091,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4105,11 +4105,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index e663fb68cfc..8347cae5a6e 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -90,7 +90,6 @@ ValuesNext(ValuesScanState *node)
 		MemoryContext oldContext;
 		Datum	   *values;
 		bool	   *isnull;
-		ListCell   *lc;
 		int			resind;
 
 		/*
@@ -139,13 +138,12 @@ ValuesNext(ValuesScanState *node)
 		isnull = slot->tts_isnull;
 
 		resind = 0;
-		foreach(lc, exprstatelist)
+		foreach_ptr(ExprState, exprstate, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 50b0e10308b..4a567d333b9 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1235,16 +1235,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2407,7 +2407,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2415,25 +2415,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index e3a2f5817e0..62e2ea122e9 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1173,17 +1173,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *op_expr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(op_expr->args)))
+			clause_expr = linitial(op_expr->args);
+		else if (is_pseudo_constant_clause(linitial(op_expr->args)))
+			clause_expr = lsecond(op_expr->args);
 		else
 			return false;
 
@@ -1199,7 +1199,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1207,7 +1207,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *op_expr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1215,21 +1215,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!op_expr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(op_expr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(op_expr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1238,7 +1238,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index d1babaff023..1434c7ee2ef 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1308,7 +1308,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1316,9 +1316,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 52ae0ba4cf7..32a635c3bda 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList vals = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &vals, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&vals);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4138,20 +4138,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc_object(JsonPathVariable);
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index b505a6b4fee..b813e65746a 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 7caf700fd61..a3e02ea2d95 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3304,14 +3304,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4935,7 +4935,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4947,12 +4947,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index d7195685f69..7488a3d547a 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 1dae918cc09..43a9627fad4 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index ab13c90ed33..0e408026183 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 9725d53dfe7..151b9bc1e56 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -203,11 +203,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 				case 'P':
 					if (pset.db)
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -390,10 +390,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..ebb3d62f187 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index b42a0cb4c78..514049a56a1 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3998,7 +3998,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4223,9 +4223,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4242,7 +4242,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (7.5K, 4-v6-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From bfa369c6de6f9b505a3525c8c3fbbb789e6bc2a1 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v6 03/13] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/statistics/extended_stats.c |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  4 ++--
 7 files changed, 21 insertions(+), 21 deletions(-)

diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index d32aaff2821..71e1c583054 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2120,7 +2120,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2375,11 +2375,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index b12765ae691..48171c0f7d5 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -831,7 +831,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -859,7 +859,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index e3697df51a2..d273288c28f 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index c3d275f8726..44297278756 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 334c6498581..44957525dd3 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -1001,7 +1001,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1021,7 +1021,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1032,7 +1032,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 88717c2ff8f..b8bc0b6201a 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index ddfec298fb7..1652fecdf6d 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 5-v6-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From 7720a3271dbeee7d4bf753363e7b1d167897ebfa Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v6 04/13] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index d59216b28f1..4072aa06703 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1959,10 +1959,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.4K, 6-v6-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From 7ab721bcec69bd2f24e7db5406cac296b9133162 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v6 05/13] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 12 ++++++------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 3 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index ff078f22264..d293c6c7e4d 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == level)
 		{
 			wal_level_str = entry->name;
 			break;
@@ -163,10 +163,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			level;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&level, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(level));
 	}
 	else if (info == XLOG_LOGICAL_DECODING_STATUS_CHANGE)
 	{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 03ada8aa0c5..e378bca0220 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index a4060309ae0..f48985fd9cc 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 7-v6-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From cf5c43919ca2f475ff69eda2e2a47761cadd212d Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v6 06/13] cleanup: avoid local variables shadowed by static
 file-scope ones in xlogrecovery.c

This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
 1 file changed, 50 insertions(+), 50 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index ecd66fd86a4..79601125c21 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1219,7 +1219,7 @@ validateRecoveryParameters(void)
  * Returns true if a backup_label was found (and fills the checkpoint
  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
  * returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
  * recovery, *backupFromStandby is set to true.
  *
  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1227,7 +1227,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndNeeded, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1244,7 +1244,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndNeeded = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1288,13 +1288,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	 * other option today being from pg_rewind).  If this was a streamed
 	 * backup then we know that we need to play through until we get to the
 	 * end of the WAL which was generated during the backup (at which point we
-	 * will have reached consistency and backupEndRequired will be reset to be
+	 * will have reached consistency and backupEndNeeded will be reset to be
 	 * false).
 	 */
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndNeeded = true;
 	}
 
 	/*
@@ -1939,14 +1939,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1973,7 +1973,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1981,7 +1981,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1989,7 +1989,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -2003,7 +2003,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2019,10 +2019,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2030,7 +2030,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2040,8 +2040,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2091,7 +2091,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -3164,19 +3164,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3186,7 +3186,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3202,10 +3202,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3221,29 +3221,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3279,8 +3279,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3333,11 +3333,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3384,7 +3384,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3394,8 +3394,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3479,7 +3479,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3515,18 +3515,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3538,7 +3538,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4116,7 +4116,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4131,8 +4131,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.5K, 8-v6-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From b24ca9a9b526de86dc25e2f0286adb8b5f74f0ee Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v6 07/13] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 90 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  4 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 ++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 114 insertions(+), 114 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index e7699be55aa..b48881e71d0 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -194,7 +194,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -290,7 +290,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -298,12 +298,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 7b9b602f3c4..5bf4c4f4774 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 53ec1544ff3..9c1fb823c30 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1048,14 +1048,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2136,7 +2136,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2151,7 +2151,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2195,14 +2195,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2210,11 +2210,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2226,9 +2226,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2258,11 +2258,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2510,11 +2510,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2590,14 +2590,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 09ba0596400..22bf0fa9dcb 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 2bc84505aab..25ec4bb7005 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -401,32 +401,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index f3ce8b1cfb1..f2833fb9b25 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 6df79067db5..49c31d672e0 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1660,7 +1660,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1696,7 +1696,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1719,7 +1719,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1749,7 +1749,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1823,7 +1823,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1895,7 +1895,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10901,8 +10901,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10922,16 +10922,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10944,17 +10944,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
-		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+		else if (strcmp(comment_items->descr, initdb_comment) == 0)
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10963,7 +10963,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11419,8 +11419,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11433,21 +11433,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11497,8 +11497,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13148,8 +13148,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13163,11 +13163,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13178,14 +13178,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13194,7 +13194,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13219,8 +13219,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index 14d886fc86e..96500f7d5c7 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -778,11 +778,11 @@ restore_one_database(const char *inputFileSpec, RestoreOptions *opts,
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
 	printf(_("%s restores PostgreSQL databases from archives created by pg_dump or pg_dumpall.\n\n"), progname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index 9d745d4b25b..c3bdec41526 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 1db55be473f..77b3599e1d6 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 9-v6-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 3a951accf56280caa23f569337e96db9a2914988 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v6 08/13] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 5cfb676f41f..3279a56f531 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 10-v6-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From d4bca5957094705c8e9b55d59a33b49b46b65fec Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v6 09/13] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c     | 12 ++++-----
 src/common/controldata_utils.c           |  8 +++---
 src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index c074556dbfc..a9409ad3783 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index 14530c6489a..b50bc04ef5a 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 11-v6-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 5e5f40eff514ed0ef325080a2d7a92a7b81f10e6 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v6 10/13] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c | 6 +++---
 src/bin/pg_ctl/pg_ctl.c               | 6 +++---
 src/bin/pg_dump/pg_dumpall.c          | 6 +++---
 src/bin/pg_resetwal/pg_resetwal.c     | 6 +++---
 src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
 5 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 61ff5ddc74c..cb5fb7dbba6 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..b1fbe1f88d2 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 1165a0f4afe..b1334da2075 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -2344,20 +2344,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index ab766c34d4b..a9c0269101d 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -745,15 +745,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 4b84f86e7d7..55fca0f0a19 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -622,10 +622,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 12-v6-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 3f302bf3b2a4af82d8978ee29229c5bf61f0f6f3 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v6 11/13] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 4 files changed, 111 insertions(+), 111 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index fa169a8d642..81e9867d7f4 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index be71783b370..9c2e606a363 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1052,12 +1052,12 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	OutputFsync(*now);
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1068,11 +1068,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1083,12 +1083,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 5ce8f2ba287..220f78e3073 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index 76abdfa2ae6..31da309d587 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 13-v6-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 4e713ff4b301014795f3ef552c37af373358def4 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v6 12/13] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v6-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 14-v6-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 043ede43b9b8744421e6158df71550c0ee7d9f2f Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v6 13/13] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/timezone/pgtz.c                | 16 +++---
 6 files changed, 97 insertions(+), 97 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 621b9175c12..6599774800e 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 90946db72ff..d7283b05255 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 0716aff22b6..1c0e5566301 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3034,12 +3034,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3074,7 +3074,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index e2603183f1c..64e44da2a47 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = palloc_object(Interval);
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2524,20 +2524,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 910b97a570b..1c45a4ecd38 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index eac988c21e7..72f41ea42d8 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.50.1 (Apple Git-155)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-03-03 11:55  Chao Li <[email protected]>
  1 sibling, 0 replies; 30+ messages in thread

From: Chao Li @ 2026-03-03 11:55 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Mar 3, 2026, at 18:26, Álvaro Herrera <[email protected]> wrote:
> 
> Pushed 0001.

Hi Alvaro, thank you very much for pushing 0001. But I don’t see it. I tried to pull master and refresh https://git.postgresql.org/cgit/postgresql.git/log/?qt=grep&q=, none of them shows 0001 pushed.


> 
> Three things about the next ones,
> 
> 1. if you rename a function argument, then the function declaration
> should match the new name as well.

Sure, I will make sure that in next revision.

> 
> 2. xlogrecovery.c has far too many global variables.  Can we use this
> opportunity to try to get rid of some of them?  Especially one called
> "xlogreader" is I think quite bug-prone.

Okay, I will try to address this.

> 
> 3. I disagree with some of the choices made; for instance rather than
> rename the local "progname" variables in all those places, I would
> rename the global to logging_progname in logging.c; in bringetbitmap
> (0002) I would rename the outer "tmp" to "sizecheck" or something like
> that.  I guess this is mostly matter of mostly arbitrary judgment ...
> 

I will rename them per your suggestion, and check if there are similar things to rename.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-03-04 06:17  Chao Li <[email protected]>
  1 sibling, 1 reply; 30+ messages in thread

From: Chao Li @ 2026-03-04 06:17 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Mar 3, 2026, at 18:26, Álvaro Herrera <[email protected]> wrote:
> 
> 1. if you rename a function argument, then the function declaration
> should match the new name as well.

Fully addressed.

> 2. xlogrecovery.c has far too many global variables.  Can we use this
> opportunity to try to get rid of some of them?  Especially one called
> "xlogreader" is I think quite bug-prone.

I looked into this. There are quite a few file-scope static variables and global variables, and getting rid of them would likely require a fairly large refactoring.

For now, I worked out an approach that wraps the file-scope static variables into a structure. I moved this change to the last commit and marked it as WIP. I plan to spend more time on the refactoring.

In the meantime, I wonder if it would make sense to handle this refactoring in a separate patch.

> 
> 3. I disagree with some of the choices made; for instance rather than
> rename the local "progname" variables in all those places, I would
> rename the global to logging_progname in logging.c;

The progname conflicts are not caused by logging.c. Instead, it is declared in postmaster.h:
```
extern PGDLLIMPORT const char *progname;
```

I hesitate to rename this global since it is exported, and doing so might lead to additional changes elsewhere. For now, I moved this commit to the second last one, and I may spend more time investigating it.


> in bringetbitmap
> (0002) I would rename the outer "tmp" to "sizecheck" or something like
> that.  I guess this is mostly matter of mostly arbitrary judgment ...
> 

I updated bringetbitmap to rename the outer variable.

I also went through the whole patch and tuned a few other names. Please let me know if you disagree with any of the other renamings.

PFA v7. Each commit is independent, so they do not need to be pushed in the same order as in this patch.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Attachments:

  [application/octet-stream] v7-0001-cleanup-rename-inner-variables-to-avoid-shadowing.patch (37.0K, 2-v7-0001-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 2fc4c8fe8bf6de76498e0693ee24c6b2bf1d3215 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v7 01/12] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/gist/gistbuild.c        | 13 ++---
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  6 +--
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 56 +++++++++++-----------
 src/backend/commands/trigger.c             | 14 +++---
 src/backend/commands/wait.c                | 12 ++---
 src/backend/executor/nodeAgg.c             | 16 +++----
 src/backend/executor/nodeValuesscan.c      |  6 +--
 src/backend/optimizer/plan/createplan.c    | 44 ++++++++---------
 src/backend/statistics/dependencies.c      | 26 +++++-----
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 ++++++------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 ++++----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 +++----
 src/bin/psql/prompt.c                      | 13 +++--
 src/fe_utils/print.c                       | 10 ++--
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 21 files changed, 160 insertions(+), 168 deletions(-)

diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 7f57c787f4c..4dba76be23d 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1129,7 +1129,6 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		int			ndownlinks,
 					i;
 		Buffer		parentBuffer;
-		ListCell   *lc;
 
 		/* Parent may have changed since we memorized this path. */
 		parentBuffer =
@@ -1156,10 +1155,8 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		ndownlinks = list_length(splitinfo);
 		downlinks = palloc_array(IndexTuple, ndownlinks);
 		i = 0;
-		foreach(lc, splitinfo)
+		foreach_ptr(GISTPageSplitInfo, si, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
-
 			/*
 			 * Remember the parent of each new child page in our parent map.
 			 * This assumes that the downlinks fit on the parent page. If the
@@ -1169,7 +1166,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1176,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index 963618a64c4..ae47fd5d480 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1452,8 +1452,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1461,8 +1461,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 4c51e920626..bcfd6562386 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -55,7 +55,6 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	const char *schemaName = stmt->schemaname;
 	Oid			namespaceId;
 	List	   *parsetree_list;
-	ListCell   *parsetree_item;
 	Oid			owner_uid;
 	Oid			saved_uid;
 	int			save_sec_context;
@@ -203,16 +202,15 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 * them through parse_analyze_*() or the rewriter; we can just hand them
 	 * straight to ProcessUtility.
 	 */
-	foreach(parsetree_item, parsetree_list)
+	foreach_ptr(Node, substmt, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index c1da79f36ba..2ea8370e69e 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnums_bms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnums_bms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnums_bms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index b04b0dbd2a0..6dca1236697 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15743,14 +15743,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15760,9 +15760,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15772,9 +15772,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15782,9 +15782,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15804,7 +15804,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15814,12 +15814,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
@@ -22336,7 +22336,7 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 		bool		ccvalid = constr->check[ccnum].ccvalid;
 		Node	   *ccbin_node;
 		bool		found_whole_row;
-		Constraint *constr;
+		Constraint *cons;
 
 		/*
 		 * The partitioned table can not have a NO INHERIT check constraint
@@ -22358,19 +22358,19 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 				 ccname,
 				 RelationGetRelationName(parent_rel));
 
-		constr = makeNode(Constraint);
-		constr->contype = CONSTR_CHECK;
-		constr->conname = pstrdup(ccname);
-		constr->deferrable = false;
-		constr->initdeferred = false;
-		constr->is_enforced = ccenforced;
-		constr->skip_validation = !ccvalid;
-		constr->initially_valid = ccvalid;
-		constr->is_no_inherit = ccnoinherit;
-		constr->raw_expr = NULL;
-		constr->cooked_expr = nodeToString(ccbin_node);
-		constr->location = -1;
-		constraints = lappend(constraints, constr);
+		cons = makeNode(Constraint);
+		cons->contype = CONSTR_CHECK;
+		cons->conname = pstrdup(ccname);
+		cons->deferrable = false;
+		cons->initdeferred = false;
+		cons->is_enforced = ccenforced;
+		cons->skip_validation = !ccvalid;
+		cons->initially_valid = ccvalid;
+		cons->is_no_inherit = ccnoinherit;
+		cons->raw_expr = NULL;
+		cons->cooked_expr = nodeToString(ccbin_node);
+		cons->location = -1;
+		constraints = lappend(constraints, cons);
 	}
 
 	/* Install all CHECK constraints. */
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 98d402c0a3b..a51e3ccb331 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 1290df10c6f..c2a0dac4899 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -79,7 +79,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -87,7 +87,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -100,20 +100,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 7d487a165fa..a4f6765142a 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4065,12 +4065,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4091,13 +4091,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4105,11 +4105,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index e663fb68cfc..8347cae5a6e 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -90,7 +90,6 @@ ValuesNext(ValuesScanState *node)
 		MemoryContext oldContext;
 		Datum	   *values;
 		bool	   *isnull;
-		ListCell   *lc;
 		int			resind;
 
 		/*
@@ -139,13 +138,12 @@ ValuesNext(ValuesScanState *node)
 		isnull = slot->tts_isnull;
 
 		resind = 0;
-		foreach(lc, exprstatelist)
+		foreach_ptr(ExprState, exprstate, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 50b0e10308b..4a567d333b9 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1235,16 +1235,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2407,7 +2407,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2415,25 +2415,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index e3a2f5817e0..62e2ea122e9 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1173,17 +1173,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *op_expr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(op_expr->args)))
+			clause_expr = linitial(op_expr->args);
+		else if (is_pseudo_constant_clause(linitial(op_expr->args)))
+			clause_expr = lsecond(op_expr->args);
 		else
 			return false;
 
@@ -1199,7 +1199,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1207,7 +1207,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *op_expr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1215,21 +1215,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!op_expr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(op_expr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(op_expr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1238,7 +1238,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index d1babaff023..1434c7ee2ef 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1308,7 +1308,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1316,9 +1316,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 52ae0ba4cf7..32a635c3bda 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList vals = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &vals, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&vals);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4138,20 +4138,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc_object(JsonPathVariable);
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index b505a6b4fee..b813e65746a 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 7caf700fd61..a3e02ea2d95 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3304,14 +3304,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4935,7 +4935,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4947,12 +4947,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index d7195685f69..7488a3d547a 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 1dae918cc09..43a9627fad4 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index ab13c90ed33..0e408026183 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 9725d53dfe7..a5882b914a3 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -74,7 +74,6 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	static char destination[MAX_PROMPT_SIZE + 1];
 	char		buf[MAX_PROMPT_SIZE + 1];
 	bool		esc = false;
-	const char *p;
 	const char *prompt_string = "? ";
 	static size_t last_prompt1_width = 0;
 
@@ -100,7 +99,7 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 
 	destination[0] = '\0';
 
-	for (p = prompt_string;
+	for (const char *p = prompt_string;
 		 *p && strlen(destination) < sizeof(destination) - 1;
 		 p++)
 	{
@@ -203,11 +202,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 				case 'P':
 					if (pset.db)
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -390,8 +389,8 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *p = (const char *) destination;
+		const char *end = p + strlen(p);
 		bool		visible = true;
 
 		last_prompt1_width = 0;
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..ebb3d62f187 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index b42a0cb4c78..514049a56a1 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3998,7 +3998,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4223,9 +4223,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4242,7 +4242,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0002-cleanup-rename-outer-variables-to-avoid-shadowing.patch (11.2K, 3-v7-0002-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 8bba1fea3448d9ce6e9c49b3fd8aa4ad412e5553 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v7 02/12] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c          | 10 +++++++---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/statistics/extended_stats.c |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  6 +++---
 src/include/catalog/pg_constraint.h     |  2 +-
 src/include/optimizer/paths.h           |  2 +-
 src/include/storage/read_stream.h       |  2 +-
 11 files changed, 32 insertions(+), 28 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 9cd563fd0c3..a6cc55ff783 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -588,7 +588,9 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 			   *nnullkeys;
 	char	   *ptr;
 	Size		len;
-	char	   *tmp PG_USED_FOR_ASSERTS_ONLY;
+#if defined(USE_ASSERT_CHECKING)
+	char	   *savePtr PG_USED_FOR_ASSERTS_ONLY;
+#endif
 
 	opaque = (BrinOpaque *) scan->opaque;
 	bdesc = opaque->bo_bdesc;
@@ -639,7 +641,9 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
 
 	ptr = palloc(len);
-	tmp = ptr;
+#if defined(USE_ASSERT_CHECKING)
+	savePtr = ptr;
+#endif
 
 	keys = (ScanKey **) ptr;
 	ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
@@ -662,7 +666,7 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
 	}
 
-	Assert(tmp + len == ptr);
+	Assert(savePtr + len == ptr);
 
 	/* zero the number of keys */
 	memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index d32aaff2821..71e1c583054 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2120,7 +2120,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2375,11 +2375,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index b12765ae691..48171c0f7d5 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -831,7 +831,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -859,7 +859,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index e3697df51a2..d273288c28f 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index c3d275f8726..44297278756 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 334c6498581..44957525dd3 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -1001,7 +1001,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1021,7 +1021,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1032,7 +1032,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index cd54c1a74ac..d698cba51a2 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -790,7 +790,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -905,8 +905,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index ddfec298fb7..681cdb5f3f1 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -59,7 +59,7 @@ static XLogRecPtr endpos = InvalidXLogRecPtr;
 static void usage(void);
 static DIR *get_destination_dir(char *dest_folder);
 static void close_destination_dir(DIR *dest_dir, char *dest_folder);
-static XLogRecPtr FindStreamingStart(uint32 *tli);
+static XLogRecPtr FindStreamingStart(uint32 *ptli);
 static void StreamLog(void);
 static bool stop_streaming(XLogRecPtr xlogpos, uint32 timeline,
 						   bool segment_finished);
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
index 1b7fedf1750..51ccda7fe52 100644
--- a/src/include/catalog/pg_constraint.h
+++ b/src/include/catalog/pg_constraint.h
@@ -269,7 +269,7 @@ extern HeapTuple findDomainNotNullConstraint(Oid typid);
 extern AttrNumber extractNotNullColumn(HeapTuple constrTup);
 extern bool AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
 									 bool is_local, bool is_no_inherit, bool is_notvalid);
-extern List *RelationGetNotNullConstraints(Oid relid, bool cooked,
+extern List *RelationGetNotNullConstraints(Oid relid, bool want_cooked,
 										   bool include_noinh);
 
 extern void RemoveConstraintById(Oid conId);
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h
index 8751ad7381c..ef4ba423f05 100644
--- a/src/include/optimizer/paths.h
+++ b/src/include/optimizer/paths.h
@@ -145,7 +145,7 @@ extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root,
 												  Oid opcintype,
 												  Oid collation,
 												  Index sortref,
-												  Relids rel,
+												  Relids relids,
 												  bool create_it);
 extern EquivalenceMember *find_ec_member_matching_expr(EquivalenceClass *ec,
 													   Expr *expr,
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index c9359b29b0f..f677f368218 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -88,7 +88,7 @@ extern ReadStream *read_stream_begin_relation(int flags,
 											  ReadStreamBlockNumberCB callback,
 											  void *callback_private_data,
 											  size_t per_buffer_data_size);
-extern Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data);
+extern Buffer read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data);
 extern BlockNumber read_stream_next_block(ReadStream *stream,
 										  BufferAccessStrategy *strategy);
 extern ReadStream *read_stream_begin_smgr_relation(int flags,
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0003-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 4-v7-0003-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From 96466e1246c0d94929968f10473de68a2efc2633 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v7 03/12] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index d59216b28f1..4072aa06703 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1959,10 +1959,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0004-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (4.0K, 5-v7-0004-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From bb03ad08fd1389756aa1a6c700752f84ab7d17f6 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v7 04/12] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 12 ++++++------
 src/backend/access/transam/xlogreader.c |  4 ++--
 src/bin/pg_controldata/pg_controldata.c |  4 ++--
 src/include/access/xlogreader.h         |  2 +-
 4 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index ff078f22264..d293c6c7e4d 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == level)
 		{
 			wal_level_str = entry->name;
 			break;
@@ -163,10 +163,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
 	}
 	else if (info == XLOG_CHECKPOINT_REDO)
 	{
-		int			wal_level;
+		int			level;
 
-		memcpy(&wal_level, rec, sizeof(int));
-		appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+		memcpy(&level, rec, sizeof(int));
+		appendStringInfo(buf, "wal_level %s", get_wal_level_string(level));
 	}
 	else if (info == XLOG_LOGICAL_DECODING_STATUS_CHANGE)
 	{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 03ada8aa0c5..e378bca0220 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index a4060309ae0..f48985fd9cc 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 80f1a548e08..43aefb94263 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -327,7 +327,7 @@ XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
 }
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wal_seg_size,
 										   const char *waldir,
 										   XLogReaderRoutine *routine,
 										   void *private_data);
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0005-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 6-v7-0005-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From bb9d78de96e36c7d8161a1531df61f5ae86e9472 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v7 05/12] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 5cfb676f41f..3279a56f531 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0006-cleanup-avoid-local-variables-shadowed-by-globals.patch (9.4K, 7-v7-0006-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From a8d3326b378bb846f9f3c3a685299b19d0c47237 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v7 06/12] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c         | 12 +++----
 src/common/controldata_utils.c               |  8 ++---
 src/include/common/controldata_utils.h       |  4 +--
 src/include/libpq/libpq.h                    |  2 +-
 src/interfaces/ecpg/preproc/descriptor.c     | 34 ++++++++++----------
 src/interfaces/ecpg/preproc/preproc_extern.h |  6 ++--
 6 files changed, 33 insertions(+), 33 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index c074556dbfc..a9409ad3783 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index 14530c6489a..b50bc04ef5a 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -186,7 +186,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/include/common/controldata_utils.h b/src/include/common/controldata_utils.h
index 6dd0999f805..a9d52cd4410 100644
--- a/src/include/common/controldata_utils.h
+++ b/src/include/common/controldata_utils.h
@@ -12,10 +12,10 @@
 
 #include "catalog/pg_control.h"
 
-extern ControlFileData *get_controlfile(const char *DataDir, bool *crc_ok_p);
+extern ControlFileData *get_controlfile(const char *data_dir, bool *crc_ok_p);
 extern ControlFileData *get_controlfile_by_exact_path(const char *ControlFilePath,
 													  bool *crc_ok_p);
-extern void update_controlfile(const char *DataDir,
+extern void update_controlfile(const char *data_dir,
 							   ControlFileData *ControlFile, bool do_sync);
 
 #endif							/* COMMON_CONTROLDATA_UTILS_H */
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index 790724b6a0b..2c93e520018 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -160,7 +160,7 @@ enum ssl_protocol_versions
  */
 extern int	run_ssl_passphrase_command(const char *prompt, bool is_server_start,
 									   char *buf, int size);
-extern bool check_ssl_key_file_permissions(const char *ssl_key_file,
+extern bool check_ssl_key_file_permissions(const char *sslKeyFile,
 										   bool isServerStart);
 
 #endif							/* LIBPQ_H */
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
diff --git a/src/interfaces/ecpg/preproc/preproc_extern.h b/src/interfaces/ecpg/preproc/preproc_extern.h
index 2c89e30621e..337b406380a 100644
--- a/src/interfaces/ecpg/preproc/preproc_extern.h
+++ b/src/interfaces/ecpg/preproc/preproc_extern.h
@@ -97,9 +97,9 @@ extern void output_set_descr(const char *desc_name, const char *index);
 extern void push_assignment(const char *var, enum ECPGdtype value);
 extern struct variable *find_variable(const char *name);
 extern void whenever_action(int mode);
-extern void add_descriptor(const char *name, const char *connection);
-extern void drop_descriptor(const char *name, const char *connection);
-extern struct descriptor *lookup_descriptor(const char *name, const char *connection);
+extern void add_descriptor(const char *name, const char *conn_str);
+extern void drop_descriptor(const char *name, const char *conn_str);
+extern struct descriptor *lookup_descriptor(const char *name, const char *conn_str);
 extern struct variable *descriptor_variable(const char *name, int input);
 extern struct variable *sqlda_variable(const char *name);
 extern void add_variable_to_head(struct arguments **list,
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0007-cleanup-avoid-local-variables-shadowed-by-static-.patch (8.6K, 8-v7-0007-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From ecc1bfd7e287196c5565cba09c68eebd5646f15b Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v7 07/12] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c |  6 ++---
 src/bin/pg_ctl/pg_ctl.c               |  6 ++---
 src/bin/pg_dump/pg_dumpall.c          | 34 +++++++++++++--------------
 src/bin/pg_resetwal/pg_resetwal.c     |  8 +++----
 src/bin/pg_test_fsync/pg_test_fsync.c |  8 +++----
 5 files changed, 31 insertions(+), 31 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 61ff5ddc74c..cb5fb7dbba6 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..b1fbe1f88d2 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 1165a0f4afe..67eb8285cf5 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -82,10 +82,10 @@ static void buildShSecLabels(PGconn *conn,
 							 PQExpBuffer buffer);
 static void executeCommand(PGconn *conn, const char *query);
 static void check_for_invalid_global_names(PGconn *conn,
-										   SimpleStringList *database_exclude_names);
+										   SimpleStringList *db_exclude_names);
 static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
 								   SimpleStringList *names);
-static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
+static void read_dumpall_filters(const char *fname, SimpleStringList *pattern);
 static ArchiveFormat parseDumpFormat(const char *format);
 static int	createDumpId(void);
 
@@ -2270,7 +2270,7 @@ executeCommand(PGconn *conn, const char *query)
  */
 static void
 check_for_invalid_global_names(PGconn *conn,
-							   SimpleStringList *database_exclude_names)
+							   SimpleStringList *db_exclude_names)
 {
 	PGresult   *res;
 	int			i;
@@ -2297,7 +2297,7 @@ check_for_invalid_global_names(PGconn *conn,
 
 		/* Skip excluded databases since they won't be in map.dat */
 		if (strcmp(objtype, "database") == 0 &&
-			simple_string_list_member(database_exclude_names, objname))
+			simple_string_list_member(db_exclude_names, objname))
 			continue;
 
 		if (strpbrk(objname, "\n\r"))
@@ -2344,20 +2344,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
@@ -2407,29 +2407,29 @@ read_dumpall_filters(const char *filename, SimpleStringList *pattern)
 static ArchiveFormat
 parseDumpFormat(const char *format)
 {
-	ArchiveFormat archDumpFormat;
+	ArchiveFormat archFormat;
 
 	if (pg_strcasecmp(format, "c") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "custom") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "d") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "directory") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "p") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "plain") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "t") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else if (pg_strcasecmp(format, "tar") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else
 		pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
 				 format);
 
-	return archDumpFormat;
+	return archFormat;
 }
 
 /*
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index ab766c34d4b..7a12e1c93ee 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -105,7 +105,7 @@ static int	WalSegSz;
 static void CheckDataVersion(void);
 static bool read_controlfile(void);
 static void GuessControlValues(void);
-static void PrintControlValues(bool guessed);
+static void PrintControlValues(bool bGuessed);
 static void PrintNewControlValues(void);
 static void RewriteControlFile(void);
 static void FindEndOfXLOG(void);
@@ -745,15 +745,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 4b84f86e7d7..8b18b53e80e 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -94,7 +94,7 @@ static void signal_cleanup(SIGNAL_ARGS);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval start_time, struct timeval stop_time, int ops);
 
 #define die(msg) pg_fatal("%s: %m", _(msg))
 
@@ -622,10 +622,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0008-cleanup-rename-local-conn-variables-to-avoid-shad.patch (32.6K, 9-v7-0008-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 4770b5e2e1d3b0ded362a339f9be29f15e6d31ef Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v7 08/12] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/receivelog.h     |   4 +-
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 src/bin/pg_basebackup/streamutil.h     |  10 +--
 6 files changed, 118 insertions(+), 118 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index fa169a8d642..81e9867d7f4 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index be71783b370..9c2e606a363 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1052,12 +1052,12 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	OutputFsync(*now);
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1068,11 +1068,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1083,12 +1083,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 5ce8f2ba287..220f78e3073 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/receivelog.h b/src/bin/pg_basebackup/receivelog.h
index 0caa904da6a..0378e4c20c8 100644
--- a/src/bin/pg_basebackup/receivelog.h
+++ b/src/bin/pg_basebackup/receivelog.h
@@ -50,8 +50,8 @@ typedef struct StreamCtl
 
 
 
-extern bool CheckServerVersionForStreaming(PGconn *conn);
-extern bool ReceiveXlogStream(PGconn *conn,
+extern bool CheckServerVersionForStreaming(PGconn *myconn);
+extern bool ReceiveXlogStream(PGconn *myconn,
 							  StreamCtl *stream);
 
 #endif							/* RECEIVELOG_H */
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index 76abdfa2ae6..31da309d587 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
diff --git a/src/bin/pg_basebackup/streamutil.h b/src/bin/pg_basebackup/streamutil.h
index 15afef3a9c8..69ae24f94ed 100644
--- a/src/bin/pg_basebackup/streamutil.h
+++ b/src/bin/pg_basebackup/streamutil.h
@@ -32,13 +32,13 @@ extern PGconn *conn;
 extern PGconn *GetConnection(void);
 
 /* Replication commands */
-extern bool CreateReplicationSlot(PGconn *conn, const char *slot_name,
+extern bool CreateReplicationSlot(PGconn *myconn, const char *slot_name,
 								  const char *plugin, bool is_temporary,
 								  bool is_physical, bool reserve_wal,
 								  bool slot_exists_ok, bool two_phase,
 								  bool failover);
-extern bool DropReplicationSlot(PGconn *conn, const char *slot_name);
-extern bool RunIdentifySystem(PGconn *conn, char **sysid,
+extern bool DropReplicationSlot(PGconn *myconn, const char *slot_name);
+extern bool RunIdentifySystem(PGconn *myconn, char **sysid,
 							  TimeLineID *starttli,
 							  XLogRecPtr *startpos,
 							  char **db_name);
@@ -53,10 +53,10 @@ extern void AppendIntegerCommandOption(PQExpBuffer buf,
 									   bool use_new_option_syntax,
 									   char *option_name, int32 option_value);
 
-extern bool GetSlotInformation(PGconn *conn, const char *slot_name,
+extern bool GetSlotInformation(PGconn *myconn, const char *slot_name,
 							   XLogRecPtr *restart_lsn,
 							   TimeLineID *restart_tli);
-extern bool RetrieveWalSegSize(PGconn *conn);
+extern bool RetrieveWalSegSize(PGconn *myconn);
 extern TimestampTz feGetCurrentTimestamp(void);
 extern void feTimestampDifference(TimestampTz start_time, TimestampTz stop_time,
 								  long *secs, int *microsecs);
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 10-v7-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From a897898dac25d69611551606690c34e24acc5b54 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v7 09/12] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0010-cleanup-avoid-local-variables-shadowed-by-globals.patch (21.9K, 11-v7-0010-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From ce6995a115082403d7c8ebe2fb7d75eb7a3a6a9c Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v7 10/12] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/include/pgtime.h               |  2 +-
 src/include/utils/datetime.h       |  4 +-
 src/timezone/pgtz.c                | 16 +++---
 8 files changed, 100 insertions(+), 100 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 621b9175c12..6599774800e 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 90946db72ff..d7283b05255 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 0716aff22b6..1c0e5566301 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3034,12 +3034,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3074,7 +3074,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index e2603183f1c..64e44da2a47 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = palloc_object(Interval);
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2524,20 +2524,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 910b97a570b..1c45a4ecd38 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/include/pgtime.h b/src/include/pgtime.h
index ba6705f71bd..458b4300a63 100644
--- a/src/include/pgtime.h
+++ b/src/include/pgtime.h
@@ -91,7 +91,7 @@ extern PGDLLIMPORT pg_tz *session_timezone;
 extern PGDLLIMPORT pg_tz *log_timezone;
 
 extern void pg_timezone_initialize(void);
-extern pg_tz *pg_tzset(const char *tzname);
+extern pg_tz *pg_tzset(const char *zone);
 extern pg_tz *pg_tzset_offset(long gmtoffset);
 
 extern pg_tzenum *pg_tzenumerate_start(void);
diff --git a/src/include/utils/datetime.h b/src/include/utils/datetime.h
index f77c6acd8b6..abdaaaccb45 100644
--- a/src/include/utils/datetime.h
+++ b/src/include/utils/datetime.h
@@ -345,8 +345,8 @@ extern int	DecodeTimezoneAbbrev(int field, const char *lowtoken,
 extern int	DecodeSpecial(int field, const char *lowtoken, int *val);
 extern int	DecodeUnits(int field, const char *lowtoken, int *val);
 
-extern int	DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz);
-extern pg_tz *DecodeTimezoneNameToTz(const char *tzname);
+extern int	DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz);
+extern pg_tz *DecodeTimezoneNameToTz(const char *tz_name);
 
 extern int	DecodeTimezoneAbbrevPrefix(const char *str,
 									   int *offset, pg_tz **tz);
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index eac988c21e7..72f41ea42d8 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0011-cleanup-rename-local-progname-variables-to-avoid-.patch (25.5K, 12-v7-0011-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 47ccbcf17ae1af0ce5bca6abc62b55e455357c87 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v7 11/12] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 90 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  4 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 ++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 114 insertions(+), 114 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index e7699be55aa..b48881e71d0 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -194,7 +194,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	int			flag;
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = 0;	/* No checksum */
@@ -290,7 +290,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -298,12 +298,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 7b9b602f3c4..5bf4c4f4774 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 53ec1544ff3..9c1fb823c30 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1048,14 +1048,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2136,7 +2136,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2151,7 +2151,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2195,14 +2195,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2210,11 +2210,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2226,9 +2226,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2258,11 +2258,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2510,11 +2510,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2590,14 +2590,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 09ba0596400..22bf0fa9dcb 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 2bc84505aab..25ec4bb7005 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -401,32 +401,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index f3ce8b1cfb1..f2833fb9b25 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 6df79067db5..49c31d672e0 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1660,7 +1660,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1696,7 +1696,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1719,7 +1719,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1749,7 +1749,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1823,7 +1823,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1895,7 +1895,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -10901,8 +10901,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -10922,16 +10922,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -10944,17 +10944,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
-		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+		else if (strcmp(comment_items->descr, initdb_comment) == 0)
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -10963,7 +10963,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11419,8 +11419,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11433,21 +11433,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11497,8 +11497,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13148,8 +13148,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13163,11 +13163,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13178,14 +13178,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13194,7 +13194,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13219,8 +13219,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index 14d886fc86e..96500f7d5c7 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -778,11 +778,11 @@ restore_one_database(const char *inputFileSpec, RestoreOptions *opts,
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
 	printf(_("%s restores PostgreSQL databases from archives created by pg_dump or pg_dumpall.\n\n"), progname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index 9d745d4b25b..c3bdec41526 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 1db55be473f..77b3599e1d6 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v7-0012-WIP-xlogrecovery-consolidate-file-local-mutable-s.patch (30.2K, 13-v7-0012-WIP-xlogrecovery-consolidate-file-local-mutable-s.patch)
  download | inline diff:
From 05dd489048d2a3c983a376469972816196f384c6 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 4 Mar 2026 12:42:12 +0800
Subject: [PATCH v7 12/12] WIP: xlogrecovery: consolidate file-local mutable
 state

---
 src/backend/access/transam/xlogrecovery.c | 395 ++++++++++++++--------
 1 file changed, 256 insertions(+), 139 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index ecd66fd86a4..f683bebaec1 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -105,25 +105,10 @@ bool		wal_receiver_create_temp_slot = false;
  * recoveryTargetTLIRequested: numeric value of requested timeline, if constant
  *
  * recoveryTargetTLI: the currently understood target timeline; changes
- *
- * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and
- * the timelines of its known parents, newest first (so recoveryTargetTLI is
- * always the first list member).  Only these TLIs are expected to be seen in
- * the WAL segments we read, and indeed only these TLIs will be considered as
- * candidate WAL files to open at all.
- *
- * curFileTLI: the TLI appearing in the name of the current input WAL file.
- * (This is not necessarily the same as the timeline from which we are
- * replaying WAL, which StartupXLOG calls replayTLI, because we could be
- * scanning data that was copied from an ancestor timeline when the current
- * file was created.)  During a sequential scan we do not allow this value
- * to decrease.
  */
 RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal = RECOVERY_TARGET_TIMELINE_LATEST;
 TimeLineID	recoveryTargetTLIRequested = 0;
 TimeLineID	recoveryTargetTLI = 0;
-static List *expectedTLEs;
-static TimeLineID curFileTLI;
 
 /*
  * When ArchiveRecoveryRequested is set, archive recovery was requested,
@@ -145,53 +130,12 @@ bool		InArchiveRecovery = false;
  * in standby mode.  These variables are only valid in the startup process.
  * They work similarly to ArchiveRecoveryRequested and InArchiveRecovery.
  */
-static bool StandbyModeRequested = false;
 bool		StandbyMode = false;
 
 /* was a signal file present at startup? */
 static bool standby_signal_file_found = false;
 static bool recovery_signal_file_found = false;
 
-/*
- * CheckPointLoc is the position of the checkpoint record that determines
- * where to start the replay.  It comes from the backup label file or the
- * control file.
- *
- * RedoStartLSN is the checkpoint's REDO location, also from the backup label
- * file or the control file.  In standby mode, XLOG streaming usually starts
- * from the position where an invalid record was found.  But if we fail to
- * read even the initial checkpoint record, we use the REDO location instead
- * of the checkpoint location as the start position of XLOG streaming.
- * Otherwise we would have to jump backwards to the REDO location after
- * reading the checkpoint record, because the REDO record can precede the
- * checkpoint record.
- */
-static XLogRecPtr CheckPointLoc = InvalidXLogRecPtr;
-static TimeLineID CheckPointTLI = 0;
-static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr;
-static TimeLineID RedoStartTLI = 0;
-
-/*
- * Local copy of SharedHotStandbyActive variable. False actually means "not
- * known, need to check the shared state".
- */
-static bool LocalHotStandbyActive = false;
-
-/*
- * Local copy of SharedPromoteIsTriggered variable. False actually means "not
- * known, need to check the shared state".
- */
-static bool LocalPromoteIsTriggered = false;
-
-/* Has the recovery code requested a walreceiver wakeup? */
-static bool doRequestWalReceiverReply;
-
-/* XLogReader object used to parse the WAL records */
-static XLogReaderState *xlogreader = NULL;
-
-/* XLogPrefetcher object used to consume WAL records with read-ahead */
-static XLogPrefetcher *xlogprefetcher = NULL;
-
 /* Parameters passed down from ReadRecord to the XLogPageRead callback. */
 typedef struct XLogPageReadPrivate
 {
@@ -201,9 +145,6 @@ typedef struct XLogPageReadPrivate
 	TimeLineID	replayTLI;
 } XLogPageReadPrivate;
 
-/* flag to tell XLogPageRead that we have started replaying */
-static bool InRedo = false;
-
 /*
  * Codes indicating where we got a WAL file from during recovery, or where
  * to attempt to get one.
@@ -219,6 +160,204 @@ typedef enum
 /* human-readable names for XLogSources, for debugging output */
 static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
 
+/*
+ * Forward declaration for state field holding shared-memory recovery control
+ * pointer.
+ */
+typedef struct XLogRecoveryCtlData XLogRecoveryCtlData;
+
+/*
+ * File-local mutable state for WAL recovery.
+ *
+ * Keep state in a single object to avoid a broad set of independent static
+ * globals and make it easier to evolve recovery internals.
+ */
+typedef struct XLogRecoveryLocalState
+{
+	/*
+	 * A list of TimeLineHistoryEntries for recoveryTargetTLI and the
+	 * timelines of its known parents, newest first (so recoveryTargetTLI is
+	 * always the first list member).  Only these TLIs are expected to be seen
+	 * in the WAL segments we read, and indeed only these TLIs will be
+	 * considered as candidate WAL files to open at all.
+	 */
+	List	   *expectedTLEs;
+
+	/*
+	 * The TLI appearing in the name of the current input WAL file. (This is
+	 * not necessarily the same as the timeline from which we are replaying
+	 * WAL, which StartupXLOG calls replayTLI, because we could be scanning
+	 * data that was copied from an ancestor timeline when the current file
+	 * was created.)  During a sequential scan we do not allow this value to
+	 * decrease.
+	 */
+	TimeLineID	curFileTLI;
+
+	/*
+	 * When StandbyModeRequested is set, standby mode was requested, i.e.
+	 * standby.signal file was present. It is only valid in the startup
+	 * process.
+	 */
+	bool		standbyModeRequested;
+
+	/*
+	 * CheckPointLoc is the position of the checkpoint record that determines
+	 * where to start the replay.  It comes from the backup label file or the
+	 * control file.
+	 *
+	 * RedoStartLSN is the checkpoint's REDO location, also from the backup
+	 * label file or the control file.  In standby mode, XLOG streaming
+	 * usually starts from the position where an invalid record was found. But
+	 * if we fail to read even the initial checkpoint record, we use the REDO
+	 * location instead of the checkpoint location as the start position of
+	 * XLOG streaming. Otherwise we would have to jump backwards to the REDO
+	 * location after reading the checkpoint record, because the REDO record
+	 * can precede the checkpoint record.
+	 */
+	XLogRecPtr	checkPointLoc;
+	TimeLineID	checkPointTLI;
+	XLogRecPtr	redoStartLSN;
+	TimeLineID	redoStartTLI;
+
+	/*
+	 * Local copy of SharedHotStandbyActive variable. False actually means
+	 * "not known, need to check the shared state".
+	 */
+	bool		localHotStandbyActive;
+
+	/*
+	 * Local copy of SharedPromoteIsTriggered variable. False actually means
+	 * "not known, need to check the shared state".
+	 */
+	bool		localPromoteIsTriggered;
+
+	/* Has the recovery code requested a walreceiver wakeup? */
+	bool		doRequestWalReceiverReply;
+
+	/* XLogReader object used to parse the WAL records */
+	XLogReaderState *xlogReader;
+
+	/* XLogPrefetcher object used to consume WAL records with read-ahead */
+	XLogPrefetcher *xlogPrefetcher;
+
+	/* flag to tell XLogPageRead that we have started replaying */
+	bool		inRedo;
+
+	/*
+	 * readFile is -1 or a kernel FD for the log file segment that's currently
+	 * open for reading.  readSegNo identifies the segment.  readOff is the
+	 * offset of the page just read, readLen indicates how much of it has been
+	 * read into readBuf, and readSource indicates where we got the currently
+	 * open file from.
+	 *
+	 * Note: we could use Reserve/ReleaseExternalFD to track consumption of
+	 * this FD too (like for openLogFile in xlog.c); but it doesn't currently
+	 * seem worthwhile, since the XLOG is not read by general-purpose
+	 * sessions.
+	 */
+	int			readFile;
+	XLogSegNo	readSegNo;
+	uint32		readOff;
+	uint32		readLen;
+	XLogSource	readSource;
+
+	/*
+	 * Keeps track of which source we're currently reading from. This is
+	 * different from readSource in that this is always set, even when we
+	 * don't currently have a WAL file open. If lastSourceFailed is set, our
+	 * last attempt to read from currentSource failed, and we should try
+	 * another source next.
+	 *
+	 * pendingWalRcvRestart is set when a config change occurs that requires a
+	 * walreceiver restart.  This is only valid in XLOG_FROM_STREAM state.
+	 */
+	XLogSource	currentSource;
+	bool		lastSourceFailed;
+	bool		pendingWalRcvRestart;
+
+	/*
+	 * These variables track when we last obtained some WAL data to process,
+	 * and where we got it from.  (XLogReceiptSource is initially the same as
+	 * readSource, but readSource gets reset to zero when we don't have data
+	 * to process right now.  It is also different from currentSource, which
+	 * also changes when we try to read from a source and fail, while
+	 * XLogReceiptSource tracks where we last successfully read some WAL.)
+	 */
+	TimestampTz xlogReceiptTime;
+	XLogSource	xlogReceiptSource;
+
+	/* Local copy of WalRcv->flushedUpto */
+	XLogRecPtr	flushedUpto;
+	TimeLineID	receiveTLI;
+
+	/* Copy of backupEndRequired from the control file */
+	bool		backupEndRequired;
+
+	/* Buffers dedicated to consistency checks of size BLCKSZ */
+	char	   *replayImageMasked;
+	char	   *primaryImageMasked;
+
+	XLogRecoveryCtlData *xlogRecoveryCtl;
+
+	/*
+	 * if recoveryStopsBefore/After returns true, it saves information of the
+	 * stop point here
+	 */
+	TransactionId recoveryStopXid;
+	TimestampTz recoveryStopTime;
+	XLogRecPtr	recoveryStopLSN;
+	char		recoveryStopName[MAXFNAMELEN];
+	bool		recoveryStopAfter;
+}			XLogRecoveryLocalState;
+
+static XLogRecoveryLocalState XLogRecoveryState =
+{
+	.checkPointLoc = InvalidXLogRecPtr,
+	.redoStartLSN = InvalidXLogRecPtr,
+	.readFile = -1,
+	.readSource = XLOG_FROM_ANY,
+	.currentSource = XLOG_FROM_ANY,
+	.xlogReceiptSource = XLOG_FROM_ANY,
+	.flushedUpto = InvalidXLogRecPtr,
+	.xlogReader = NULL,
+	.xlogPrefetcher = NULL
+};
+
+#define expectedTLEs (XLogRecoveryState.expectedTLEs)
+#define curFileTLI (XLogRecoveryState.curFileTLI)
+#define StandbyModeRequested (XLogRecoveryState.standbyModeRequested)
+#define CheckPointLoc (XLogRecoveryState.checkPointLoc)
+#define CheckPointTLI (XLogRecoveryState.checkPointTLI)
+#define RedoStartLSN (XLogRecoveryState.redoStartLSN)
+#define RedoStartTLI (XLogRecoveryState.redoStartTLI)
+#define LocalHotStandbyActive (XLogRecoveryState.localHotStandbyActive)
+#define LocalPromoteIsTriggered (XLogRecoveryState.localPromoteIsTriggered)
+#define doRequestWalReceiverReply (XLogRecoveryState.doRequestWalReceiverReply)
+#define InRedo (XLogRecoveryState.inRedo)
+#define readFile (XLogRecoveryState.readFile)
+#define readSegNo (XLogRecoveryState.readSegNo)
+#define readOff (XLogRecoveryState.readOff)
+#define readLen (XLogRecoveryState.readLen)
+#define readSource (XLogRecoveryState.readSource)
+#define currentSource (XLogRecoveryState.currentSource)
+#define lastSourceFailed (XLogRecoveryState.lastSourceFailed)
+#define pendingWalRcvRestart (XLogRecoveryState.pendingWalRcvRestart)
+#define XLogReceiptTime (XLogRecoveryState.xlogReceiptTime)
+#define XLogReceiptSource (XLogRecoveryState.xlogReceiptSource)
+#define flushedUpto (XLogRecoveryState.flushedUpto)
+#define receiveTLI (XLogRecoveryState.receiveTLI)
+#define xlogreader (XLogRecoveryState.xlogReader)
+#define xlogprefetcher (XLogRecoveryState.xlogPrefetcher)
+#define BackupEndRequired (XLogRecoveryState.backupEndRequired)
+#define replay_image_masked (XLogRecoveryState.replayImageMasked)
+#define primary_image_masked (XLogRecoveryState.primaryImageMasked)
+#define XLogRecoveryCtl (XLogRecoveryState.xlogRecoveryCtl)
+#define recoveryStopXid (XLogRecoveryState.recoveryStopXid)
+#define recoveryStopTime (XLogRecoveryState.recoveryStopTime)
+#define recoveryStopLSN (XLogRecoveryState.recoveryStopLSN)
+#define recoveryStopName (XLogRecoveryState.recoveryStopName)
+#define recoveryStopAfter (XLogRecoveryState.recoveryStopAfter)
+
 /*
  * readFile is -1 or a kernel FD for the log file segment that's currently
  * open for reading.  readSegNo identifies the segment.  readOff is the offset
@@ -229,11 +368,6 @@ static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "strea
  * FD too (like for openLogFile in xlog.c); but it doesn't currently seem
  * worthwhile, since the XLOG is not read by general-purpose sessions.
  */
-static int	readFile = -1;
-static XLogSegNo readSegNo = 0;
-static uint32 readOff = 0;
-static uint32 readLen = 0;
-static XLogSource readSource = XLOG_FROM_ANY;
 
 /*
  * Keeps track of which source we're currently reading from. This is
@@ -245,9 +379,6 @@ static XLogSource readSource = XLOG_FROM_ANY;
  * pendingWalRcvRestart is set when a config change occurs that requires a
  * walreceiver restart.  This is only valid in XLOG_FROM_STREAM state.
  */
-static XLogSource currentSource = XLOG_FROM_ANY;
-static bool lastSourceFailed = false;
-static bool pendingWalRcvRestart = false;
 
 /*
  * These variables track when we last obtained some WAL data to process,
@@ -257,12 +388,8 @@ static bool pendingWalRcvRestart = false;
  * also changes when we try to read from a source and fail, while
  * XLogReceiptSource tracks where we last successfully read some WAL.)
  */
-static TimestampTz XLogReceiptTime = 0;
-static XLogSource XLogReceiptSource = XLOG_FROM_ANY;
 
 /* Local copy of WalRcv->flushedUpto */
-static XLogRecPtr flushedUpto = InvalidXLogRecPtr;
-static TimeLineID receiveTLI = 0;
 
 /*
  * Copy of minRecoveryPoint and backupEndPoint from the control file.
@@ -282,7 +409,6 @@ static TimeLineID minRecoveryPointTLI;
 
 static XLogRecPtr backupStartPoint;
 static XLogRecPtr backupEndPoint;
-static bool backupEndRequired = false;
 
 /*
  * Have we reached a consistent database state?  In crash recovery, we have
@@ -301,8 +427,6 @@ static bool backupEndRequired = false;
 bool		reachedConsistency = false;
 
 /* Buffers dedicated to consistency checks of size BLCKSZ */
-static char *replay_image_masked = NULL;
-static char *primary_image_masked = NULL;
 
 
 /*
@@ -368,8 +492,6 @@ typedef struct XLogRecoveryCtlData
 	slock_t		info_lck;		/* locks shared variables shown above */
 } XLogRecoveryCtlData;
 
-static XLogRecoveryCtlData *XLogRecoveryCtl = NULL;
-
 /*
  * abortedRecPtr is the start pointer of a broken record at end of WAL when
  * recovery completes; missingContrecPtr is the location of the first
@@ -383,21 +505,16 @@ static XLogRecPtr missingContrecPtr;
  * if recoveryStopsBefore/After returns true, it saves information of the stop
  * point here
  */
-static TransactionId recoveryStopXid;
-static TimestampTz recoveryStopTime;
-static XLogRecPtr recoveryStopLSN;
-static char recoveryStopName[MAXFNAMELEN];
-static bool recoveryStopAfter;
 
 /* prototypes for local functions */
-static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI);
+static void ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI);
 
 static void EnableStandbyMode(void);
 static void readRecoverySignalFile(void);
 static void validateRecoveryParameters(void);
 static bool read_backup_label(XLogRecPtr *checkPointLoc,
 							  TimeLineID *backupLabelTLI,
-							  bool *backupEndRequired, bool *backupFromStandby);
+							  bool *backupEndRequiredPtr, bool *backupFromStandby);
 static bool read_tablespace_map(List **tablespaces);
 
 static void xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI);
@@ -419,11 +536,11 @@ static void recoveryPausesHere(bool endOfRecovery);
 static bool recoveryApplyDelay(XLogReaderState *record);
 static void ConfirmRecoveryPaused(void);
 
-static XLogRecord *ReadRecord(XLogPrefetcher *xlogprefetcher,
+static XLogRecord *ReadRecord(XLogPrefetcher *prefetcher,
 							  int emode, bool fetching_ckpt,
 							  TimeLineID replayTLI);
 
-static int	XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
+static int	XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr,
 						 int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
 static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
 													  bool randAccess,
@@ -433,7 +550,7 @@ static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
 													  XLogRecPtr replayLSN,
 													  bool nonblocking);
 static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
-static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher,
+static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *prefetcher,
 										XLogRecPtr RecPtr, TimeLineID replayTLI);
 static bool rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN);
 static int	XLogFileRead(XLogSegNo segno, TimeLineID tli,
@@ -596,7 +713,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 	 * process after checking for signal files and after performing validation
 	 * of the recovery parameters.
 	 */
-	if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &backupEndRequired,
+	if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &BackupEndRequired,
 						  &backupFromStandby))
 	{
 		List	   *tablespaces = NIL;
@@ -994,7 +1111,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 		if (haveBackupLabel)
 		{
 			ControlFile->backupStartPoint = checkPoint.redo;
-			ControlFile->backupEndRequired = backupEndRequired;
+			ControlFile->backupEndRequired = BackupEndRequired;
 
 			if (backupFromStandby)
 			{
@@ -1011,7 +1128,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 
 	/* remember these, so that we know when we have reached consistency */
 	backupStartPoint = ControlFile->backupStartPoint;
-	backupEndRequired = ControlFile->backupEndRequired;
+	BackupEndRequired = ControlFile->backupEndRequired;
 	backupEndPoint = ControlFile->backupEndPoint;
 	if (InArchiveRecovery)
 	{
@@ -1227,7 +1344,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndRequiredPtr, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1244,7 +1361,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndRequiredPtr = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1294,7 +1411,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndRequiredPtr = true;
 	}
 
 	/*
@@ -1939,14 +2056,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1973,7 +2090,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1981,7 +2098,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1989,7 +2106,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -2003,7 +2120,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2019,10 +2136,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -2030,7 +2147,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -2040,8 +2157,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2091,7 +2208,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -2246,7 +2363,7 @@ CheckRecoveryConsistency(void)
 		ReachedEndOfBackup(lastReplayedEndRecPtr, lastReplayedTLI);
 		backupStartPoint = InvalidXLogRecPtr;
 		backupEndPoint = InvalidXLogRecPtr;
-		backupEndRequired = false;
+		BackupEndRequired = false;
 
 		ereport(LOG,
 				errmsg("completed backup recovery with redo LSN %X/%08X and end LSN %X/%08X",
@@ -2260,7 +2377,7 @@ CheckRecoveryConsistency(void)
 	 * XLOG_BACKUP_END arrives to advise us of the correct minRecoveryPoint.
 	 * All we know prior to that is that we're not consistent yet.
 	 */
-	if (!reachedConsistency && !backupEndRequired &&
+	if (!reachedConsistency && !BackupEndRequired &&
 		minRecoveryPoint <= lastReplayedEndRecPtr)
 	{
 		/*
@@ -3164,19 +3281,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3186,7 +3303,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3202,10 +3319,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3221,29 +3338,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3279,8 +3396,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3333,11 +3450,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3384,7 +3501,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3394,8 +3511,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3479,7 +3596,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3515,18 +3632,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3538,7 +3655,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4116,7 +4233,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4131,8 +4248,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.50.1 (Apple Git-155)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-21 07:01  Chao Li <[email protected]>
  parent: Chao Li <[email protected]>
  0 siblings, 1 reply; 30+ messages in thread

From: Chao Li @ 2026-04-21 07:01 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Mar 4, 2026, at 14:17, Chao Li <[email protected]> wrote:
> 
> 
> 
>> On Mar 3, 2026, at 18:26, Álvaro Herrera <[email protected]> wrote:
>> 
>> 1. if you rename a function argument, then the function declaration
>> should match the new name as well.
> 
> Fully addressed.
> 
>> 2. xlogrecovery.c has far too many global variables.  Can we use this
>> opportunity to try to get rid of some of them?  Especially one called
>> "xlogreader" is I think quite bug-prone.
> 
> I looked into this. There are quite a few file-scope static variables and global variables, and getting rid of them would likely require a fairly large refactoring.
> 
> For now, I worked out an approach that wraps the file-scope static variables into a structure. I moved this change to the last commit and marked it as WIP. I plan to spend more time on the refactoring.
> 
> In the meantime, I wonder if it would make sense to handle this refactoring in a separate patch.
> 
>> 
>> 3. I disagree with some of the choices made; for instance rather than
>> rename the local "progname" variables in all those places, I would
>> rename the global to logging_progname in logging.c;
> 
> The progname conflicts are not caused by logging.c. Instead, it is declared in postmaster.h:
> ```
> extern PGDLLIMPORT const char *progname;
> ```
> 
> I hesitate to rename this global since it is exported, and doing so might lead to additional changes elsewhere. For now, I moved this commit to the second last one, and I may spend more time investigating it.
> 
> 
>> in bringetbitmap
>> (0002) I would rename the outer "tmp" to "sizecheck" or something like
>> that.  I guess this is mostly matter of mostly arbitrary judgment ...
>> 
> 
> I updated bringetbitmap to rename the outer variable.
> 
> I also went through the whole patch and tuned a few other names. Please let me know if you disagree with any of the other renamings.
> 
> PFA v7. Each commit is independent, so they do not need to be pushed in the same order as in this patch.
> 
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
> 
> 
> 
> 
> <v7-0001-cleanup-rename-inner-variables-to-avoid-shadowing.patch><v7-0002-cleanup-rename-outer-variables-to-avoid-shadowing.patch><v7-0003-cleanup-fix-macro-induced-variable-shadowing-in-i.patch><v7-0004-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch><v7-0005-cleanup-avoid-local-variables-shadowed-by-static-.patch><v7-0006-cleanup-avoid-local-variables-shadowed-by-globals.patch><v7-0007-cleanup-avoid-local-variables-shadowed-by-static-.patch><v7-0008-cleanup-rename-local-conn-variables-to-avoid-shad.patch><v7-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch><v7-0010-cleanup-avoid-local-variables-shadowed-by-globals.patch><v7-0011-cleanup-rename-local-progname-variables-to-avoid-.patch><v7-0012-WIP-xlogrecovery-consolidate-file-local-mutable-s.patch>

PFA v8 - rebased and fixed a few new occurrences.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Attachments:

  [application/octet-stream] v8-0001-cleanup-rename-inner-variables-to-avoid-shadowing.patch (39.7K, 2-v8-0001-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 74774c0aa98563d09127d97c1373c0ef105295de Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v8 01/12] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/gist/gistbuild.c         | 13 ++---
 src/backend/commands/extension.c            |  8 +--
 src/backend/commands/schemacmds.c           |  6 +--
 src/backend/commands/statscmds.c            |  6 +--
 src/backend/commands/tablecmds.c            | 56 ++++++++++-----------
 src/backend/commands/trigger.c              | 14 +++---
 src/backend/commands/wait.c                 | 12 ++---
 src/backend/executor/nodeAgg.c              | 16 +++---
 src/backend/executor/nodeValuesscan.c       |  6 +--
 src/backend/optimizer/plan/createplan.c     | 44 ++++++++--------
 src/backend/postmaster/datachecksum_state.c |  8 +--
 src/backend/statistics/dependencies.c       | 26 +++++-----
 src/backend/storage/buffer/bufmgr.c         |  6 +--
 src/backend/utils/adt/jsonpath_exec.c       | 28 +++++------
 src/backend/utils/adt/pg_upgrade_support.c  |  4 +-
 src/backend/utils/adt/ruleutils.c           |  6 +--
 src/backend/utils/adt/varlena.c             | 20 ++++----
 src/backend/utils/mmgr/freepage.c           |  6 +--
 src/bin/pgbench/pgbench.c                   |  6 +--
 src/bin/psql/describe.c                     | 30 +++++------
 src/bin/psql/prompt.c                       | 13 +++--
 src/fe_utils/print.c                        | 10 ++--
 src/interfaces/libpq/fe-connect.c           |  8 +--
 23 files changed, 172 insertions(+), 180 deletions(-)

diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 7f57c787f4c..4dba76be23d 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1129,7 +1129,6 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		int			ndownlinks,
 					i;
 		Buffer		parentBuffer;
-		ListCell   *lc;
 
 		/* Parent may have changed since we memorized this path. */
 		parentBuffer =
@@ -1156,10 +1155,8 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		ndownlinks = list_length(splitinfo);
 		downlinks = palloc_array(IndexTuple, ndownlinks);
 		i = 0;
-		foreach(lc, splitinfo)
+		foreach_ptr(GISTPageSplitInfo, si, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
-
 			/*
 			 * Remember the parent of each new child page in our parent map.
 			 * This assumes that the downlinks fit on the parent page. If the
@@ -1169,7 +1166,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1176,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index a330b5fd6ce..88e14c075b9 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1453,8 +1453,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1462,8 +1462,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index bfaa4743cd8..38adb2b0504 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -55,7 +55,6 @@ CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
 	const char *schemaName = stmt->schemaname;
 	Oid			namespaceId;
 	List	   *parsetree_list;
-	ListCell   *parsetree_item;
 	Oid			owner_uid;
 	Oid			saved_uid;
 	int			save_sec_context;
@@ -203,16 +202,15 @@ CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
 	 * them through parse_analyze_*() or the rewriter; we can just hand them
 	 * straight to ProcessUtility.
 	 */
-	foreach(parsetree_item, parsetree_list)
+	foreach_ptr(Node, substmt, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index b354723be44..1dd22dbd583 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -349,15 +349,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnums_bms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnums_bms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnums_bms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index eec09ba1ded..7b3bb4a211a 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15962,14 +15962,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15979,9 +15979,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15991,9 +15991,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -16001,9 +16001,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -16023,7 +16023,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -16033,12 +16033,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
@@ -22599,7 +22599,7 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 		bool		ccvalid = constr->check[ccnum].ccvalid;
 		Node	   *ccbin_node;
 		bool		found_whole_row;
-		Constraint *constr;
+		Constraint *cons;
 
 		/*
 		 * The partitioned table can not have a NO INHERIT check constraint
@@ -22621,19 +22621,19 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 				 ccname,
 				 RelationGetRelationName(parent_rel));
 
-		constr = makeNode(Constraint);
-		constr->contype = CONSTR_CHECK;
-		constr->conname = pstrdup(ccname);
-		constr->deferrable = false;
-		constr->initdeferred = false;
-		constr->is_enforced = ccenforced;
-		constr->skip_validation = !ccvalid;
-		constr->initially_valid = ccvalid;
-		constr->is_no_inherit = ccnoinherit;
-		constr->raw_expr = NULL;
-		constr->cooked_expr = nodeToString(ccbin_node);
-		constr->location = -1;
-		constraints = lappend(constraints, constr);
+		cons = makeNode(Constraint);
+		cons->contype = CONSTR_CHECK;
+		cons->conname = pstrdup(ccname);
+		cons->deferrable = false;
+		cons->initdeferred = false;
+		cons->is_enforced = ccenforced;
+		cons->skip_validation = !ccvalid;
+		cons->initially_valid = ccvalid;
+		cons->is_no_inherit = ccnoinherit;
+		cons->raw_expr = NULL;
+		cons->cooked_expr = nodeToString(ccbin_node);
+		cons->location = -1;
+		constraints = lappend(constraints, cons);
 	}
 
 	/* Install all CHECK constraints. */
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index da0d1ba6791..38f42c6f706 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1167,7 +1167,7 @@ CreateTriggerFiringOn(const CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1180,18 +1180,18 @@ CreateTriggerFiringOn(const CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 382d5c2d44f..2fa65a22632 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -92,7 +92,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -100,7 +100,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -113,20 +113,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 925caadd2ce..103dee7ec8e 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4067,12 +4067,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4093,13 +4093,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4107,11 +4107,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index effc896ea1c..6d38fc5d26b 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -90,7 +90,6 @@ ValuesNext(ValuesScanState *node)
 		MemoryContext oldContext;
 		Datum	   *values;
 		bool	   *isnull;
-		ListCell   *lc;
 		int			resind;
 
 		/*
@@ -139,13 +138,12 @@ ValuesNext(ValuesScanState *node)
 		isnull = slot->tts_isnull;
 
 		resind = 0;
-		foreach(lc, exprstatelist)
+		foreach_ptr(ExprState, exprstate, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index de6a183da79..fd41fc84113 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1235,16 +1235,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2407,7 +2407,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2415,25 +2415,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index 213a909aa92..f897ff60145 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -546,7 +546,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 {
 	BackgroundWorker bgw;
 	BackgroundWorkerHandle *bgw_handle;
-	bool		launcher_running;
+	bool		worker_launcher_running;
 	DataChecksumsWorkerOperation launcher_running_op;
 
 #ifdef USE_ASSERT_CHECKING
@@ -565,8 +565,8 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	DataChecksumState->launch_cost_limit = cost_limit;
 
 	/* Is the launcher already running? If so, what is it doing? */
-	launcher_running = DataChecksumState->launcher_running;
-	if (launcher_running)
+	worker_launcher_running = DataChecksumState->launcher_running;
+	if (worker_launcher_running)
 		launcher_running_op = DataChecksumState->operation;
 
 	LWLockRelease(DataChecksumsWorkerLock);
@@ -589,7 +589,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	 * already in the desired state, i.e. if the checksums are already enabled
 	 * and you call pg_enable_data_checksums().
 	 */
-	if (!launcher_running)
+	if (!worker_launcher_running)
 	{
 		/*
 		 * Prepare the BackgroundWorker and launch it.
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index e3a2f5817e0..62e2ea122e9 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1173,17 +1173,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *op_expr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(op_expr->args)))
+			clause_expr = linitial(op_expr->args);
+		else if (is_pseudo_constant_clause(linitial(op_expr->args)))
+			clause_expr = lsecond(op_expr->args);
 		else
 			return false;
 
@@ -1199,7 +1199,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1207,7 +1207,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *op_expr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1215,21 +1215,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!op_expr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(op_expr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(op_expr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1238,7 +1238,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 3cc0b0bdd92..24b24e01807 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1299,7 +1299,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1307,9 +1307,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 0ec9b4df2ef..f01a20502a3 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -1925,32 +1925,32 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals;
-				JsonPathExecResult res;
+				JsonPathExecResult execres;
 				bool		isempty;
 
 				JsonValueListInit(&vals);
 
-				res = executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
-														false, &vals);
+				execres = executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
+															false, &vals);
 
 				isempty = JsonValueListIsEmpty(&vals);
 				JsonValueListClear(&vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return isempty ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2128,9 +2128,9 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				error = true;
 				if (jspStrictAbsenceOfErrors(cxt))
@@ -2139,7 +2139,7 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 					goto exit;
 				}
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				found = true;
 				if (!jspStrictAbsenceOfErrors(cxt))
@@ -4444,20 +4444,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc_object(JsonPathVariable);
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index b505a6b4fee..b813e65746a 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 090e8cc28c1..0b098cf469c 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -13097,16 +13097,16 @@ get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
 					foreach(lc, rte->graph_table_columns)
 					{
 						TargetEntry *te = lfirst_node(TargetEntry, lc);
-						deparse_context context = {0};
+						deparse_context dpcontext = {0};
 
 						if (!first)
 							appendStringInfoString(buf, ", ");
 						else
 							first = false;
 
-						context.buf = buf;
+						dpcontext.buf = buf;
 
-						get_rule_expr((Node *) te->expr, &context, false);
+						get_rule_expr((Node *) te->expr, &dpcontext, false);
 						appendStringInfoString(buf, " AS ");
 						appendStringInfoString(buf, quote_identifier(te->resname));
 					}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index c0ff51bd2fc..1dde98d96d2 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3315,14 +3315,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4946,7 +4946,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4958,12 +4958,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index d7195685f69..7488a3d547a 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index c969afab3a5..0dd9600a043 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index dd1179ef927..7d0762556de 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1777,7 +1777,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		printfPQExpBuffer(&buf, "/* %s */\n", _("Get sequence information"));
@@ -1919,12 +1919,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -1938,7 +1938,7 @@ describeOneTableDetails(const char *schemaname,
 	 */
 	if (tableinfo.relkind == RELKIND_PROPGRAPH)
 	{
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		printfPQExpBuffer(&buf, "/* %s */\n", _("Get property graph information"));
@@ -1993,12 +1993,12 @@ describeOneTableDetails(const char *schemaname,
 			}
 		}
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2424,11 +2424,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 9725d53dfe7..a5882b914a3 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -74,7 +74,6 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	static char destination[MAX_PROMPT_SIZE + 1];
 	char		buf[MAX_PROMPT_SIZE + 1];
 	bool		esc = false;
-	const char *p;
 	const char *prompt_string = "? ";
 	static size_t last_prompt1_width = 0;
 
@@ -100,7 +99,7 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 
 	destination[0] = '\0';
 
-	for (p = prompt_string;
+	for (const char *p = prompt_string;
 		 *p && strlen(destination) < sizeof(destination) - 1;
 		 p++)
 	{
@@ -203,11 +202,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 				case 'P':
 					if (pset.db)
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -390,8 +389,8 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *p = (const char *) destination;
+		const char *end = p + strlen(p);
 		bool		visible = true;
 
 		last_prompt1_width = 0;
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index f2dd52003c1..6194bfe3e28 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 4272d386e64..e6ec29906a9 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -4002,7 +4002,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4227,9 +4227,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4246,7 +4246,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0002-cleanup-rename-outer-variables-to-avoid-shadowing.patch (11.2K, 3-v8-0002-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
  download | inline diff:
From 5541f1773ce229f08da3c6a44c2cc3e524e99076 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v8 02/12] cleanup: rename outer variables to avoid shadowing
 inner locals

This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.

Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c          | 10 +++++++---
 src/backend/catalog/objectaddress.c     | 10 +++++-----
 src/backend/catalog/pg_constraint.c     |  4 ++--
 src/backend/optimizer/path/equivclass.c |  6 +++---
 src/backend/partitioning/partdesc.c     |  6 +++---
 src/backend/statistics/extended_stats.c |  6 +++---
 src/backend/storage/aio/read_stream.c   |  6 +++---
 src/bin/pg_basebackup/pg_receivewal.c   |  6 +++---
 src/include/catalog/pg_constraint.h     |  2 +-
 src/include/optimizer/paths.h           |  2 +-
 src/include/storage/read_stream.h       |  2 +-
 11 files changed, 32 insertions(+), 28 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index bdb30752e09..8e67c7c923d 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -591,7 +591,9 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 			   *nnullkeys;
 	char	   *ptr;
 	Size		len;
-	char	   *tmp PG_USED_FOR_ASSERTS_ONLY;
+#if defined(USE_ASSERT_CHECKING)
+	char	   *savePtr PG_USED_FOR_ASSERTS_ONLY;
+#endif
 
 	opaque = (BrinOpaque *) scan->opaque;
 	bdesc = opaque->bo_bdesc;
@@ -642,7 +644,9 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
 
 	ptr = palloc(len);
-	tmp = ptr;
+#if defined(USE_ASSERT_CHECKING)
+	savePtr = ptr;
+#endif
 
 	keys = (ScanKey **) ptr;
 	ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
@@ -665,7 +669,7 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
 	}
 
-	Assert(tmp + len == ptr);
+	Assert(savePtr + len == ptr);
 
 	/* zero the number of keys */
 	memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c1862809577..3eb5b82e8ae 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2215,7 +2215,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		isnulls[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2471,11 +2471,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	isnulls[0] = false;
+	isnulls[1] = false;
+	isnulls[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, isnulls);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index b12765ae691..48171c0f7d5 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -831,7 +831,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
  * 'include_noinh' determines whether to include NO INHERIT constraints or not.
  */
 List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
 {
 	List	   *notnulls = NIL;
 	Relation	constrRel;
@@ -859,7 +859,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
 
 		colnum = extractNotNullColumn(htup);
 
-		if (cooked)
+		if (want_cooked)
 		{
 			CookedConstraint *cooked;
 
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index e3697df51a2..d273288c28f 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid opcintype,
 						 Oid collation,
 						 Index sortref,
-						 Relids rel,
+						 Relids relids,
 						 bool create_it)
 {
 	JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		if (!equal(opfamilies, cur_ec->ec_opfamilies))
 			continue;
 
-		setup_eclass_member_iterator(&it, cur_ec, rel);
+		setup_eclass_member_iterator(&it, cur_ec, relids);
 		while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
 		{
 			/*
 			 * Ignore child members unless they match the request.
 			 */
 			if (cur_em->em_is_child &&
-				!bms_equal(cur_em->em_relids, rel))
+				!bms_equal(cur_em->em_relids, relids))
 				continue;
 
 			/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index c3d275f8726..44297278756 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	int			i,
 				nparts;
 	bool		retried = false;
-	PartitionKey key = RelationGetPartitionKey(rel);
+	PartitionKey partkey = RelationGetPartitionKey(rel);
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -308,7 +308,7 @@ retry:
 	 * This could fail, but we haven't done any damage if so.
 	 */
 	if (nparts > 0)
-		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
 	if (nparts > 0)
 	{
 		oldcxt = MemoryContextSwitchTo(new_pdcxt);
-		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+		partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
 
 		/* Initialize caching fields for speeding up ExecFindPartition */
 		partdesc->last_found_datum_index = -1;
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 2b83355d26e..a6990db04be 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -1040,7 +1040,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	Size		len;
 	SortItem   *items;
 	Datum	   *values;
-	bool	   *isnull;
+	bool	   *isnulls;
 	char	   *ptr;
 	int		   *typlen;
 
@@ -1060,7 +1060,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	values = (Datum *) ptr;
 	ptr += nvalues * sizeof(Datum);
 
-	isnull = (bool *) ptr;
+	isnulls = (bool *) ptr;
 	ptr += nvalues * sizeof(bool);
 
 	/* make sure we consumed the whole buffer exactly */
@@ -1071,7 +1071,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
 	for (i = 0; i < data->numrows; i++)
 	{
 		items[nrows].values = &values[nrows * numattrs];
-		items[nrows].isnull = &isnull[nrows * numattrs];
+		items[nrows].isnull = &isnulls[nrows * numattrs];
 
 		nrows++;
 	}
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 2374b4cd507..5e26fb64afe 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -1017,7 +1017,7 @@ read_stream_begin_smgr_relation(int flags,
  * the stream early at any time by calling read_stream_end().
  */
 Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
 {
 	Buffer		buffer;
 	int16		oldest_buffer_index;
@@ -1162,8 +1162,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	Assert(oldest_buffer_index >= 0 &&
 		   oldest_buffer_index < stream->queue_size);
 	buffer = stream->buffers[oldest_buffer_index];
-	if (per_buffer_data)
-		*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+	if (pper_buffer_data)
+		*pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 
 	Assert(BufferIsValid(buffer));
 
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index ddfec298fb7..681cdb5f3f1 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -59,7 +59,7 @@ static XLogRecPtr endpos = InvalidXLogRecPtr;
 static void usage(void);
 static DIR *get_destination_dir(char *dest_folder);
 static void close_destination_dir(DIR *dest_dir, char *dest_folder);
-static XLogRecPtr FindStreamingStart(uint32 *tli);
+static XLogRecPtr FindStreamingStart(uint32 *ptli);
 static void StreamLog(void);
 static bool stop_streaming(XLogRecPtr xlogpos, uint32 timeline,
 						   bool segment_finished);
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
  * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
  */
 static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
 {
 	DIR		   *dir;
 	struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
 
 		XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
 
-		*tli = high_tli;
+		*ptli = high_tli;
 		return high_ptr;
 	}
 	else
diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
index 1b7fedf1750..51ccda7fe52 100644
--- a/src/include/catalog/pg_constraint.h
+++ b/src/include/catalog/pg_constraint.h
@@ -269,7 +269,7 @@ extern HeapTuple findDomainNotNullConstraint(Oid typid);
 extern AttrNumber extractNotNullColumn(HeapTuple constrTup);
 extern bool AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
 									 bool is_local, bool is_no_inherit, bool is_notvalid);
-extern List *RelationGetNotNullConstraints(Oid relid, bool cooked,
+extern List *RelationGetNotNullConstraints(Oid relid, bool want_cooked,
 										   bool include_noinh);
 
 extern void RemoveConstraintById(Oid conId);
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h
index 17f2099ec3b..d8eceb66610 100644
--- a/src/include/optimizer/paths.h
+++ b/src/include/optimizer/paths.h
@@ -144,7 +144,7 @@ extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root,
 												  Oid opcintype,
 												  Oid collation,
 												  Index sortref,
-												  Relids rel,
+												  Relids relids,
 												  bool create_it);
 extern EquivalenceMember *find_ec_member_matching_expr(EquivalenceClass *ec,
 													   Expr *expr,
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index 48995c6d534..f89b16bca5a 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -89,7 +89,7 @@ extern ReadStream *read_stream_begin_relation(int flags,
 											  ReadStreamBlockNumberCB callback,
 											  void *callback_private_data,
 											  size_t per_buffer_data_size);
-extern Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data);
+extern Buffer read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data);
 extern BlockNumber read_stream_next_block(ReadStream *stream,
 										  BufferAccessStrategy *strategy);
 extern ReadStream *read_stream_begin_smgr_relation(int flags,
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0003-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 4-v8-0003-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
  download | inline diff:
From 57aa9eafddc4b553bda4b77ecea159713e91261d Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v8 03/12] cleanup: fix macro-induced variable shadowing in
 inval.c

This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index d59216b28f1..4072aa06703 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 		int		_endmsg = (group)->nextmsg[subgroup]; \
 		for (; _msgindex < _endmsg; _msgindex++) \
 		{ \
-			SharedInvalidationMessage *msg = \
+			SharedInvalidationMessage *_msg = \
 				&InvalMessageArrays[subgroup].msgs[_msgindex]; \
 			codeFragment; \
 		} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
 	do { \
 		int		n = NumMessagesInSubGroup(group, subgroup); \
 		if (n > 0) { \
-			SharedInvalidationMessage *msgs = \
+			SharedInvalidationMessage *_msgs = \
 				&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
 			codeFragment; \
 		} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
 	 * don't need to add individual ones when it is present.
 	 */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
 
 	/* Don't add a duplicate item. */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
-							   (msg->rc.relId == relId ||
-								msg->rc.relId == InvalidOid))
+						   if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+							   (_msg->rc.relId == relId ||
+								_msg->rc.relId == InvalidOid))
 						   return);
 
 	/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
 	/* Don't add a duplicate item */
 	/* We assume dbId need not be checked because it will never change */
 	ProcessMessageSubGroup(group, RelCacheMsgs,
-						   if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
-							   msg->sn.relId == relId)
+						   if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+							   _msg->sn.relId == relId)
 						   return);
 
 	/* OK, add the item */
@@ -574,8 +574,8 @@ static void
 ProcessInvalidationMessages(InvalidationMsgsGroup *group,
 							void (*func) (SharedInvalidationMessage *msg))
 {
-	ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
-	ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+	ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+	ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
 }
 
 /*
@@ -586,8 +586,8 @@ static void
 ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
 								 void (*func) (const SharedInvalidationMessage *msgs, int n))
 {
-	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
-	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+	ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+	ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
 }
 
 /* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								CatCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
 								RelCacheMsgs,
 								(memcpy(msgarray + nmsgs,
-										msgs,
+										_msgs,
 										n * sizeof(SharedInvalidationMessage)),
 								 nmsgs += n));
 	Assert(nmsgs == nummsgs);
@@ -1959,10 +1959,10 @@ LogLogicalInvalidations(void)
 		XLogBeginInsert();
 		XLogRegisterData(&xlrec, MinSizeOfXactInvals);
 		ProcessMessageSubGroupMulti(group, CatCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		ProcessMessageSubGroupMulti(group, RelCacheMsgs,
-									XLogRegisterData(msgs,
+									XLogRegisterData(_msgs,
 													 n * sizeof(SharedInvalidationMessage)));
 		XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
 	}
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0004-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.5K, 5-v8-0004-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
  download | inline diff:
From cf97f39017f97ad17636f3ccb12f5e5ce318e9ed Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v8 04/12] cleanup: avoid local wal_level and wal_segment_size
 being shadowed by globals

This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.

Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/rmgrdesc/xlogdesc.c  | 6 +++---
 src/backend/access/transam/xlogreader.c | 4 ++--
 src/bin/pg_controldata/pg_controldata.c | 4 ++--
 src/include/access/xlogreader.h         | 2 +-
 4 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index 2468a7d2578..9af5b42b347 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -35,17 +35,17 @@ const struct config_enum_entry wal_level_options[] = {
 };
 
 /*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
  */
 static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
 {
 	const struct config_enum_entry *entry;
 	const char *wal_level_str = "?";
 
 	for (entry = wal_level_options; entry->name; entry++)
 	{
-		if (entry->val == wal_level)
+		if (entry->val == level)
 		{
 			wal_level_str = entry->name;
 			break;
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 8849610db00..f3360698278 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -105,7 +105,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
 				   XLogReaderRoutine *routine, void *private_data)
 {
 	XLogReaderState *state;
@@ -135,7 +135,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
 					   waldir);
 
 	/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index fe5fc5ec133..1d2577bb2c0 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 97eae2c1dab..73d35144dff 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -327,7 +327,7 @@ XLogReaderHasQueuedRecordOrError(XLogReaderState *state)
 }
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wal_seg_size,
 										   const char *waldir,
 										   XLogReaderRoutine *routine,
 										   void *private_data);
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0005-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 6-v8-0005-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From a34e341962d8f181c5e9f3c509f2bcf0b3e66c43 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v8 05/12] cleanup: avoid local variables shadowed by static
 file-scope ones in file_ops.c

This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 25 deletions(-)

diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 5cfb676f41f..3279a56f531 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
 void
 remove_target_file(const char *path, bool missing_ok)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 	{
 		if (errno == ENOENT && missing_ok)
 			return;
 
 		pg_fatal("could not remove file \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 	}
 }
 
 void
 truncate_target_file(const char *path, off_t newsize)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 	int			fd;
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
 
-	fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+	fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
 	if (fd < 0)
 		pg_fatal("could not open file \"%s\" for truncation: %m",
-				 dstpath);
+				 pathbuf);
 
 	if (ftruncate(fd, newsize) != 0)
 		pg_fatal("could not truncate file \"%s\" to %u: %m",
-				 dstpath, (unsigned int) newsize);
+				 pathbuf, (unsigned int) newsize);
 
 	close(fd);
 }
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
 static void
 create_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (mkdir(dstpath, pg_dir_create_mode) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (mkdir(pathbuf, pg_dir_create_mode) != 0)
 		pg_fatal("could not create directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_dir(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (rmdir(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (rmdir(pathbuf) != 0)
 		pg_fatal("could not remove directory \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 create_target_symlink(const char *path, const char *link)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (symlink(link, dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (symlink(link, pathbuf) != 0)
 		pg_fatal("could not create symbolic link at \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 static void
 remove_target_symlink(const char *path)
 {
-	char		dstpath[MAXPGPATH];
+	char		pathbuf[MAXPGPATH];
 
 	if (dry_run)
 		return;
 
-	snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
-	if (unlink(dstpath) != 0)
+	snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+	if (unlink(pathbuf) != 0)
 		pg_fatal("could not remove symbolic link \"%s\": %m",
-				 dstpath);
+				 pathbuf);
 }
 
 /*
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0006-cleanup-avoid-local-variables-shadowed-by-globals.patch (9.5K, 7-v8-0006-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 48745ffcc7f2e0c48a9a697f0bfba6cefc02d855 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v8 06/12] cleanup: avoid local variables shadowed by globals
 across several files

This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/libpq/be-secure-common.c         | 12 +++----
 src/common/controldata_utils.c               |  8 ++---
 src/include/common/controldata_utils.h       |  4 +--
 src/include/libpq/libpq.h                    |  2 +-
 src/interfaces/ecpg/preproc/descriptor.c     | 34 ++++++++++----------
 src/interfaces/ecpg/preproc/preproc_extern.h |  6 ++--
 6 files changed, 33 insertions(+), 33 deletions(-)

diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index ad04bedaa1d..ee59b77c938 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -118,17 +118,17 @@ error:
  * Check permissions for SSL key files.
  */
 bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
 {
 	int			loglevel = isServerStart ? FATAL : LOG;
 	struct stat buf;
 
-	if (stat(ssl_key_file, &buf) != 0)
+	if (stat(sslKeyFile, &buf) != 0)
 	{
 		ereport(loglevel,
 				(errcode_for_file_access(),
 				 errmsg("could not access private key file \"%s\": %m",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -138,7 +138,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" is not a regular file",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -164,7 +164,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" must be owned by the database user or root",
-						ssl_key_file)));
+						sslKeyFile)));
 		return false;
 	}
 
@@ -174,7 +174,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
 		ereport(loglevel,
 				(errcode(ERRCODE_CONFIG_FILE_ERROR),
 				 errmsg("private key file \"%s\" has group or world access",
-						ssl_key_file),
+						sslKeyFile),
 				 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
 		return false;
 	}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index 4ab116afcde..4b4a35fc01c 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -50,11 +50,11 @@
  * file data is correct.
  */
 ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
 {
 	char		ControlFilePath[MAXPGPATH];
 
-	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 	return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
 }
@@ -187,7 +187,7 @@ retry:
  * routine in the backend.
  */
 void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
 				   ControlFileData *ControlFile, bool do_sync)
 {
 	int			fd;
@@ -212,7 +212,7 @@ update_controlfile(const char *DataDir,
 	memset(buffer, 0, PG_CONTROL_FILE_SIZE);
 	memcpy(buffer, ControlFile, sizeof(ControlFileData));
 
-	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+	snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
 
 #ifndef FRONTEND
 
diff --git a/src/include/common/controldata_utils.h b/src/include/common/controldata_utils.h
index 6dd0999f805..a9d52cd4410 100644
--- a/src/include/common/controldata_utils.h
+++ b/src/include/common/controldata_utils.h
@@ -12,10 +12,10 @@
 
 #include "catalog/pg_control.h"
 
-extern ControlFileData *get_controlfile(const char *DataDir, bool *crc_ok_p);
+extern ControlFileData *get_controlfile(const char *data_dir, bool *crc_ok_p);
 extern ControlFileData *get_controlfile_by_exact_path(const char *ControlFilePath,
 													  bool *crc_ok_p);
-extern void update_controlfile(const char *DataDir,
+extern void update_controlfile(const char *data_dir,
 							   ControlFileData *ControlFile, bool do_sync);
 
 #endif							/* COMMON_CONTROLDATA_UTILS_H */
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index c9b934d2321..a948e246078 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -162,7 +162,7 @@ enum ssl_protocol_versions
 extern int	run_ssl_passphrase_command(const char *cmd, const char *prompt,
 									   bool is_server_start,
 									   char *buf, int size);
-extern bool check_ssl_key_file_permissions(const char *ssl_key_file,
+extern bool check_ssl_key_file_permissions(const char *sslKeyFile,
 										   bool isServerStart);
 extern int	load_hosts(List **hosts, char **err_msg);
 
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *new;
 
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
 
 	new->next = descriptors;
 	new->name = mm_strdup(name);
-	if (connection)
-		new->connection = mm_strdup(connection);
+	if (conn_str)
+		new->connection = mm_strdup(conn_str);
 	else
 		new->connection = NULL;
 	descriptors = new;
 }
 
 void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 }
 
 struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
 {
 	struct descriptor *i;
 
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
-			if (connection && !i->connection)
+			if (conn_str && !i->connection)
 			{
 				/* overwrite descriptor's connection */
-				i->connection = mm_strdup(connection);
+				i->connection = mm_strdup(conn_str);
 				return i;
 			}
 		}
 	}
-	if (connection)
-		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+	if (conn_str)
+		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
 	else
 		mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
 	return NULL;
diff --git a/src/interfaces/ecpg/preproc/preproc_extern.h b/src/interfaces/ecpg/preproc/preproc_extern.h
index 2c89e30621e..337b406380a 100644
--- a/src/interfaces/ecpg/preproc/preproc_extern.h
+++ b/src/interfaces/ecpg/preproc/preproc_extern.h
@@ -97,9 +97,9 @@ extern void output_set_descr(const char *desc_name, const char *index);
 extern void push_assignment(const char *var, enum ECPGdtype value);
 extern struct variable *find_variable(const char *name);
 extern void whenever_action(int mode);
-extern void add_descriptor(const char *name, const char *connection);
-extern void drop_descriptor(const char *name, const char *connection);
-extern struct descriptor *lookup_descriptor(const char *name, const char *connection);
+extern void add_descriptor(const char *name, const char *conn_str);
+extern void drop_descriptor(const char *name, const char *conn_str);
+extern struct descriptor *lookup_descriptor(const char *name, const char *conn_str);
 extern struct variable *descriptor_variable(const char *name, int input);
 extern struct variable *sqlda_variable(const char *name);
 extern void add_variable_to_head(struct arguments **list,
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0007-cleanup-avoid-local-variables-shadowed-by-static-.patch (8.6K, 8-v8-0007-cleanup-avoid-local-variables-shadowed-by-static-.patch)
  download | inline diff:
From 070a6408c55818093641d3c1fb4399c4f71ba703 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v8 07/12] cleanup: avoid local variables shadowed by static
 file-scope ones in several files

This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/executor/execExprInterp.c |  6 ++---
 src/bin/pg_ctl/pg_ctl.c               |  6 ++---
 src/bin/pg_dump/pg_dumpall.c          | 34 +++++++++++++--------------
 src/bin/pg_resetwal/pg_resetwal.c     |  8 +++----
 src/bin/pg_test_fsync/pg_test_fsync.c |  8 +++----
 5 files changed, 31 insertions(+), 31 deletions(-)

diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 3c4843cde86..e0f4761d729 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -473,7 +473,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 	 * This array has to be in the same order as enum ExprEvalOp.
 	 */
 #if defined(EEO_USE_COMPUTED_GOTO)
-	static const void *const dispatch_table[] = {
+	static const void *const _dispatch_table[] = {
 		&&CASE_EEOP_DONE_RETURN,
 		&&CASE_EEOP_DONE_NO_RETURN,
 		&&CASE_EEOP_INNER_FETCHSOME,
@@ -597,11 +597,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
 		&&CASE_EEOP_LAST
 	};
 
-	StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+	StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
 					 "dispatch_table out of whack with ExprEvalOp");
 
 	if (unlikely(state == NULL))
-		return PointerGetDatum(dispatch_table);
+		return PointerGetDatum(_dispatch_table);
 #else
 	Assert(state != NULL);
 #endif							/* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 5539eb8ebef..be5dd81cb8f 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(myargv0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 9e904f76baa..fa713f4e753 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -83,10 +83,10 @@ static void buildShSecLabels(PGconn *conn,
 							 PQExpBuffer buffer);
 static void executeCommand(PGconn *conn, const char *query);
 static void check_for_invalid_global_names(PGconn *conn,
-										   SimpleStringList *database_exclude_names);
+										   SimpleStringList *db_exclude_names);
 static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
 								   SimpleStringList *names);
-static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
+static void read_dumpall_filters(const char *fname, SimpleStringList *pattern);
 static ArchiveFormat parseDumpFormat(const char *format);
 static int	createDumpId(void);
 
@@ -2269,7 +2269,7 @@ executeCommand(PGconn *conn, const char *query)
  */
 static void
 check_for_invalid_global_names(PGconn *conn,
-							   SimpleStringList *database_exclude_names)
+							   SimpleStringList *db_exclude_names)
 {
 	PGresult   *res;
 	int			i;
@@ -2296,7 +2296,7 @@ check_for_invalid_global_names(PGconn *conn,
 
 		/* Skip excluded databases since they won't be in map.dat */
 		if (strcmp(objtype, "database") == 0 &&
-			simple_string_list_member(database_exclude_names, objname))
+			simple_string_list_member(db_exclude_names, objname))
 			continue;
 
 		if (strpbrk(objname, "\n\r"))
@@ -2343,20 +2343,20 @@ dumpTimestamp(const char *msg)
  * read_dumpall_filters - retrieve database identifier patterns from file
  *
  * Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists.  If the filename is "-" then filters will be
+ * them to the relevant lists.  If the fname is "-" then filters will be
  * read from STDIN rather than a file.
  *
  * At the moment, the only allowed filter is for database exclusion.
  */
 static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
 {
 	FilterStateData fstate;
 	char	   *objname;
 	FilterCommandType comtype;
 	FilterObjectType objtype;
 
-	filter_init(&fstate, filename, exit);
+	filter_init(&fstate, fname, exit);
 
 	while (filter_read_item(&fstate, &objname, &comtype, &objtype))
 	{
@@ -2406,29 +2406,29 @@ read_dumpall_filters(const char *filename, SimpleStringList *pattern)
 static ArchiveFormat
 parseDumpFormat(const char *format)
 {
-	ArchiveFormat archDumpFormat;
+	ArchiveFormat archFormat;
 
 	if (pg_strcasecmp(format, "c") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "custom") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "d") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "directory") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "p") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "plain") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "t") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else if (pg_strcasecmp(format, "tar") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else
 		pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
 				 format);
 
-	return archDumpFormat;
+	return archFormat;
 }
 
 /*
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 44f2b446e5d..e087729072c 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -105,7 +105,7 @@ static int	WalSegSz;
 static void CheckDataVersion(void);
 static bool read_controlfile(void);
 static void GuessControlValues(void);
-static void PrintControlValues(bool guessed);
+static void PrintControlValues(bool bGuessed);
 static void PrintNewControlValues(void);
 static void RewriteControlFile(void);
 static void FindEndOfXLOG(void);
@@ -745,15 +745,15 @@ GuessControlValues(void)
 
 
 /*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
  *
  * NB: this display should be just those fields that will not be
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
 {
-	if (guessed)
+	if (bGuessed)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 4b84f86e7d7..8b18b53e80e 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -94,7 +94,7 @@ static void signal_cleanup(SIGNAL_ARGS);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval start_time, struct timeval stop_time, int ops);
 
 #define die(msg) pg_fatal("%s: %m", _(msg))
 
@@ -622,10 +622,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-		(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop_time.tv_sec - start_time.tv_sec) +
+		(stop_time.tv_usec - start_time.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0008-cleanup-rename-local-conn-variables-to-avoid-shad.patch (32.6K, 9-v8-0008-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
  download | inline diff:
From 9a58b41ad589d2716b65eb8fd953bc00ec4d2760 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v8 08/12] cleanup: rename local conn variables to avoid
 shadowing the global

This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/bin/pg_basebackup/pg_basebackup.c  |  32 ++++----
 src/bin/pg_basebackup/pg_recvlogical.c |  24 +++---
 src/bin/pg_basebackup/receivelog.c     | 108 ++++++++++++-------------
 src/bin/pg_basebackup/receivelog.h     |   4 +-
 src/bin/pg_basebackup/streamutil.c     |  58 ++++++-------
 src/bin/pg_basebackup/streamutil.h     |  10 +--
 6 files changed, 118 insertions(+), 118 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index c1a4672aa6f..e653c91355b 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
  * chunk.
  */
 static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
 				void *callback_data)
 {
 	PGresult   *res;
 
 	/* Get the COPY data stream. */
-	res = PQgetResult(conn);
+	res = PQgetResult(myconn);
 	if (PQresultStatus(res) != PGRES_COPY_OUT)
 		pg_fatal("could not get COPY data stream: %s",
-				 PQerrorMessage(conn));
+				 PQerrorMessage(myconn));
 	PQclear(res);
 
 	/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		int			r;
 		char	   *copybuf;
 
-		r = PQgetCopyData(conn, &copybuf, 0);
+		r = PQgetCopyData(myconn, &copybuf, 0);
 		if (r == -1)
 		{
 			/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
 		}
 		else if (r == -2)
 			pg_fatal("could not read COPY data: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 
 		if (bgchild_exited)
 			pg_fatal("background process terminated unexpectedly");
@@ -1269,7 +1269,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
  * manifest if present - as a single COPY stream.
  */
 static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
 {
 	ArchiveStreamState state;
 
@@ -1279,7 +1279,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
 	state.compress = compress;
 
 	/* All the real work happens in ReceiveArchiveStreamChunk. */
-	ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+	ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
 
 	/* If we wrote the backup manifest to a file, close the file. */
 	if (state.manifest_file !=NULL)
@@ -1584,7 +1584,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
  * receive the backup manifest and inject it into that tarfile.
  */
 static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
 			   bool tablespacenum, pg_compress_specification *compress)
 {
 	WriteTarState state;
@@ -1595,16 +1595,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 	/* Pass all COPY data through to the backup streamer. */
 	memset(&state, 0, sizeof(state));
 	is_recovery_guc_supported =
-		PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+		PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
 	expect_unterminated_tarfile =
-		PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+		PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
 	state.streamer = CreateBackupStreamer(archive_name, spclocation,
 										  &manifest_inject_streamer,
 										  is_recovery_guc_supported,
 										  expect_unterminated_tarfile,
 										  compress);
 	state.tablespacenum = tablespacenum;
-	ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+	ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
 	progress_update_filename(NULL);
 
 	/*
@@ -1619,7 +1619,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
 
 		/* Slurp the entire backup manifest into a buffer. */
 		initPQExpBuffer(&buf);
-		ReceiveBackupManifestInMemory(conn, &buf);
+		ReceiveBackupManifestInMemory(myconn, &buf);
 		if (PQExpBufferDataBroken(buf))
 			pg_fatal("out of memory");
 
@@ -1683,7 +1683,7 @@ get_tablespace_mapping(const char *dir)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
 {
 	WriteManifestState state;
 
@@ -1693,7 +1693,7 @@ ReceiveBackupManifest(PGconn *conn)
 	if (state.file == NULL)
 		pg_fatal("could not create file \"%s\": %m", state.filename);
 
-	ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+	ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
 
 	fclose(state.file);
 }
@@ -1720,9 +1720,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
  * Receive the backup manifest file and write it out to a file.
  */
 static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
 {
-	ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+	ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
 }
 
 /*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index be71783b370..9c2e606a363 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
 static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
 							   StreamStopReason reason,
 							   XLogRecPtr lsn);
 
@@ -126,7 +126,7 @@ usage(void)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
 {
 	static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
 	static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 	last_written_lsn = output_written_lsn;
 	last_fsync_lsn = output_fsync_lsn;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -1052,12 +1052,12 @@ main(int argc, char **argv)
  * feedback.
  */
 static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
 {
 	/* flush data to disk, so that we send a recent flush pointer */
 	OutputFsync(*now);
 	*now = feGetCurrentTimestamp();
-	if (!sendFeedback(conn, *now, true, false))
+	if (!sendFeedback(myconn, *now, true, false))
 		return false;
 
 	return true;
@@ -1068,11 +1068,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
  * retry on failure.
  */
 static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
 				   XLogRecPtr lsn)
 {
-	(void) PQputCopyEnd(conn, NULL);
-	(void) PQflush(conn);
+	(void) PQputCopyEnd(myconn, NULL);
+	(void) PQflush(myconn);
 
 	if (verbose)
 	{
@@ -1083,12 +1083,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
 				break;
 			case STREAM_STOP_KEEPALIVE:
 				pg_log_info("end position %X/%08X reached by keepalive",
-							LSN_FORMAT_ARGS(endpos));
+							LSN_FORMAT_ARGS(end_pos));
 				break;
 			case STREAM_STOP_END_OF_WAL:
 				Assert(XLogRecPtrIsValid(lsn));
 				pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
-							LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+							LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
 				break;
 			case STREAM_STOP_NONE:
 				Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 5ce8f2ba287..220f78e3073 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
 
 static bool still_sending = true;	/* feedback still needs to be sent? */
 
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 								  XLogRecPtr *stoppos);
-static int	CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int	CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int	CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int	CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 							  char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
 								int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 							  XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 									   XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
 static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
 										 TimestampTz last_status);
 
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
  * Send a Standby Status Update message to server.
  */
 static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
 {
 	char		replybuf[1 + 8 + 8 + 8 + 8 + 1];
 	int			len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 	replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
 	len += 1;
 
-	if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+	if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
 	{
 		pg_log_error("could not send feedback packet: %s",
-					 PQerrorMessage(conn));
+					 PQerrorMessage(myconn));
 		return false;
 	}
 
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
  * If it's not, an error message is printed to stderr, and false is returned.
  */
 bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
 {
 	int			minServerMajor,
 				maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
 	 */
 	minServerMajor = 903;
 	maxServerMajor = PG_VERSION_NUM / 100;
-	serverMajor = PQserverVersion(conn) / 100;
+	serverMajor = PQserverVersion(myconn) / 100;
 	if (serverMajor < minServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
 					 serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
 	}
 	else if (serverMajor > maxServerMajor)
 	{
-		const char *serverver = PQparameterStatus(conn, "server_version");
+		const char *serverver = PQparameterStatus(myconn, "server_version");
 
 		pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
 					 serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
  * Note: The WAL location *must* be at a log segment start!
  */
 bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
 {
 	char		query[128];
 	char		slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 	 * The caller should've checked the server version already, but doesn't do
 	 * any harm to check it here too.
 	 */
-	if (!CheckServerVersionForStreaming(conn))
+	if (!CheckServerVersionForStreaming(myconn))
 		return false;
 
 	/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		/*
 		 * Get the server system identifier and timeline, and validate them.
 		 */
-		if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+		if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
 		{
 			pg_free(sysidentifier);
 			return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		if (!existsTimeLineHistoryFile(stream))
 		{
 			snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
-			res = PQexec(conn, query);
+			res = PQexec(myconn, query);
 			if (PQresultStatus(res) != PGRES_TUPLES_OK)
 			{
 				/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 				 slotcmd,
 				 LSN_FORMAT_ARGS(stream->startpos),
 				 stream->timeline);
-		res = PQexec(conn, query);
+		res = PQexec(myconn, query);
 		if (PQresultStatus(res) != PGRES_COPY_BOTH)
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 		PQclear(res);
 
 		/* Stream the WAL */
-		res = HandleCopyStream(conn, stream, &stoppos);
+		res = HandleCopyStream(myconn, stream, &stoppos);
 		if (res == NULL)
 			goto error;
 
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 			}
 
 			/* Read the final result, which should be CommandComplete. */
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 			if (PQresultStatus(res) != PGRES_COMMAND_OK)
 			{
 				pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
  * On any other sort of error, returns NULL.
  */
 static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
 				 XLogRecPtr *stoppos)
 {
 	char	   *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		/*
 		 * Check if we should continue streaming, or abort at this point.
 		 */
-		if (!CheckCopyStreamStop(conn, stream, blockpos))
+		if (!CheckCopyStreamStop(myconn, stream, blockpos))
 			goto error;
 
 		now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Send feedback so that the server sees the latest WAL locations
 			 * immediately.
 			 */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 										 stream->standby_message_timeout))
 		{
 			/* Time to send feedback! */
-			if (!sendFeedback(conn, blockpos, now, false))
+			if (!sendFeedback(myconn, blockpos, now, false))
 				goto error;
 			last_status = now;
 		}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 		PQfreemem(copybuf);
 		copybuf = NULL;
 
-		r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, &copybuf);
+		r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, &copybuf);
 		while (r != 0)
 		{
 			if (r == -1)
 				goto error;
 			if (r == -2)
 			{
-				PGresult   *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
+				PGresult   *res = HandleEndOfCopyStream(myconn, stream, copybuf, blockpos, stoppos);
 
 				if (res == NULL)
 					goto error;
@@ -826,20 +826,20 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			/* Check the message type. */
 			if (copybuf[0] == PqReplMsg_Keepalive)
 			{
-				if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
+				if (!ProcessKeepaliveMsg(myconn, stream, copybuf, r, blockpos,
 										 &last_status))
 					goto error;
 			}
 			else if (copybuf[0] == PqReplMsg_WALData)
 			{
-				if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
+				if (!ProcessWALDataMsg(myconn, stream, copybuf, r, &blockpos))
 					goto error;
 
 				/*
 				 * Check if we should continue streaming, or abort at this
 				 * point.
 				 */
-				if (!CheckCopyStreamStop(conn, stream, blockpos))
+				if (!CheckCopyStreamStop(myconn, stream, blockpos))
 					goto error;
 			}
 			else
@@ -857,7 +857,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
 			 * Process the received data, and any subsequent data we can read
 			 * without blocking.
 			 */
-			r = CopyStreamReceive(conn, 0, stream->stop_socket, &copybuf);
+			r = CopyStreamReceive(myconn, 0, stream->stop_socket, &copybuf);
 		}
 	}
 
@@ -875,7 +875,7 @@ error:
  * or interrupted by signal or stop_socket input, and -1 on an error.
  */
 static int
-CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
+CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket)
 {
 	int			ret;
 	fd_set		input_mask;
@@ -884,10 +884,10 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
 	struct timeval timeout;
 	struct timeval *timeoutptr;
 
-	connsocket = PQsocket(conn);
+	connsocket = PQsocket(myconn);
 	if (connsocket < 0)
 	{
-		pg_log_error("invalid socket: %s", PQerrorMessage(conn));
+		pg_log_error("invalid socket: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -937,7 +937,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
  * -1 on error. -2 if the server ended the COPY.
  */
 static int
-CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
 				  char **buffer)
 {
 	char	   *copybuf = NULL;
@@ -947,7 +947,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 	Assert(*buffer == NULL);
 
 	/* Try to receive a CopyData message */
-	rawlen = PQgetCopyData(conn, &copybuf, 1);
+	rawlen = PQgetCopyData(myconn, &copybuf, 1);
 	if (rawlen == 0)
 	{
 		int			ret;
@@ -957,20 +957,20 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		 * the specified timeout, so that we can ping the server.  Also stop
 		 * waiting if input appears on stop_socket.
 		 */
-		ret = CopyStreamPoll(conn, timeout, stop_socket);
+		ret = CopyStreamPoll(myconn, timeout, stop_socket);
 		if (ret <= 0)
 			return ret;
 
 		/* Now there is actually data on the socket */
-		if (PQconsumeInput(conn) == 0)
+		if (PQconsumeInput(myconn) == 0)
 		{
 			pg_log_error("could not receive data from WAL stream: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return -1;
 		}
 
 		/* Now that we've consumed some input, try again */
-		rawlen = PQgetCopyData(conn, &copybuf, 1);
+		rawlen = PQgetCopyData(myconn, &copybuf, 1);
 		if (rawlen == 0)
 			return 0;
 	}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
 		return -2;
 	if (rawlen == -2)
 	{
-		pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+		pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
 		return -1;
 	}
 
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
  * Process the keepalive message.
  */
 static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 					XLogRecPtr blockpos, TimestampTz *last_status)
 {
 	int			pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 		}
 
 		now = feGetCurrentTimestamp();
-		if (!sendFeedback(conn, blockpos, now, false))
+		if (!sendFeedback(myconn, blockpos, now, false))
 			return false;
 		*last_status = now;
 	}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Process WALData message.
  */
 static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
 				  XLogRecPtr *blockpos)
 {
 	int			xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
 			if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
 			{
-				if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+				if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 				{
 					pg_log_error("could not send copy-end packet: %s",
-								 PQerrorMessage(conn));
+								 PQerrorMessage(myconn));
 					return false;
 				}
 				still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
  * Handle end of the copy stream.
  */
 static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
 					  XLogRecPtr blockpos, XLogRecPtr *stoppos)
 {
-	PGresult   *res = PQgetResult(conn);
+	PGresult   *res = PQgetResult(myconn);
 
 	/*
 	 * The server closed its end of the copy stream.  If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
 		}
 		if (PQresultStatus(res) == PGRES_COPY_IN)
 		{
-			if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+			if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 			{
 				pg_log_error("could not send copy-end packet: %s",
-							 PQerrorMessage(conn));
+							 PQerrorMessage(myconn));
 				PQclear(res);
 				return NULL;
 			}
-			res = PQgetResult(conn);
+			res = PQgetResult(myconn);
 		}
 		still_sending = false;
 	}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
  * Check if we should continue streaming, or abort at this point.
  */
 static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
 {
 	if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
 	{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
 			/* Potential error message is written by close_walfile */
 			return false;
 		}
-		if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+		if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
 		{
 			pg_log_error("could not send copy-end packet: %s",
-						 PQerrorMessage(conn));
+						 PQerrorMessage(myconn));
 			return false;
 		}
 		still_sending = false;
diff --git a/src/bin/pg_basebackup/receivelog.h b/src/bin/pg_basebackup/receivelog.h
index 0caa904da6a..0378e4c20c8 100644
--- a/src/bin/pg_basebackup/receivelog.h
+++ b/src/bin/pg_basebackup/receivelog.h
@@ -50,8 +50,8 @@ typedef struct StreamCtl
 
 
 
-extern bool CheckServerVersionForStreaming(PGconn *conn);
-extern bool ReceiveXlogStream(PGconn *conn,
+extern bool CheckServerVersionForStreaming(PGconn *myconn);
+extern bool ReceiveXlogStream(PGconn *myconn,
 							  StreamCtl *stream);
 
 #endif							/* RECEIVELOG_H */
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index 76abdfa2ae6..31da309d587 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
 
 int			WalSegSz;
 
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
 
 /* SHOW command for replication connection was introduced in version 10 */
 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
  * since ControlFile is not accessible here.
  */
 bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
 {
 	PGresult   *res;
 	char		xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
 				multiplier = 1;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions set the default xlog seg size */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
 	{
 		WalSegSz = DEFAULT_XLOG_SEG_SIZE;
 		return true;
 	}
 
-	res = PQexec(conn, "SHOW wal_segment_size");
+	res = PQexec(myconn, "SHOW wal_segment_size");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW wal_segment_size", PQerrorMessage(conn));
+					 "SHOW wal_segment_size", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
  * on the data directory.
  */
 static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
 {
 	PGresult   *res;
 	int			data_directory_mode;
 
 	/* check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
 	/* for previous versions leave the default group access */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+	if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
 		return true;
 
-	res = PQexec(conn, "SHOW data_directory_mode");
+	res = PQexec(myconn, "SHOW data_directory_mode");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "SHOW data_directory_mode", PQerrorMessage(conn));
+					 "SHOW data_directory_mode", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
  * - Database name (NULL in servers prior to 9.4)
  */
 bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
 				  XLogRecPtr *startpos, char **db_name)
 {
 	PGresult   *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 				lo;
 
 	/* Check connection existence */
-	Assert(conn != NULL);
+	Assert(myconn != NULL);
 
-	res = PQexec(conn, "IDENTIFY_SYSTEM");
+	res = PQexec(myconn, "IDENTIFY_SYSTEM");
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+					 "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
 
 		PQclear(res);
 		return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	if (db_name != NULL)
 	{
 		*db_name = NULL;
-		if (PQserverVersion(conn) >= 90400)
+		if (PQserverVersion(myconn) >= 90400)
 		{
 			if (PQnfields(res) < 4)
 			{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * Returns false on failure, and true otherwise.
  */
 bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
 				   XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
 {
 	PGresult   *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
 
 	query = createPQExpBuffer();
 	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	destroyPQExpBuffer(query);
 
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+					 "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
 		PQclear(res);
 		return false;
 	}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
  * returns true in case of success.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
 					  bool is_temporary, bool is_physical, bool reserve_wal,
 					  bool slot_exists_ok, bool two_phase, bool failover)
 {
 	PQExpBuffer query;
 	PGresult   *res;
-	bool		use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+	bool		use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
 
 	query = createPQExpBuffer();
 
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 	else
 	{
-		if (failover && PQserverVersion(conn) >= 170000)
+		if (failover && PQserverVersion(myconn) >= 170000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "FAILOVER");
 
-		if (two_phase && PQserverVersion(conn) >= 150000)
+		if (two_phase && PQserverVersion(myconn) >= 150000)
 			AppendPlainCommandOption(query, use_new_option_syntax,
 									 "TWO_PHASE");
 
-		if (PQserverVersion(conn) >= 100000)
+		if (PQserverVersion(myconn) >= 100000)
 		{
 			/* pg_recvlogical doesn't use an exported snapshot, so suppress */
 			if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 	}
 
 	/* Now run the query */
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 		else
 		{
 			pg_log_error("could not send replication command \"%s\": %s",
-						 query->data, PQerrorMessage(conn));
+						 query->data, PQerrorMessage(myconn));
 
 			destroyPQExpBuffer(query);
 			PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 	/* Build query */
 	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
 					  slot_name);
-	res = PQexec(conn, query->data);
+	res = PQexec(myconn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		pg_log_error("could not send replication command \"%s\": %s",
-					 query->data, PQerrorMessage(conn));
+					 query->data, PQerrorMessage(myconn));
 
 		destroyPQExpBuffer(query);
 		PQclear(res);
diff --git a/src/bin/pg_basebackup/streamutil.h b/src/bin/pg_basebackup/streamutil.h
index 15afef3a9c8..69ae24f94ed 100644
--- a/src/bin/pg_basebackup/streamutil.h
+++ b/src/bin/pg_basebackup/streamutil.h
@@ -32,13 +32,13 @@ extern PGconn *conn;
 extern PGconn *GetConnection(void);
 
 /* Replication commands */
-extern bool CreateReplicationSlot(PGconn *conn, const char *slot_name,
+extern bool CreateReplicationSlot(PGconn *myconn, const char *slot_name,
 								  const char *plugin, bool is_temporary,
 								  bool is_physical, bool reserve_wal,
 								  bool slot_exists_ok, bool two_phase,
 								  bool failover);
-extern bool DropReplicationSlot(PGconn *conn, const char *slot_name);
-extern bool RunIdentifySystem(PGconn *conn, char **sysid,
+extern bool DropReplicationSlot(PGconn *myconn, const char *slot_name);
+extern bool RunIdentifySystem(PGconn *myconn, char **sysid,
 							  TimeLineID *starttli,
 							  XLogRecPtr *startpos,
 							  char **db_name);
@@ -53,10 +53,10 @@ extern void AppendIntegerCommandOption(PQExpBuffer buf,
 									   bool use_new_option_syntax,
 									   char *option_name, int32 option_value);
 
-extern bool GetSlotInformation(PGconn *conn, const char *slot_name,
+extern bool GetSlotInformation(PGconn *myconn, const char *slot_name,
 							   XLogRecPtr *restart_lsn,
 							   TimeLineID *restart_tli);
-extern bool RetrieveWalSegSize(PGconn *conn);
+extern bool RetrieveWalSegSize(PGconn *myconn);
 extern TimestampTz feGetCurrentTimestamp(void);
 extern void feTimestampDifference(TimestampTz start_time, TimestampTz stop_time,
 								  long *secs, int *microsecs);
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 10-v8-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From 581fc3abe5896c19b278827f433dd9b072098794 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v8 09/12] cleanup: avoid local variables shadowed by globals
 in ecpg.header

This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
 }
 
 static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
 {
 	/*
 	 * Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		struct variable *newvar,
 				   *newind;
 
-		list = (insert ? cur->argsinsert : cur->argsresult);
+		list = (insert ? pcur->argsinsert : pcur->argsresult);
 
 		for (ptr = list; ptr != NULL; ptr = ptr->next)
 		{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
 		}
 
 		if (insert)
-			cur->argsinsert_oos = newlist;
+			pcur->argsinsert_oos = newlist;
 		else
-			cur->argsresult_oos = newlist;
+			pcur->argsresult_oos = newlist;
 	}
 
 	return result;
@@ -490,7 +490,7 @@ static void
 add_typedef(const char *name, const char *dimension, const char *length,
 			enum ECPGttype type_enum,
 			const char *type_dimension, const char *type_index,
-			int initializer, int array)
+			int initial_value, int array)
 {
 	/* add entry to list */
 	struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
-		initializer == 1)
+		initial_value == 1)
 		mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
 	else if (INFORMIX_MODE && strcmp(name, "string") == 0)
 		mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0010-cleanup-avoid-local-variables-shadowed-by-globals.patch (21.9K, 11-v8-0010-cleanup-avoid-local-variables-shadowed-by-globals.patch)
  download | inline diff:
From aca8c2042a2113b16e29b3d75859e479811505a0 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v8 10/12] cleanup: avoid local variables shadowed by globals
 across time-related modules

This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.

A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/utils/adt/date.c       | 20 +++----
 src/backend/utils/adt/datetime.c   | 20 +++----
 src/backend/utils/adt/formatting.c |  8 +--
 src/backend/utils/adt/timestamp.c  | 92 +++++++++++++++---------------
 src/bin/initdb/findtimezone.c      | 38 ++++++------
 src/include/pgtime.h               |  2 +-
 src/include/utils/datetime.h       |  4 +-
 src/timezone/pgtz.c                | 16 +++---
 8 files changed, 100 insertions(+), 100 deletions(-)

diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c3327440380..2534dba55bb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -562,16 +562,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -586,16 +586,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		dayVal = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - dayVal;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3152,7 +3152,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 	TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
 	TimeTzADT  *result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -3160,9 +3160,9 @@ timetz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -3175,7 +3175,7 @@ timetz_zone(PG_FUNCTION_ARGS)
 		TimestampTz now = GetCurrentTransactionStartTimestamp();
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
 	}
 	else
 	{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 8f25c15fcfc..072eda02900 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -643,12 +643,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
 static bool
 AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
 {
-	int			days;
+	int			dayVal;
 
 	if (val < INT_MIN || val > INT_MAX)
 		return false;
-	return !pg_mul_s32_overflow((int32) val, scale, &days) &&
-		!pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+	return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+		!pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
 }
 
 /*
@@ -3286,7 +3286,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
  * the zone name or the abbreviation's underlying zone.
  */
 int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
 {
 	char	   *lowzone;
 	int			dterr,
@@ -3303,8 +3303,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	 */
 
 	/* DecodeTimezoneAbbrev requires lowercase input */
-	lowzone = downcase_truncate_identifier(tzname,
-										   strlen(tzname),
+	lowzone = downcase_truncate_identifier(tz_name,
+										   strlen(tz_name),
 										   false);
 
 	dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3324,11 +3324,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
 	else
 	{
 		/* try it as a full zone name */
-		*tz = pg_tzset(tzname);
+		*tz = pg_tzset(tz_name);
 		if (*tz == NULL)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 		return TZNAME_ZONE;
 	}
 }
@@ -3341,12 +3341,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
  * result in all cases.
  */
 pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
 {
 	pg_tz	   *result;
 	int			offset;
 
-	if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+	if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
 	{
 		/* fixed-offset abbreviation, get a pg_tz descriptor for that */
 		result = pg_tzset_offset(-offset);	/* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 0716aff22b6..1c0e5566301 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3034,12 +3034,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 				else
 				{
 					int			mon = 0;
-					const char *const *months;
+					const char *const *pmonths;
 
 					if (n->key->id == DCH_RM)
-						months = rm_months_upper;
+						pmonths = rm_months_upper;
 					else
-						months = rm_months_lower;
+						pmonths = rm_months_lower;
 
 					/*
 					 * Compute the position in the roman-numeral array.  Note
@@ -3074,7 +3074,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					}
 
 					sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
-							months[mon]);
+							pmonths[mon]);
 					s += strlen(s);
 				}
 				break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 288d696be77..0cd37997014 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -482,11 +482,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
 static int
 parse_sane_timezone(struct pg_tm *tm, text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			dterr;
 	int			tz;
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
 	/*
 	 * Look up the requested timezone.  First we try to interpret it as a
@@ -498,14 +498,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 	 * as invalid, it's enough to disallow having a digit in the first
 	 * position of our input string.
 	 */
-	if (isdigit((unsigned char) *tzname))
+	if (isdigit((unsigned char) *tz_name))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("invalid input syntax for type %s: \"%s\"",
-						"numeric time zone", tzname),
+						"numeric time zone", tz_name),
 				 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
 
-	dterr = DecodeTimezone(tzname, &tz);
+	dterr = DecodeTimezone(tz_name, &tz);
 	if (dterr != 0)
 	{
 		int			type,
@@ -515,13 +515,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		if (dterr == DTERR_TZDISP_OVERFLOW)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("numeric time zone \"%s\" out of range", tzname)));
+					 errmsg("numeric time zone \"%s\" out of range", tz_name)));
 		else if (dterr != DTERR_BAD_FORMAT)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("time zone \"%s\" not recognized", tzname)));
+					 errmsg("time zone \"%s\" not recognized", tz_name)));
 
-		type = DecodeTimezoneName(tzname, &val, &tzp);
+		type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 		if (type == TZNAME_FIXED_OFFSET)
 		{
@@ -531,7 +531,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 		else if (type == TZNAME_DYNTZ)
 		{
 			/* dynamic-offset abbreviation, resolve using specified time */
-			tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+			tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
 		}
 		else
 		{
@@ -551,11 +551,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
 static pg_tz *
 lookup_timezone(text *zone)
 {
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	return DecodeTimezoneNameToTz(tzname);
+	return DecodeTimezoneNameToTz(tz_name);
 }
 
 /*
@@ -1523,41 +1523,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
 Datum
 make_interval(PG_FUNCTION_ARGS)
 {
-	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
-	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
-	int32		hours = PG_GETARG_INT32(4);
-	int32		mins = PG_GETARG_INT32(5);
-	double		secs = PG_GETARG_FLOAT8(6);
+	int32		yearVal = PG_GETARG_INT32(0);
+	int32		monthVal = PG_GETARG_INT32(1);
+	int32		weekVal = PG_GETARG_INT32(2);
+	int32		dayVal = PG_GETARG_INT32(3);
+	int32		hourVal = PG_GETARG_INT32(4);
+	int32		minVal = PG_GETARG_INT32(5);
+	double		secVal = PG_GETARG_FLOAT8(6);
 	Interval   *result;
 
 	/*
 	 * Reject out-of-range inputs.  We reject any input values that cause
 	 * integer overflow of the corresponding interval fields.
 	 */
-	if (isinf(secs) || isnan(secs))
+	if (isinf(secVal) || isnan(secVal))
 		goto out_of_range;
 
 	result = palloc_object(Interval);
 
 	/* years and months -> months */
-	if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
-		pg_add_s32_overflow(result->month, months, &result->month))
+	if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+		pg_add_s32_overflow(result->month, monthVal, &result->month))
 		goto out_of_range;
 
 	/* weeks and days -> days */
-	if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
-		pg_add_s32_overflow(result->day, days, &result->day))
+	if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+		pg_add_s32_overflow(result->day, dayVal, &result->day))
 		goto out_of_range;
 
 	/* hours and mins -> usecs (cannot overflow 64-bit) */
-	result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+	result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
 
 	/* secs -> usecs */
-	secs = rint(float8_mul(secs, USECS_PER_SEC));
-	if (!FLOAT8_FITS_IN_INT64(secs) ||
-		pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+	secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+	if (!FLOAT8_FITS_IN_INT64(secVal) ||
+		pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
 		goto out_of_range;
 
 	/* make sure that the result is finite */
@@ -2125,9 +2125,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
 }
 
 static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
 {
-	dt -= (timezone * USECS_PER_SEC);
+	dt -= (tz * USECS_PER_SEC);
 	return dt;
 }
 
@@ -2518,20 +2518,20 @@ static inline INT128
 interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
-	int64		days;
+	int64		dayVal;
 
 	/*
 	 * Combine the month and day fields into an integral number of days.
 	 * Because the inputs are int32, int64 arithmetic suffices here.
 	 */
-	days = interval->month * INT64CONST(30);
-	days += interval->day;
+	dayVal = interval->month * INT64CONST(30);
+	dayVal += interval->day;
 
 	/* Widen time field to 128 bits */
 	span = int64_to_int128(interval->time);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
 
 	return span;
 }
@@ -6216,7 +6216,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 		{
 			Numeric		result;
 			int64		secs_from_day_month;
-			int64		val;
+			int64		value;
 
 			/*
 			 * To do this calculation in integer arithmetic even though
@@ -6239,9 +6239,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
 			 * numeric (slower).  This overflow happens around 10^9 days, so
 			 * not common in practice.
 			 */
-			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
-				!pg_add_s64_overflow(val, interval->time, &val))
-				result = int64_div_fast_to_numeric(val, 6);
+			if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+				!pg_add_s64_overflow(value, interval->time, &value))
+				result = int64_div_fast_to_numeric(value, 6);
 			else
 				result =
 					numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6305,7 +6305,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	Timestamp	timestamp = PG_GETARG_TIMESTAMP(1);
 	TimestampTz result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6318,9 +6318,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6335,7 +6335,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
 					 errmsg("timestamp out of range")));
-		tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+		tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
 		result = dt2local(timestamp, tz);
 	}
 	else
@@ -6570,7 +6570,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
 	Timestamp	result;
 	int			tz;
-	char		tzname[TZ_STRLEN_MAX + 1];
+	char		tz_name[TZ_STRLEN_MAX + 1];
 	int			type,
 				val;
 	pg_tz	   *tzp;
@@ -6581,9 +6581,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 	/*
 	 * Look up the requested timezone.
 	 */
-	text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+	text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
 
-	type = DecodeTimezoneName(tzname, &val, &tzp);
+	type = DecodeTimezoneName(tz_name, &val, &tzp);
 
 	if (type == TZNAME_FIXED_OFFSET)
 	{
@@ -6596,7 +6596,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
 		/* dynamic-offset abbreviation, resolve using specified time */
 		int			isdst;
 
-		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+		tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
 		result = dt2local(timestamp, tz);
 	}
 	else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 910b97a570b..1c45a4ecd38 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
  * test time.
  */
 static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
 {
 	int			i;
 	pg_time_t	pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	pg_tz	   *tz;
 
 	/* Load timezone definition */
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(tz_name);
 	if (!tz)
 		return -1;				/* unrecognized zone name */
 
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	if (!pg_tz_acceptable(tz))
 	{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+		fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
 #endif
 		return -1;
 	}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 		{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 			fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
-					tzname, i, (long) pgtt,
+					tz_name, i, (long) pgtt,
 					pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
 					pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
 					pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 			{
 #ifdef DEBUG_IDENTIFY_TIMEZONE
 				fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
-						tzname, i, (long) pgtt,
+						tz_name, i, (long) pgtt,
 						pgtm->tm_zone, cbuf);
 #endif
 				return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
 	}
 
 #ifdef DEBUG_IDENTIFY_TIMEZONE
-	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+	fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
 #endif
 
 	return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
  * Test whether given zone name is a perfect match to localtime() behavior
  */
 static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
 {
-	return (score_timezone(tzname, tt) == tt->n_test_times);
+	return (score_timezone(tz_name, tt) == tt->n_test_times);
 }
 
 
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
  * Return true if the given zone name is valid and is an "acceptable" zone.
  */
 static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
 {
 	pg_tz	   *tz;
 
-	if (!tzname || !tzname[0])
+	if (!zone || !zone[0])
 		return false;
 
-	tz = pg_load_tz(tzname);
+	tz = pg_load_tz(zone);
 	if (!tz)
 		return false;
 
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
 const char *
 select_default_timezone(const char *share_path)
 {
-	const char *tzname;
+	const char *tz;
 
 	/* Initialize timezone directory path, if needed */
 #ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
 #endif
 
 	/* Check TZ environment variable */
-	tzname = getenv("TZ");
-	if (validate_zone(tzname))
-		return tzname;
+	tz = getenv("TZ");
+	if (validate_zone(tz))
+		return tz;
 
 	/* Nope, so try to identify the system timezone */
-	tzname = identify_system_timezone();
-	if (validate_zone(tzname))
-		return tzname;
+	tz = identify_system_timezone();
+	if (validate_zone(tz))
+		return tz;
 
 	return NULL;
 }
diff --git a/src/include/pgtime.h b/src/include/pgtime.h
index ba6705f71bd..458b4300a63 100644
--- a/src/include/pgtime.h
+++ b/src/include/pgtime.h
@@ -91,7 +91,7 @@ extern PGDLLIMPORT pg_tz *session_timezone;
 extern PGDLLIMPORT pg_tz *log_timezone;
 
 extern void pg_timezone_initialize(void);
-extern pg_tz *pg_tzset(const char *tzname);
+extern pg_tz *pg_tzset(const char *zone);
 extern pg_tz *pg_tzset_offset(long gmtoffset);
 
 extern pg_tzenum *pg_tzenumerate_start(void);
diff --git a/src/include/utils/datetime.h b/src/include/utils/datetime.h
index f77c6acd8b6..abdaaaccb45 100644
--- a/src/include/utils/datetime.h
+++ b/src/include/utils/datetime.h
@@ -345,8 +345,8 @@ extern int	DecodeTimezoneAbbrev(int field, const char *lowtoken,
 extern int	DecodeSpecial(int field, const char *lowtoken, int *val);
 extern int	DecodeUnits(int field, const char *lowtoken, int *val);
 
-extern int	DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz);
-extern pg_tz *DecodeTimezoneNameToTz(const char *tzname);
+extern int	DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz);
+extern pg_tz *DecodeTimezoneNameToTz(const char *tz_name);
 
 extern int	DecodeTimezoneAbbrevPrefix(const char *str,
 									   int *offset, pg_tz **tz);
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index eac988c21e7..72f41ea42d8 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
  * default timezone setting is later overridden from postgresql.conf.
  */
 pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
 {
 	pg_tz_cache *tzp;
 	struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
 	char		canonname[TZ_STRLEN_MAX + 1];
 	char	   *p;
 
-	if (strlen(tzname) > TZ_STRLEN_MAX)
+	if (strlen(zone) > TZ_STRLEN_MAX)
 		return NULL;			/* not going to fit */
 
 	if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
 	 * a POSIX-style timezone spec.)
 	 */
 	p = uppername;
-	while (*tzname)
-		*p++ = pg_toupper((unsigned char) *tzname++);
+	while (*zone)
+		*p++ = pg_toupper((unsigned char) *zone++);
 	*p = '\0';
 
 	tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
 {
 	long		absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
 	char		offsetstr[64];
-	char		tzname[128];
+	char		zone[128];
 
 	snprintf(offsetstr, sizeof(offsetstr),
 			 "%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
 					 ":%02ld", absoffset);
 	}
 	if (gmtoffset > 0)
-		snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+		snprintf(zone, sizeof(zone), "<-%s>+%s",
 				 offsetstr, offsetstr);
 	else
-		snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+		snprintf(zone, sizeof(zone), "<+%s>-%s",
 				 offsetstr, offsetstr);
 
-	return pg_tzset(tzname);
+	return pg_tzset(zone);
 }
 
 
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0011-cleanup-rename-local-progname-variables-to-avoid-.patch (25.4K, 12-v8-0011-cleanup-rename-local-progname-variables-to-avoid-.patch)
  download | inline diff:
From 4b2fdbf960aa406685b2d053de9b43315b539b1f Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v8 11/12] cleanup: rename local progname variables to avoid
 shadowing the global

This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.

A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.

Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/main/main.c                     | 14 ++--
 src/bin/initdb/initdb.c                     | 60 +++++++-------
 src/bin/pg_amcheck/pg_amcheck.c             |  6 +-
 src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
 src/bin/pg_dump/connectdb.c                 |  4 +-
 src/bin/pg_dump/pg_dump.c                   | 90 ++++++++++-----------
 src/bin/pg_dump/pg_restore.c                |  4 +-
 src/bin/pg_rewind/pg_rewind.c               | 22 ++---
 src/interfaces/ecpg/preproc/ecpg.c          |  6 +-
 10 files changed, 114 insertions(+), 114 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index b0dcd9876c5..4a4dde82655 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -237,7 +237,7 @@ void
 BootstrapModeMain(int argc, char *argv[], bool check_only)
 {
 	int			i;
-	char	   *progname = argv[0];
+	char	   *myprogname = argv[0];
 	pg_getopt_ctx optctx;
 	int			flag;
 	char	   *userDoption = NULL;
@@ -335,7 +335,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 				break;
 			default:
 				write_stderr("Try \"%s --help\" for more information.\n",
-							 progname);
+							 myprogname);
 				proc_exit(1);
 				break;
 		}
@@ -343,12 +343,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 
 	if (argc != optctx.optind)
 	{
-		write_stderr("%s: invalid command-line arguments\n", progname);
+		write_stderr("%s: invalid command-line arguments\n", myprogname);
 		proc_exit(1);
 	}
 
 	/* Acquire configuration parameters */
-	if (!SelectConfigFiles(userDoption, progname))
+	if (!SelectConfigFiles(userDoption, myprogname))
 		proc_exit(1);
 
 	/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 7b9b602f3c4..5bf4c4f4774 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 myprogname, err);
 			exit(1);
 		}
 
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *myprogname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 myprogname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 14cb79c26be..158e6a2d005 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -828,7 +828,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -839,9 +839,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user);
 }
 
 static char *
@@ -1062,14 +1062,14 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 		pg_fatal("could not open file \"%s\" for writing: %m", path);
-	if (fclose(conf_file))
+	if (fclose(file))
 		pg_fatal("could not write file \"%s\": %m", path);
 	free(path);
 }
@@ -2163,7 +2163,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2178,7 +2178,7 @@ locale_date_order(const char *locale)
 
 	save = save_global_locale(LC_TIME);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, mylocale);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2222,14 +2222,14 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
 {
 	save_locale_t save;
 	char	   *res;
 
 	/* Don't let Windows' non-ASCII locale names in. */
-	if (locale && !pg_is_ascii(locale))
-		pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+	if (mylocale && !pg_is_ascii(mylocale))
+		pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
 
 	if (canonname)
 		*canonname = NULL;		/* in case of failure */
@@ -2237,11 +2237,11 @@ check_locale_name(int category, const char *locale, char **canonname)
 	save = save_global_locale(category);
 
 	/* for setlocale() call */
-	if (!locale)
-		locale = "";
+	if (!mylocale)
+		mylocale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, mylocale);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2253,9 +2253,9 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
+		if (*mylocale)
 		{
-			pg_log_error("invalid locale name \"%s\"", locale);
+			pg_log_error("invalid locale name \"%s\"", mylocale);
 			pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
 			exit(1);
 		}
@@ -2285,11 +2285,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(mylocale, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2537,11 +2537,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), myprogname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2617,14 +2617,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+	if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+		 strcmp(myauthmethodlocal, "password") == 0 ||
+		 strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+		(strcmp(myauthmethodhost, "md5") == 0 ||
+		 strcmp(myauthmethodhost, "password") == 0 ||
+		 strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 		pg_fatal("must specify a password for the superuser to enable password authentication");
 }
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 09ba0596400..22bf0fa9dcb 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
  * progname: the name of the executed program, such as "pg_amcheck"
  */
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+	printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 	printf(_("\nTarget options:\n"));
 	printf(_("  -a, --all                       check all databases\n"));
 	printf(_("  -d, --database=PATTERN          check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 15e06e5686e..0676944f9cd 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -411,32 +411,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
  * path of the progname.
  */
 static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
 {
 	char	   *versionstr;
 	char	   *exec_path;
 	int			ret;
 
-	versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+	versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
 	exec_path = pg_malloc(MAXPGPATH);
-	ret = find_other_exec(argv0, progname, versionstr, exec_path);
+	ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
 
 	if (ret < 0)
 	{
 		char		full_path[MAXPGPATH];
 
 		if (find_my_exec(argv0, full_path) < 0)
-			strlcpy(full_path, progname, sizeof(full_path));
+			strlcpy(full_path, myprogname, sizeof(full_path));
 
 		if (ret == -1)
 			pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
-					 progname, "pg_createsubscriber", full_path);
+					 myprogname, "pg_createsubscriber", full_path);
 		else
 			pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
-					 progname, full_path, "pg_createsubscriber");
+					 myprogname, full_path, "pg_createsubscriber");
 	}
 
-	pg_log_debug("%s path is:  %s", progname, exec_path);
+	pg_log_debug("%s path is:  %s", myprogname, exec_path);
 
 	return exec_path;
 }
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index f3ce8b1cfb1..f2833fb9b25 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
 PGconn *
 ConnectDatabase(const char *dbname, const char *connection_string,
 				const char *pghost, const char *pgport, const char *pguser,
-				trivalue prompt_password, bool fail_on_error, const char *progname,
+				trivalue prompt_password, bool fail_on_error, const char *myprogname,
 				const char **connstr, int *server_version, char *password,
 				char *override_dbname)
 {
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
 	{
 		pg_log_error("aborting because of server version mismatch");
 		pg_log_error_detail("server version: %s; %s version: %s",
-							remoteversion_str, progname, PG_VERSION);
+							remoteversion_str, myprogname, PG_VERSION);
 		exit_nicely(1);
 	}
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 1ca03d6b278..4c892b9fcc4 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1288,11 +1288,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
-	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+	printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1647,7 +1647,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1683,7 +1683,7 @@ expand_schema_name_patterns(Archive *fout,
 		termPQExpBuffer(&dbbuf);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1706,7 +1706,7 @@ static void
 expand_extension_name_patterns(Archive *fout,
 							   SimpleStringList *patterns,
 							   SimpleOidList *oids,
-							   bool strict_names)
+							   bool strict)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1736,7 +1736,7 @@ expand_extension_name_patterns(Archive *fout,
 					 cell->val);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1810,7 +1810,7 @@ expand_foreign_server_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names, bool with_child_tables)
+						   bool strict, bool with_child_tables)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1882,7 +1882,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strict && PQntuples(res) == 0)
 			pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -11002,8 +11002,8 @@ dumpCommentExtended(Archive *fout, const char *type,
 					const char *initdb_comment)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 
 	/* do nothing, if --no-comments is supplied */
 	if (dopt->no_comments)
@@ -11023,16 +11023,16 @@ dumpCommentExtended(Archive *fout, const char *type,
 	}
 
 	/* Search for comments associated with catalogId, using table */
-	ncomments = findComments(catalogId.tableoid, catalogId.oid,
-							 &comments);
+	n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+								   &comment_items);
 
 	/* Is there one matching the subid? */
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		if (comments->objsubid == subid)
+		if (comment_items->objsubid == subid)
 			break;
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	if (initdb_comment != NULL)
@@ -11045,17 +11045,17 @@ dumpCommentExtended(Archive *fout, const char *type,
 		 * non-superuser use of pg_dump.  When the DBA has removed initdb's
 		 * comment, replicate that.
 		 */
-		if (ncomments == 0)
+		if (n_comment_items == 0)
 		{
-			comments = &empty_comment;
-			ncomments = 1;
+			comment_items = &empty_comment;
+			n_comment_items = 1;
 		}
-		else if (strcmp(comments->descr, initdb_comment) == 0)
-			ncomments = 0;
+		else if (strcmp(comment_items->descr, initdb_comment) == 0)
+			n_comment_items = 0;
 	}
 
 	/* If a comment exists, build COMMENT ON statement */
-	if (ncomments > 0)
+	if (n_comment_items > 0)
 	{
 		PQExpBuffer query = createPQExpBuffer();
 		PQExpBuffer tag = createPQExpBuffer();
@@ -11064,7 +11064,7 @@ dumpCommentExtended(Archive *fout, const char *type,
 		if (namespace && *namespace)
 			appendPQExpBuffer(query, "%s.", fmtId(namespace));
 		appendPQExpBuffer(query, "%s IS ", name);
-		appendStringLiteralAH(query, comments->descr, fout);
+		appendStringLiteralAH(query, comment_items->descr, fout);
 		appendPQExpBufferStr(query, ";\n");
 
 		appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11560,8 +11560,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 				 const char *reltypename)
 {
 	DumpOptions *dopt = fout->dopt;
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer tag;
 
@@ -11574,21 +11574,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 		return;
 
 	/* Search for comments associated with relation, using table */
-	ncomments = findComments(tbinfo->dobj.catId.tableoid,
-							 tbinfo->dobj.catId.oid,
-							 &comments);
+	n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+								   tbinfo->dobj.catId.oid,
+								   &comment_items);
 
 	/* If comments exist, build COMMENT ON statements */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	query = createPQExpBuffer();
 	tag = createPQExpBuffer();
 
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
-		const char *descr = comments->descr;
-		int			objsubid = comments->objsubid;
+		const char *descr = comment_items->descr;
+		int			objsubid = comment_items->objsubid;
 
 		if (objsubid == 0)
 		{
@@ -11638,8 +11638,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
@@ -13289,8 +13289,8 @@ static void
 dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 							 PGresult *res)
 {
-	CommentItem *comments;
-	int			ncomments;
+	CommentItem *comment_items;
+	int			n_comment_items;
 	PQExpBuffer query;
 	PQExpBuffer target;
 	int			i;
@@ -13304,11 +13304,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		return;
 
 	/* Search for comments associated with type's pg_class OID */
-	ncomments = findComments(RelationRelationId, tyinfo->typrelid,
-							 &comments);
+	n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+								   &comment_items);
 
 	/* If no comments exist, we're done */
-	if (ncomments <= 0)
+	if (n_comment_items <= 0)
 		return;
 
 	/* Build COMMENT ON statements */
@@ -13319,14 +13319,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 	i_attnum = PQfnumber(res, "attnum");
 	i_attname = PQfnumber(res, "attname");
 	i_attisdropped = PQfnumber(res, "attisdropped");
-	while (ncomments > 0)
+	while (n_comment_items > 0)
 	{
 		const char *attname;
 
 		attname = NULL;
 		for (i = 0; i < ntups; i++)
 		{
-			if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+			if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
 				PQgetvalue(res, i, i_attisdropped)[0] != 't')
 			{
 				attname = PQgetvalue(res, i, i_attname);
@@ -13335,7 +13335,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 		}
 		if (attname)			/* just in case we don't find it */
 		{
-			const char *descr = comments->descr;
+			const char *descr = comment_items->descr;
 
 			resetPQExpBuffer(target);
 			appendPQExpBuffer(target, "COLUMN %s.",
@@ -13360,8 +13360,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
 									  .nDeps = 1));
 		}
 
-		comments++;
-		ncomments--;
+		comment_items++;
+		n_comment_items--;
 	}
 
 	destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index f016b336308..327ce8053b0 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -743,11 +743,11 @@ restore_one_database(const char *inputFileSpec, RestoreOptions *opts,
 }
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
 	printf(_("%s restores PostgreSQL databases from archives created by pg_dump or pg_dumpall.\n\n"), progname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), myprogname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index 9d745d4b25b..c3bdec41526 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
 static rewind_source *source;
 
 static void
-usage(const char *progname)
+usage(const char *myprogname)
 {
-	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+	printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
 	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
 	printf(_("Options:\n"));
 	printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
  * target and the source.
  */
 static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
 			   XLogRecPtr chkptrec,
 			   TimeLineID chkpttli,
 			   XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			while (datapagemap_next(iter, &blkno))
 			{
 				offset = blkno * BLCKSZ;
-				source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+				rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
 			}
 			pg_free(iter);
 		}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY:
-				source->queue_fetch_file(source, entry->path, entry->source_size);
+				rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
 				break;
 
 			case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 				break;
 
 			case FILE_ACTION_COPY_TAIL:
-				source->queue_fetch_range(source, entry->path,
-										  entry->target_size,
-										  entry->source_size - entry->target_size);
+				rewindsource->queue_fetch_range(rewindsource, entry->path,
+												entry->target_size,
+												entry->source_size - entry->target_size);
 				break;
 
 			case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	}
 
 	/* Complete any remaining range-fetches that we queued up above. */
-	source->finish_fetch(source);
+	rewindsource->finish_fetch(rewindsource);
 
 	close_target_file();
 
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 	 * Fetch the control file from the source last. This ensures that the
 	 * minRecoveryPoint is up-to-date.
 	 */
-	buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+	buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
 	digestControlFile(&ControlFile_source_after, buffer, size);
 	pg_free(buffer);
 
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
 			if (ControlFile_source_after.state != DB_IN_PRODUCTION)
 				pg_fatal("source system was in unexpected state at end of rewind");
 
-			endrec = source->get_current_wal_insert_lsn(source);
+			endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
 			endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
 						 ControlFile_source_after.minRecoveryPointTLI);
 		}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 1db55be473f..77b3599e1d6 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
 struct declared_list *g_declared_list = NULL;
 
 static void
-help(const char *progname)
+help(const char *myprogname)
 {
 	printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Usage:\n"
 			 "  %s [OPTION]... FILE...\n\n"),
-		   progname);
+		   myprogname);
 	printf(_("Options:\n"));
 	printf(_("  -c             automatically generate C code from embedded SQL code;\n"
 			 "                 this affects EXEC SQL TYPE\n"));
-- 
2.50.1 (Apple Git-155)



  [application/octet-stream] v8-0012-WIP-xlogrecovery-consolidate-file-local-mutable-s.patch (29.8K, 13-v8-0012-WIP-xlogrecovery-consolidate-file-local-mutable-s.patch)
  download | inline diff:
From 1e6a069f444280afed133b532449125be7cb2008 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 4 Mar 2026 12:42:12 +0800
Subject: [PATCH v8 12/12] WIP: xlogrecovery: consolidate file-local mutable
 state

---
 src/backend/access/transam/xlogrecovery.c | 390 ++++++++++++++--------
 1 file changed, 253 insertions(+), 137 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index c236e2b7969..f17d6558b90 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -107,25 +107,10 @@ bool		wal_receiver_create_temp_slot = false;
  * recoveryTargetTLIRequested: numeric value of requested timeline, if constant
  *
  * recoveryTargetTLI: the currently understood target timeline; changes
- *
- * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and
- * the timelines of its known parents, newest first (so recoveryTargetTLI is
- * always the first list member).  Only these TLIs are expected to be seen in
- * the WAL segments we read, and indeed only these TLIs will be considered as
- * candidate WAL files to open at all.
- *
- * curFileTLI: the TLI appearing in the name of the current input WAL file.
- * (This is not necessarily the same as the timeline from which we are
- * replaying WAL, which StartupXLOG calls replayTLI, because we could be
- * scanning data that was copied from an ancestor timeline when the current
- * file was created.)  During a sequential scan we do not allow this value
- * to decrease.
  */
 RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal = RECOVERY_TARGET_TIMELINE_LATEST;
 TimeLineID	recoveryTargetTLIRequested = 0;
 TimeLineID	recoveryTargetTLI = 0;
-static List *expectedTLEs;
-static TimeLineID curFileTLI;
 
 /*
  * When ArchiveRecoveryRequested is set, archive recovery was requested,
@@ -147,53 +132,12 @@ bool		InArchiveRecovery = false;
  * in standby mode.  These variables are only valid in the startup process.
  * They work similarly to ArchiveRecoveryRequested and InArchiveRecovery.
  */
-static bool StandbyModeRequested = false;
 bool		StandbyMode = false;
 
 /* was a signal file present at startup? */
 static bool standby_signal_file_found = false;
 static bool recovery_signal_file_found = false;
 
-/*
- * CheckPointLoc is the position of the checkpoint record that determines
- * where to start the replay.  It comes from the backup label file or the
- * control file.
- *
- * RedoStartLSN is the checkpoint's REDO location, also from the backup label
- * file or the control file.  In standby mode, XLOG streaming usually starts
- * from the position where an invalid record was found.  But if we fail to
- * read even the initial checkpoint record, we use the REDO location instead
- * of the checkpoint location as the start position of XLOG streaming.
- * Otherwise we would have to jump backwards to the REDO location after
- * reading the checkpoint record, because the REDO record can precede the
- * checkpoint record.
- */
-static XLogRecPtr CheckPointLoc = InvalidXLogRecPtr;
-static TimeLineID CheckPointTLI = 0;
-static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr;
-static TimeLineID RedoStartTLI = 0;
-
-/*
- * Local copy of SharedHotStandbyActive variable. False actually means "not
- * known, need to check the shared state".
- */
-static bool LocalHotStandbyActive = false;
-
-/*
- * Local copy of SharedPromoteIsTriggered variable. False actually means "not
- * known, need to check the shared state".
- */
-static bool LocalPromoteIsTriggered = false;
-
-/* Has the recovery code requested a walreceiver wakeup? */
-static bool doRequestWalReceiverReply;
-
-/* XLogReader object used to parse the WAL records */
-static XLogReaderState *xlogreader = NULL;
-
-/* XLogPrefetcher object used to consume WAL records with read-ahead */
-static XLogPrefetcher *xlogprefetcher = NULL;
-
 /* Parameters passed down from ReadRecord to the XLogPageRead callback. */
 typedef struct XLogPageReadPrivate
 {
@@ -203,9 +147,6 @@ typedef struct XLogPageReadPrivate
 	TimeLineID	replayTLI;
 } XLogPageReadPrivate;
 
-/* flag to tell XLogPageRead that we have started replaying */
-static bool InRedo = false;
-
 /*
  * Codes indicating where we got a WAL file from during recovery, or where
  * to attempt to get one.
@@ -221,6 +162,201 @@ typedef enum
 /* human-readable names for XLogSources, for debugging output */
 static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
 
+/*
+ * Forward declaration for state field holding shared-memory recovery control
+ * pointer.
+ */
+typedef struct XLogRecoveryCtlData XLogRecoveryCtlData;
+
+/*
+ * File-local mutable state for WAL recovery.
+ *
+ * Keep state in a single object to avoid a broad set of independent static
+ * globals and make it easier to evolve recovery internals.
+ */
+typedef struct XLogRecoveryLocalState
+{
+	/*
+	 * A list of TimeLineHistoryEntries for recoveryTargetTLI and the
+	 * timelines of its known parents, newest first (so recoveryTargetTLI is
+	 * always the first list member).  Only these TLIs are expected to be seen
+	 * in the WAL segments we read, and indeed only these TLIs will be
+	 * considered as candidate WAL files to open at all.
+	 */
+	List	   *expectedTLEs;
+
+	/*
+	 * The TLI appearing in the name of the current input WAL file. (This is
+	 * not necessarily the same as the timeline from which we are replaying
+	 * WAL, which StartupXLOG calls replayTLI, because we could be scanning
+	 * data that was copied from an ancestor timeline when the current file
+	 * was created.)  During a sequential scan we do not allow this value to
+	 * decrease.
+	 */
+	TimeLineID	curFileTLI;
+
+	/*
+	 * When StandbyModeRequested is set, standby mode was requested, i.e.
+	 * standby.signal file was present. It is only valid in the startup
+	 * process.
+	 */
+	bool		standbyModeRequested;
+
+	/*
+	 * CheckPointLoc is the position of the checkpoint record that determines
+	 * where to start the replay.  It comes from the backup label file or the
+	 * control file.
+	 *
+	 * RedoStartLSN is the checkpoint's REDO location, also from the backup
+	 * label file or the control file.  In standby mode, XLOG streaming
+	 * usually starts from the position where an invalid record was found. But
+	 * if we fail to read even the initial checkpoint record, we use the REDO
+	 * location instead of the checkpoint location as the start position of
+	 * XLOG streaming. Otherwise we would have to jump backwards to the REDO
+	 * location after reading the checkpoint record, because the REDO record
+	 * can precede the checkpoint record.
+	 */
+	XLogRecPtr	checkPointLoc;
+	TimeLineID	checkPointTLI;
+	XLogRecPtr	redoStartLSN;
+	TimeLineID	redoStartTLI;
+
+	/*
+	 * Local copy of SharedHotStandbyActive variable. False actually means
+	 * "not known, need to check the shared state".
+	 */
+	bool		localHotStandbyActive;
+
+	/*
+	 * Local copy of SharedPromoteIsTriggered variable. False actually means
+	 * "not known, need to check the shared state".
+	 */
+	bool		localPromoteIsTriggered;
+
+	/* Has the recovery code requested a walreceiver wakeup? */
+	bool		doRequestWalReceiverReply;
+
+	/* XLogReader object used to parse the WAL records */
+	XLogReaderState *xlogReader;
+
+	/* XLogPrefetcher object used to consume WAL records with read-ahead */
+	XLogPrefetcher *xlogPrefetcher;
+
+	/* flag to tell XLogPageRead that we have started replaying */
+	bool		inRedo;
+
+	/*
+	 * readFile is -1 or a kernel FD for the log file segment that's currently
+	 * open for reading.  readSegNo identifies the segment.  readOff is the
+	 * offset of the page just read, readLen indicates how much of it has been
+	 * read into readBuf, and readSource indicates where we got the currently
+	 * open file from.
+	 *
+	 * Note: we could use Reserve/ReleaseExternalFD to track consumption of
+	 * this FD too (like for openLogFile in xlog.c); but it doesn't currently
+	 * seem worthwhile, since the XLOG is not read by general-purpose
+	 * sessions.
+	 */
+	int			readFile;
+	XLogSegNo	readSegNo;
+	uint32		readOff;
+	uint32		readLen;
+	XLogSource	readSource;
+
+	/*
+	 * Keeps track of which source we're currently reading from. This is
+	 * different from readSource in that this is always set, even when we
+	 * don't currently have a WAL file open. If lastSourceFailed is set, our
+	 * last attempt to read from currentSource failed, and we should try
+	 * another source next.
+	 *
+	 * pendingWalRcvRestart is set when a config change occurs that requires a
+	 * walreceiver restart.  This is only valid in XLOG_FROM_STREAM state.
+	 */
+	XLogSource	currentSource;
+	bool		lastSourceFailed;
+	bool		pendingWalRcvRestart;
+
+	/*
+	 * These variables track when we last obtained some WAL data to process,
+	 * and where we got it from.  (XLogReceiptSource is initially the same as
+	 * readSource, but readSource gets reset to zero when we don't have data
+	 * to process right now.  It is also different from currentSource, which
+	 * also changes when we try to read from a source and fail, while
+	 * XLogReceiptSource tracks where we last successfully read some WAL.)
+	 */
+	TimestampTz xlogReceiptTime;
+	XLogSource	xlogReceiptSource;
+
+	/* Local copy of WalRcv->flushedUpto */
+	XLogRecPtr	flushedUpto;
+	TimeLineID	receiveTLI;
+
+	/* Copy of backupEndRequired from the control file */
+	bool		backupEndRequired;
+
+	/* Buffers dedicated to consistency checks of size BLCKSZ */
+	char	   *replayImageMasked;
+	char	   *primaryImageMasked;
+
+	/*
+	 * if recoveryStopsBefore/After returns true, it saves information of the
+	 * stop point here
+	 */
+	TransactionId recoveryStopXid;
+	TimestampTz recoveryStopTime;
+	XLogRecPtr	recoveryStopLSN;
+	char		recoveryStopName[MAXFNAMELEN];
+	bool		recoveryStopAfter;
+}			XLogRecoveryLocalState;
+
+static XLogRecoveryLocalState XLogRecoveryState =
+{
+	.checkPointLoc = InvalidXLogRecPtr,
+	.redoStartLSN = InvalidXLogRecPtr,
+	.readFile = -1,
+	.readSource = XLOG_FROM_ANY,
+	.currentSource = XLOG_FROM_ANY,
+	.xlogReceiptSource = XLOG_FROM_ANY,
+	.flushedUpto = InvalidXLogRecPtr,
+	.xlogReader = NULL,
+	.xlogPrefetcher = NULL
+};
+
+#define expectedTLEs (XLogRecoveryState.expectedTLEs)
+#define curFileTLI (XLogRecoveryState.curFileTLI)
+#define StandbyModeRequested (XLogRecoveryState.standbyModeRequested)
+#define CheckPointLoc (XLogRecoveryState.checkPointLoc)
+#define CheckPointTLI (XLogRecoveryState.checkPointTLI)
+#define RedoStartLSN (XLogRecoveryState.redoStartLSN)
+#define RedoStartTLI (XLogRecoveryState.redoStartTLI)
+#define LocalHotStandbyActive (XLogRecoveryState.localHotStandbyActive)
+#define LocalPromoteIsTriggered (XLogRecoveryState.localPromoteIsTriggered)
+#define doRequestWalReceiverReply (XLogRecoveryState.doRequestWalReceiverReply)
+#define InRedo (XLogRecoveryState.inRedo)
+#define readFile (XLogRecoveryState.readFile)
+#define readSegNo (XLogRecoveryState.readSegNo)
+#define readOff (XLogRecoveryState.readOff)
+#define readLen (XLogRecoveryState.readLen)
+#define readSource (XLogRecoveryState.readSource)
+#define currentSource (XLogRecoveryState.currentSource)
+#define lastSourceFailed (XLogRecoveryState.lastSourceFailed)
+#define pendingWalRcvRestart (XLogRecoveryState.pendingWalRcvRestart)
+#define XLogReceiptTime (XLogRecoveryState.xlogReceiptTime)
+#define XLogReceiptSource (XLogRecoveryState.xlogReceiptSource)
+#define flushedUpto (XLogRecoveryState.flushedUpto)
+#define receiveTLI (XLogRecoveryState.receiveTLI)
+#define xlogreader (XLogRecoveryState.xlogReader)
+#define xlogprefetcher (XLogRecoveryState.xlogPrefetcher)
+#define BackupEndRequired (XLogRecoveryState.backupEndRequired)
+#define replay_image_masked (XLogRecoveryState.replayImageMasked)
+#define primary_image_masked (XLogRecoveryState.primaryImageMasked)
+#define recoveryStopXid (XLogRecoveryState.recoveryStopXid)
+#define recoveryStopTime (XLogRecoveryState.recoveryStopTime)
+#define recoveryStopLSN (XLogRecoveryState.recoveryStopLSN)
+#define recoveryStopName (XLogRecoveryState.recoveryStopName)
+#define recoveryStopAfter (XLogRecoveryState.recoveryStopAfter)
+
 /*
  * readFile is -1 or a kernel FD for the log file segment that's currently
  * open for reading.  readSegNo identifies the segment.  readOff is the offset
@@ -231,11 +367,6 @@ static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "strea
  * FD too (like for openLogFile in xlog.c); but it doesn't currently seem
  * worthwhile, since the XLOG is not read by general-purpose sessions.
  */
-static int	readFile = -1;
-static XLogSegNo readSegNo = 0;
-static uint32 readOff = 0;
-static uint32 readLen = 0;
-static XLogSource readSource = XLOG_FROM_ANY;
 
 /*
  * Keeps track of which source we're currently reading from. This is
@@ -247,9 +378,6 @@ static XLogSource readSource = XLOG_FROM_ANY;
  * pendingWalRcvRestart is set when a config change occurs that requires a
  * walreceiver restart.  This is only valid in XLOG_FROM_STREAM state.
  */
-static XLogSource currentSource = XLOG_FROM_ANY;
-static bool lastSourceFailed = false;
-static bool pendingWalRcvRestart = false;
 
 /*
  * These variables track when we last obtained some WAL data to process,
@@ -259,12 +387,8 @@ static bool pendingWalRcvRestart = false;
  * also changes when we try to read from a source and fail, while
  * XLogReceiptSource tracks where we last successfully read some WAL.)
  */
-static TimestampTz XLogReceiptTime = 0;
-static XLogSource XLogReceiptSource = XLOG_FROM_ANY;
 
 /* Local copy of WalRcv->flushedUpto */
-static XLogRecPtr flushedUpto = InvalidXLogRecPtr;
-static TimeLineID receiveTLI = 0;
 
 /*
  * Copy of minRecoveryPoint and backupEndPoint from the control file.
@@ -284,7 +408,6 @@ static TimeLineID minRecoveryPointTLI;
 
 static XLogRecPtr backupStartPoint;
 static XLogRecPtr backupEndPoint;
-static bool backupEndRequired = false;
 
 /*
  * Have we reached a consistent database state?  In crash recovery, we have
@@ -303,8 +426,6 @@ static bool backupEndRequired = false;
 bool		reachedConsistency = false;
 
 /* Buffers dedicated to consistency checks of size BLCKSZ */
-static char *replay_image_masked = NULL;
-static char *primary_image_masked = NULL;
 
 XLogRecoveryCtlData *XLogRecoveryCtl = NULL;
 
@@ -329,21 +450,16 @@ static XLogRecPtr missingContrecPtr;
  * if recoveryStopsBefore/After returns true, it saves information of the stop
  * point here
  */
-static TransactionId recoveryStopXid;
-static TimestampTz recoveryStopTime;
-static XLogRecPtr recoveryStopLSN;
-static char recoveryStopName[MAXFNAMELEN];
-static bool recoveryStopAfter;
 
 /* prototypes for local functions */
-static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI);
+static void ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI);
 
 static void EnableStandbyMode(void);
 static void readRecoverySignalFile(void);
 static void validateRecoveryParameters(void);
 static bool read_backup_label(XLogRecPtr *checkPointLoc,
 							  TimeLineID *backupLabelTLI,
-							  bool *backupEndRequired, bool *backupFromStandby);
+							  bool *backupEndRequiredPtr, bool *backupFromStandby);
 static bool read_tablespace_map(List **tablespaces);
 
 static void xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI);
@@ -365,11 +481,11 @@ static void recoveryPausesHere(bool endOfRecovery);
 static bool recoveryApplyDelay(XLogReaderState *record);
 static void ConfirmRecoveryPaused(void);
 
-static XLogRecord *ReadRecord(XLogPrefetcher *xlogprefetcher,
+static XLogRecord *ReadRecord(XLogPrefetcher *prefetcher,
 							  int emode, bool fetching_ckpt,
 							  TimeLineID replayTLI);
 
-static int	XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
+static int	XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr,
 						 int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
 static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
 													  bool randAccess,
@@ -379,7 +495,7 @@ static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
 													  XLogRecPtr replayLSN,
 													  bool nonblocking);
 static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
-static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher,
+static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *prefetcher,
 										XLogRecPtr RecPtr, TimeLineID replayTLI);
 static bool rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN);
 static int	XLogFileRead(XLogSegNo segno, TimeLineID tli,
@@ -534,7 +650,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 	 * process after checking for signal files and after performing validation
 	 * of the recovery parameters.
 	 */
-	if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &backupEndRequired,
+	if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &BackupEndRequired,
 						  &backupFromStandby))
 	{
 		List	   *tablespaces = NIL;
@@ -932,7 +1048,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 		if (haveBackupLabel)
 		{
 			ControlFile->backupStartPoint = checkPoint.redo;
-			ControlFile->backupEndRequired = backupEndRequired;
+			ControlFile->backupEndRequired = BackupEndRequired;
 
 			if (backupFromStandby)
 			{
@@ -949,7 +1065,7 @@ InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
 
 	/* remember these, so that we know when we have reached consistency */
 	backupStartPoint = ControlFile->backupStartPoint;
-	backupEndRequired = ControlFile->backupEndRequired;
+	BackupEndRequired = ControlFile->backupEndRequired;
 	backupEndPoint = ControlFile->backupEndPoint;
 	if (InArchiveRecovery)
 	{
@@ -1165,7 +1281,7 @@ validateRecoveryParameters(void)
  */
 static bool
 read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
-				  bool *backupEndRequired, bool *backupFromStandby)
+				  bool *backupEndRequiredPtr, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
@@ -1182,7 +1298,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/* suppress possible uninitialized-variable warnings */
 	*checkPointLoc = InvalidXLogRecPtr;
 	*backupLabelTLI = 0;
-	*backupEndRequired = false;
+	*backupEndRequiredPtr = false;
 	*backupFromStandby = false;
 
 	/*
@@ -1232,7 +1348,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
 	{
 		if (strcmp(backuptype, "streamed") == 0)
-			*backupEndRequired = true;
+			*backupEndRequiredPtr = true;
 	}
 
 	/*
@@ -1877,14 +1993,14 @@ PerformWalRecovery(void)
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
 static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
 {
 	ErrorContextCallback errcallback;
 	bool		switchedTLI = false;
 
 	/* Setup error traceback support for ereport() */
 	errcallback.callback = rm_redo_error_callback;
-	errcallback.arg = xlogreader;
+	errcallback.arg = reader;
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
@@ -1911,7 +2027,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			CheckPoint	checkPoint;
 
-			memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+			memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
 			newReplayTLI = checkPoint.ThisTimeLineID;
 			prevReplayTLI = checkPoint.PrevTimeLineID;
 		}
@@ -1919,7 +2035,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		{
 			xl_end_of_recovery xlrec;
 
-			memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+			memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
 			newReplayTLI = xlrec.ThisTimeLineID;
 			prevReplayTLI = xlrec.PrevTimeLineID;
 		}
@@ -1927,7 +2043,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		if (newReplayTLI != *replayTLI)
 		{
 			/* Check that it's OK to switch to this TLI */
-			checkTimeLineSwitch(xlogreader->EndRecPtr,
+			checkTimeLineSwitch(reader->EndRecPtr,
 								newReplayTLI, prevReplayTLI, *replayTLI);
 
 			/* Following WAL records should be run with new TLI */
@@ -1941,7 +2057,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * XLogFlush will update minRecoveryPoint correctly.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->replayEndTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -1957,10 +2073,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * directly here, rather than in xlog_redo()
 	 */
 	if (record->xl_rmid == RM_XLOG_ID)
-		xlogrecovery_redo(xlogreader, *replayTLI);
+		xlogrecovery_redo(reader, *replayTLI);
 
 	/* Now apply the WAL record itself */
-	GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+	GetRmgr(record->xl_rmid).rm_redo(reader);
 
 	/*
 	 * After redo, check whether the backup pages associated with the WAL
@@ -1968,7 +2084,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * if consistency check is enabled for this record.
 	 */
 	if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
-		verifyBackupPageConsistency(xlogreader);
+		verifyBackupPageConsistency(reader);
 
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
@@ -1978,8 +2094,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 	 * replayed.
 	 */
 	SpinLockAcquire(&XLogRecoveryCtl->info_lck);
-	XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
-	XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+	XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+	XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
 	XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
 	SpinLockRelease(&XLogRecoveryCtl->info_lck);
 
@@ -2029,7 +2145,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 		 * Before we continue on the new timeline, clean up any (possibly
 		 * bogus) future WAL segments on the old timeline.
 		 */
-		RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+		RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
@@ -2184,7 +2300,7 @@ CheckRecoveryConsistency(void)
 		ReachedEndOfBackup(lastReplayedEndRecPtr, lastReplayedTLI);
 		backupStartPoint = InvalidXLogRecPtr;
 		backupEndPoint = InvalidXLogRecPtr;
-		backupEndRequired = false;
+		BackupEndRequired = false;
 
 		ereport(LOG,
 				errmsg("completed backup recovery with redo LSN %X/%08X and end LSN %X/%08X",
@@ -2198,7 +2314,7 @@ CheckRecoveryConsistency(void)
 	 * XLOG_BACKUP_END arrives to advise us of the correct minRecoveryPoint.
 	 * All we know prior to that is that we're not consistent yet.
 	 */
-	if (!reachedConsistency && !backupEndRequired &&
+	if (!reachedConsistency && !BackupEndRequired &&
 		minRecoveryPoint <= lastReplayedEndRecPtr)
 	{
 		/*
@@ -3102,19 +3218,19 @@ ConfirmRecoveryPaused(void)
  * record is available.
  */
 static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
 		   bool fetching_ckpt, TimeLineID replayTLI)
 {
 	XLogRecord *record;
-	XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+	XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
 
 	Assert(AmStartupProcess() || !IsUnderPostmaster);
 
 	/* Pass through parameters to XLogPageRead */
 	private->fetching_ckpt = fetching_ckpt;
 	private->emode = emode;
-	private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+	private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
 	private->replayTLI = replayTLI;
 
 	/* This is the first attempt to read this page. */
@@ -3124,7 +3240,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 	{
 		char	   *errormsg;
 
-		record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+		record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
 		if (record == NULL)
 		{
 			/*
@@ -3140,10 +3256,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * overwrite contrecord in the wrong place, breaking everything.
 			 */
 			if (!ArchiveRecoveryRequested &&
-				XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+				XLogRecPtrIsValid(reader->abortedRecPtr))
 			{
-				abortedRecPtr = xlogreader->abortedRecPtr;
-				missingContrecPtr = xlogreader->missingContrecPtr;
+				abortedRecPtr = reader->abortedRecPtr;
+				missingContrecPtr = reader->missingContrecPtr;
 			}
 
 			if (readFile >= 0)
@@ -3159,29 +3275,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			 * shouldn't loop anymore in that case.
 			 */
 			if (errormsg)
-				ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+				ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 						(errmsg_internal("%s", errormsg) /* already translated */ ));
 		}
 
 		/*
 		 * Check page TLI is one of the expected values.
 		 */
-		else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+		else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
 		{
 			char		fname[MAXFNAMELEN];
 			XLogSegNo	segno;
 			int32		offset;
 
-			XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
-			offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+			XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+			offset = XLogSegmentOffset(reader->latestPagePtr,
 									   wal_segment_size);
-			XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+			XLogFileName(fname, reader->seg.ws_tli, segno,
 						 wal_segment_size);
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
 					errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
-						   xlogreader->latestPageTLI,
+						   reader->latestPageTLI,
 						   fname,
-						   LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+						   LSN_FORMAT_ARGS(reader->latestPagePtr),
 						   offset));
 			record = NULL;
 		}
@@ -3217,8 +3333,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 				if (StandbyModeRequested)
 					EnableStandbyMode();
 
-				SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
-				minRecoveryPoint = xlogreader->EndRecPtr;
+				SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+				minRecoveryPoint = reader->EndRecPtr;
 				minRecoveryPointTLI = replayTLI;
 
 				CheckRecoveryConsistency();
@@ -3271,11 +3387,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
  * sleep and retry.
  */
 static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf)
 {
 	XLogPageReadPrivate *private =
-		(XLogPageReadPrivate *) xlogreader->private_data;
+		(XLogPageReadPrivate *) reader->private_data;
 	int			emode = private->emode;
 	uint32		targetPageOff;
 	XLogSegNo	targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3322,7 +3438,7 @@ retry:
 		 flushedUpto < targetPagePtr + reqLen))
 	{
 		if (readFile >= 0 &&
-			xlogreader->nonblocking &&
+			reader->nonblocking &&
 			readSource == XLOG_FROM_STREAM &&
 			flushedUpto < targetPagePtr + reqLen)
 			return XLREAD_WOULDBLOCK;
@@ -3332,8 +3448,8 @@ retry:
 											private->fetching_ckpt,
 											targetRecPtr,
 											private->replayTLI,
-											xlogreader->EndRecPtr,
-											xlogreader->nonblocking))
+											reader->EndRecPtr,
+											reader->nonblocking))
 		{
 			case XLREAD_WOULDBLOCK:
 				return XLREAD_WOULDBLOCK;
@@ -3417,7 +3533,7 @@ retry:
 	Assert(targetPageOff == readOff);
 	Assert(reqLen <= readLen);
 
-	xlogreader->seg.ws_tli = curFileTLI;
+	reader->seg.ws_tli = curFileTLI;
 
 	/*
 	 * Check the page header immediately, so that we can retry immediately if
@@ -3453,18 +3569,18 @@ retry:
 	 */
 	if (StandbyMode &&
 		(targetPagePtr % wal_segment_size) == 0 &&
-		!XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+		!XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
 	{
 		/*
 		 * Emit this error right now then retry this page immediately. Use
 		 * errmsg_internal() because the message was already translated.
 		 */
-		if (xlogreader->errormsg_buf[0])
-			ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
-					(errmsg_internal("%s", xlogreader->errormsg_buf)));
+		if (reader->errormsg_buf[0])
+			ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+					(errmsg_internal("%s", reader->errormsg_buf)));
 
 		/* reset any error XLogReaderValidatePageHeader() might have set */
-		XLogReaderResetError(xlogreader);
+		XLogReaderResetError(reader);
 		goto next_record_is_invalid;
 	}
 
@@ -3476,7 +3592,7 @@ next_record_is_invalid:
 	 * If we're reading ahead, give up fast.  Retries and error reporting will
 	 * be handled by a later read when recovery catches up to this point.
 	 */
-	if (xlogreader->nonblocking)
+	if (reader->nonblocking)
 		return XLREAD_WOULDBLOCK;
 
 	lastSourceFailed = true;
@@ -4054,7 +4170,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
  * Subroutine to try to fetch and validate a prior checkpoint record.
  */
 static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
 					 TimeLineID replayTLI)
 {
 	XLogRecord *record;
@@ -4069,8 +4185,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
 		return NULL;
 	}
 
-	XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
-	record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+	XLogPrefetcherBeginRead(prefetcher, RecPtr);
+	record = ReadRecord(prefetcher, LOG, true, replayTLI);
 
 	if (record == NULL)
 	{
-- 
2.50.1 (Apple Git-155)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-21 11:02  David Rowley <[email protected]>
  parent: Chao Li <[email protected]>
  0 siblings, 1 reply; 30+ messages in thread

From: David Rowley @ 2026-04-21 11:02 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Álvaro Herrera <[email protected]>; Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>

On Tue, 21 Apr 2026 at 19:02, Chao Li <[email protected]> wrote:
> PFA v8 - rebased and fixed a few new occurrences.

Which of these are new to v19?  Can you separate those ones out? IMO,
we should commit at least those, as those won't cause any backpatching
pain.

I recall that I was motivated to commit the -Wshadow=compatible-local
ones as there'd been a few bugs with shadowed variables. There'd be
more of an argument to cause all this churn if it was for something
more than to make things better for clang users.

David





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-21 13:51  Álvaro Herrera <[email protected]>
  parent: David Rowley <[email protected]>
  0 siblings, 1 reply; 30+ messages in thread

From: Álvaro Herrera @ 2026-04-21 13:51 UTC (permalink / raw)
  To: David Rowley <[email protected]>; +Cc: Chao Li <[email protected]>; Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>

On 2026-Apr-21, David Rowley wrote:

> On Tue, 21 Apr 2026 at 19:02, Chao Li <[email protected]> wrote:
> > PFA v8 - rebased and fixed a few new occurrences.
> 
> Which of these are new to v19?  Can you separate those ones out? IMO,
> we should commit at least those, as those won't cause any backpatching
> pain.

I agree.  The others are v20 material.


Specifically about 0003 (v20 material for sure, as this is ancient
code), I don't like this patch very much.  I wonder if it would be
possible to do away with the idea of using these codeFragment things
without introducing a performance issue here.  Is that doable by turning
these macros into static functions?

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Puedes vivir sólo una vez, pero si lo haces bien, una vez es suficiente"





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-22 05:14  Chao Li <[email protected]>
  parent: Álvaro Herrera <[email protected]>
  0 siblings, 3 replies; 30+ messages in thread

From: Chao Li @ 2026-04-22 05:14 UTC (permalink / raw)
  To: Álvaro Herrera <[email protected]>; David Rowley <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Apr 21, 2026, at 21:51, Álvaro Herrera <[email protected]> wrote:
> 
> On 2026-Apr-21, David Rowley wrote:
> 
>> On Tue, 21 Apr 2026 at 19:02, Chao Li <[email protected]> wrote:
>>> PFA v8 - rebased and fixed a few new occurrences.
>> 
>> Which of these are new to v19?  Can you separate those ones out? IMO,
>> we should commit at least those, as those won't cause any backpatching
>> pain.
> 
> I agree.  The others are v20 material.
> 

Sounds reasonable.

The attached new v1 patch fixes the v19-only shadow warnings. There are not many. I strictly limited it to warnings newly introduced in v19, without touching any pre-existing ones, even where an old occurrence is very close to a new one.

I intentionally left out one occurrence in ruleutils.c:
```
ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
 13100 |                                                 deparse_context context = {0};
       |                                                                 ^
ruleutils.c:12955:67: note: previous declaration is here
 12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
       |                                                                   ^
1 warning generated.
```

I saw there is a thread [1] that will remove this deparse_context context = {0};, so I skipped this one to avoid a potential conflict.

Besides the patch file, I am also attaching three files for reference:

* v18-shadow-warnings.txt - all shadow warnings from branch REL_18_STABLE
* v19-shadow-warnings-master.txt - all shadow warnings from current master (9d3e094f12c)
* v19-shadow-warnings-patched.txt - all shadow warnings after applying this v1 patch

Except for the one in ruleutils.c, v19-shadow-warnings-patched.txt is a pure subset of v18-shadow-warnings.txt. You don't need to read these large files; they are attached only for reference.

I will recreate the previous patch set for v20.

> 
> Specifically about 0003 (v20 material for sure, as this is ancient
> code), I don't like this patch very much.  I wonder if it would be
> possible to do away with the idea of using these codeFragment things
> without introducing a performance issue here.  Is that doable by turning
> these macros into static functions?
> 

Okay, I will remove 0003 from this patch set, and use a separate patch to try converting the macros to static functions.

[1] http://postgr.es/m/CAHg+QDcLVa2iBnggkHxY4itZbXtDMfsYHEjnCUYe9hNbnxDi-w@mail.gmail.com

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/





controldata_utils.c:52:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   52 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:173:26: note: previous declaration is here
  173 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:189:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:173:26: note: previous declaration is here
  173 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:697:16: warning: declaration shadows a local variable [-Wshadow]
  697 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:589:11: note: previous declaration is here
  589 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:40:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   40 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
xlogdesc.c:165:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  165 |                 int                     wal_level;
      |                                         ^
../../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1228:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1228 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:285:13: note: previous declaration is here
  285 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1928:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1928 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3153:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3153 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:193:24: note: previous declaration is here
  193 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3157:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3157 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3320:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3320 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4093:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4093 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:193:24: note: previous declaration is here
  193 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
basebackup_incremental.c:599:14: warning: declaration shadows a local variable [-Wshadow]
  599 |                                 unsigned        i;
      |                                                 ^
basebackup_incremental.c:273:8: note: previous declaration is here
  273 |         int                     i;
      |                                 ^
1 warning generated.
bootstrap.c:201:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  201 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2144:12: warning: declaration shadows a local variable [-Wshadow]
 2144 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
objectaddress.c:2161:12: warning: declaration shadows a local variable [-Wshadow]
 2161 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
objectaddress.c:2198:12: warning: declaration shadows a local variable [-Wshadow]
 2198 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
parse_target.c:1613:13: warning: declaration shadows a local variable [-Wshadow]
 1613 |                                         Index           levelsup;
      |                                                         ^
parse_target.c:1522:56: note: previous declaration is here
 1522 | expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
      |                                                        ^
parse_target.c:1671:13: warning: declaration shadows a local variable [-Wshadow]
 1671 |                                         Index           levelsup;
      |                                                         ^
parse_target.c:1522:56: note: previous declaration is here
 1522 | expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
      |                                                        ^
2 warnings generated.
extension.c:1406:13: warning: declaration shadows a local variable [-Wshadow]
 1406 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1200:20: note: previous declaration is here
 1200 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:39: note: previous declaration is here
   52 | CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
      |                                       ^
1 warning generated.
statscmds.c:321:16: warning: declaration shadows a local variable [-Wshadow]
  321 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:64:9: note: previous declaration is here
   64 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15721:20: warning: declaration shadows a local variable [-Wshadow]
 15721 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15630:67: note: previous declaration is here
 15630 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:15792:20: warning: declaration shadows a local variable [-Wshadow]
 15792 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15630:67: note: previous declaration is here
 15630 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
2 warnings generated.
trigger.c:1169:13: warning: declaration shadows a local variable [-Wshadow]
 1169 |                         Node       *qual;
      |                                     ^
trigger.c:189:11: note: previous declaration is here
  189 |         char       *qual;
      |                     ^
1 warning generated.
execExprInterp.c:474:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  474 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:112:21: note: previous declaration is here
  112 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4073:20: warning: declaration shadows a local variable [-Wshadow]
 4073 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3293:8: note: previous declaration is here
 3293 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:114:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  114 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:107:26: note: previous declaration is here
  107 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:280:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  280 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:384:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  384 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:443:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  443 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1246:12: warning: declaration shadows a local variable [-Wshadow]
 1246 |                 Plan       *plan;
      |                             ^
createplan.c:1218:13: note: previous declaration is here
 1218 |         Append     *plan;
      |                     ^
createplan.c:2559:12: warning: declaration shadows a local variable [-Wshadow]
 2559 |                 Plan       *plan;
      |                             ^
createplan.c:2549:13: note: previous declaration is here
 2549 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
dependencies.c:1192:14: warning: declaration shadows a local variable [-Wshadow]
 1192 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1168:87: note: previous declaration is here
 1168 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1226:22: warning: declaration shadows a local variable [-Wshadow]
 1226 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1168:87: note: previous declaration is here
 1168 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1053:10: warning: declaration shadows a local variable [-Wshadow]
 1053 |                         bool            isnull;
      |                                         ^
extended_stats.c:1005:11: note: previous declaration is here
 1005 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:963:12: warning: declaration shadows a local variable [-Wshadow]
  963 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:790:52: note: previous declaration is here
  790 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1210:11: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1200:8: note: previous declaration is here
 1200 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:572:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  572 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:596:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  596 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3131:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3131 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:645:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  645 |         int                     days;
      |                                 ^
datetime.c:84:19: note: previous declaration is here
   84 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
datetime.c:3288:32: warning: declaration shadows a variable in the global scope [-Wshadow]
 3288 | DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
      |                                ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
datetime.c:3343:36: warning: declaration shadows a variable in the global scope [-Wshadow]
 3343 | DecodeTimezoneNameToTz(const char *tzname)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
formatting.c:3076:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3076 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:538:17: warning: declaration shadows a local variable [-Wshadow]
  538 |                 JsonValueList found = {0};
      |                               ^
jsonpath_exec.c:527:11: note: previous declaration is here
  527 |         List       *found;
      |                     ^
jsonpath_exec.c:1880:24: warning: declaration shadows a local variable [-Wshadow]
 1880 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1781:15: note: previous declaration is here
 1781 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1891:24: warning: declaration shadows a local variable [-Wshadow]
 1891 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1781:15: note: previous declaration is here
 1781 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2067:17: warning: declaration shadows a local variable [-Wshadow]
 2067 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2029:21: note: previous declaration is here
 2029 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4137:16: warning: declaration shadows a local variable [-Wshadow]
 4137 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4110:41: note: previous declaration is here
 4110 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
5 warnings generated.
pg_upgrade_support.c:229:13: warning: declaration shadows a local variable [-Wshadow]
  229 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:186:11: note: previous declaration is here
  186 |         text       *extName;
      |                     ^
1 warning generated.
timestamp.c:493:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  493 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:562:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  562 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1533:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1533 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1535:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1535 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2134:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2134 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2545:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2545 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6243:11: warning: declaration shadows a local variable [-Wshadow]
 6243 |                         int64           val;
      |                                         ^
timestamp.c:6104:5: note: previous declaration is here
 6104 |                                 val;
      |                                 ^
timestamp.c:6332:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6332 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6570:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6570 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:4438:13: warning: declaration shadows a local variable [-Wshadow]
 4438 |                         char       *chunk_start;
      |                                     ^
varlena.c:4373:15: note: previous declaration is here
 4373 |                 const char *chunk_start = p;
      |                             ^
varlena.c:6067:14: warning: declaration shadows a local variable [-Wshadow]
 6067 |                                 char       *str;
      |                                             ^
varlena.c:5902:17: note: previous declaration is here
 5902 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:3988:11: warning: declaration shadows a local variable [-Wshadow]
 3988 |                                 int                     res;
      |                                                         ^
fe-connect.c:2912:14: note: previous declaration is here
 2912 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:956:10: warning: declaration shadows a local variable [-Wshadow]
  956 |                         int                     curr_nl_line;
      |                                                 ^
print.c:654:8: note: previous declaration is here
  654 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:817:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  817 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1049:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1049 |         FILE       *conf_file;
      |                     ^
initdb.c:180:14: note: previous declaration is here
  180 | static char *conf_file;
      |              ^
initdb.c:2143:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2143 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2202:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2202 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2265:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2265 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2517:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2517 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2597:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2597 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2597:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2597 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1015:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1015 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1285:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1285 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1600:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1600 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1699:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1699 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1736:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1736 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:336:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  336 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:374:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  374 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:452:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  452 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:744:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  744 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:877:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  877 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:939:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  939 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:993:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  993 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1047:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1047 | ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1178:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1178 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1217:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1217 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:371:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  371 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:134:20: note: previous declaration is here
  134 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:128:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  128 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1047:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1047 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1064:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1064 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1064:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1064 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:50:19: note: previous declaration is here
   50 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:875:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  875 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:93:14: note: previous declaration is here
   93 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1264:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1264 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1612:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1612 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1671:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1671 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1775:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1775 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:10713:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 10713 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:10714:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 10714 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11231:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11231 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11232:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11232 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
pg_dump.c:12964:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 12964 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:12965:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 12965 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:533:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  533 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:1840:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 1840 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:120:14: note: previous declaration is here
  120 | static char *filename = NULL;
      |              ^
1 warning generated.
pg_resetwal.c:743:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  743 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:64:13: note: previous declaration is here
   64 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:555:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  555 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:628:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  628 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:74:23: note: previous declaration is here
   74 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:628:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  628 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:75:4: note: previous declaration is here
   75 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:40:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   40 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
xlogdesc.c:165:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  165 |                 int                     wal_level;
      |                                         ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4654:11: warning: declaration shadows a local variable [-Wshadow]
 4654 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4622:25: note: previous declaration is here
 4622 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1761:17: warning: declaration shadows a local variable [-Wshadow]
 1761 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1579:16: note: previous declaration is here
 1579 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2287:13: warning: declaration shadows a local variable [-Wshadow]
 2287 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1571:37: note: previous declaration is here
 1571 | describeOneTableDetails(const char *schemaname,
      |                                     ^
2 warnings generated.
prompt.c:193:24: warning: declaration shadows a local variable [-Wshadow]
  193 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:68:27: note: previous declaration is here
   68 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:364:12: warning: declaration shadows a local variable [-Wshadow]
  364 |                 char       *p = destination;
      |                             ^
prompt.c:74:14: note: previous declaration is here
   74 |         const char *p;
      |                     ^
2 warnings generated.

controldata_utils.c:53:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   53 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:190:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  190 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:702:16: warning: declaration shadows a local variable [-Wshadow]
  702 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:594:11: note: previous declaration is here
  594 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1168:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1168 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:287:13: note: previous declaration is here
  287 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1880:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1880 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3105:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3105 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3109:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3109 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3274:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3274 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4057:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4057 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
bootstrap.c:240:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  240 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2239:12: warning: declaration shadows a local variable [-Wshadow]
 2239 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2256:12: warning: declaration shadows a local variable [-Wshadow]
 2256 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2293:12: warning: declaration shadows a local variable [-Wshadow]
 2293 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
extension.c:1456:13: warning: declaration shadows a local variable [-Wshadow]
 1456 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1250:20: note: previous declaration is here
 1250 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:59: note: previous declaration is here
   52 | CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
      |                                                           ^
1 warning generated.
statscmds.c:352:16: warning: declaration shadows a local variable [-Wshadow]
  352 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:66:9: note: previous declaration is here
   66 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15965:20: warning: declaration shadows a local variable [-Wshadow]
 15965 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:16036:20: warning: declaration shadows a local variable [-Wshadow]
 16036 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:22613:15: warning: declaration shadows a local variable [-Wshadow]
 22613 |                 Constraint *constr;
       |                             ^
tablecmds.c:22526:15: note: previous declaration is here
 22526 |         TupleConstr *constr;
       |                      ^
3 warnings generated.
trigger.c:1170:13: warning: declaration shadows a local variable [-Wshadow]
 1170 |                         Node       *qual;
      |                                     ^
trigger.c:190:11: note: previous declaration is here
  190 |         char       *qual;
      |                     ^
1 warning generated.
wait.c:95:12: warning: declaration shadows a local variable [-Wshadow]
   95 |                         double          result;
      |                                         ^
wait.c:44:14: note: previous declaration is here
   44 |         const char *result = "<unset>";
      |                     ^
1 warning generated.
execExprInterp.c:476:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  476 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:114:21: note: previous declaration is here
  114 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4070:20: warning: declaration shadows a local variable [-Wshadow]
 4070 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3295:8: note: previous declaration is here
 3295 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:121:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  121 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:110:26: note: previous declaration is here
  110 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:284:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  284 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:388:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  388 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:447:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  447 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1238:12: warning: declaration shadows a local variable [-Wshadow]
 1238 |                 Plan       *plan;
      |                             ^
createplan.c:1210:13: note: previous declaration is here
 1210 |         Append     *plan;
      |                     ^
createplan.c:2410:12: warning: declaration shadows a local variable [-Wshadow]
 2410 |                 Plan       *plan;
      |                             ^
createplan.c:2400:13: note: previous declaration is here
 2400 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
datachecksum_state.c:549:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  549 |         bool            launcher_running;
      |                         ^
datachecksum_state.c:344:30: note: previous declaration is here
  344 | static volatile sig_atomic_t launcher_running = false;
      |                              ^
1 warning generated.
dependencies.c:1176:14: warning: declaration shadows a local variable [-Wshadow]
 1176 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1210:22: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1093:10: warning: declaration shadows a local variable [-Wshadow]
 1093 |                         bool            isnull;
      |                                         ^
extended_stats.c:1043:11: note: previous declaration is here
 1043 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:1297:12: warning: declaration shadows a local variable [-Wshadow]
 1297 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:1020:52: note: previous declaration is here
 1020 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1302:11: warning: declaration shadows a local variable [-Wshadow]
 1302 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1292:8: note: previous declaration is here
 1292 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:565:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  565 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:589:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  589 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3155:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3155 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:646:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  646 |         int                     days;
      |                                 ^
datetime.c:85:19: note: previous declaration is here
   85 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
1 warning generated.
formatting.c:3037:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3037 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:1928:24: warning: declaration shadows a local variable [-Wshadow]
 1928 |                                 JsonPathExecResult res;
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1946:24: warning: declaration shadows a local variable [-Wshadow]
 1946 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2131:17: warning: declaration shadows a local variable [-Wshadow]
 2131 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2084:21: note: previous declaration is here
 2084 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4447:16: warning: declaration shadows a local variable [-Wshadow]
 4447 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4420:41: note: previous declaration is here
 4420 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
4 warnings generated.
pg_upgrade_support.c:230:13: warning: declaration shadows a local variable [-Wshadow]
  230 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:187:11: note: previous declaration is here
  187 |         text       *extName;
      |                     ^
1 warning generated.
ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
 13100 |                                                 deparse_context context = {0};
       |                                                                 ^
ruleutils.c:12955:67: note: previous declaration is here
 12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
       |                                                                   ^
1 warning generated.
timestamp.c:485:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  485 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:554:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  554 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1527:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1527 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1529:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1529 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2128:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2128 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2521:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2521 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6219:11: warning: declaration shadows a local variable [-Wshadow]
 6219 |                         int64           val;
      |                                         ^
timestamp.c:6080:5: note: previous declaration is here
 6080 |                                 val;
      |                                 ^
timestamp.c:6308:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6308 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6573:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6573 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:3318:13: warning: declaration shadows a local variable [-Wshadow]
 3318 |                         char       *chunk_start;
      |                                     ^
varlena.c:3253:15: note: previous declaration is here
 3253 |                 const char *chunk_start = p;
      |                             ^
varlena.c:4949:14: warning: declaration shadows a local variable [-Wshadow]
 4949 |                                 char       *str;
      |                                             ^
varlena.c:4784:17: note: previous declaration is here
 4784 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:4005:11: warning: declaration shadows a local variable [-Wshadow]
 4005 |                                 int                     res;
      |                                                         ^
fe-connect.c:2929:14: note: previous declaration is here
 2929 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:936:10: warning: declaration shadows a local variable [-Wshadow]
  936 |                         int                     curr_nl_line;
      |                                                 ^
print.c:670:8: note: previous declaration is here
  670 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:831:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  831 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1065:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1065 |         FILE       *conf_file;
      |                     ^
initdb.c:181:14: note: previous declaration is here
  181 | static char *conf_file;
      |              ^
initdb.c:2166:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2166 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2225:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2225 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2288:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2288 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2540:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2540 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2620:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2620:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1016:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1016 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1272:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1272 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1587:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1587 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1686:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1686 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1723:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1723 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:337:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  337 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:375:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  375 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:453:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  453 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:745:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  745 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:878:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  878 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:940:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  940 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:994:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  994 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1048:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1048 | ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1179:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1179 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1218:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1218 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:414:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  414 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:157:20: note: previous declaration is here
  157 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:129:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  129 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1055:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1055 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:51:19: note: previous declaration is here
   51 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:876:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  876 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:94:14: note: previous declaration is here
   94 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1291:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1291 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1650:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1650 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1709:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1709 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1813:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1813 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:11005:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11005 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11006:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11006 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11563:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11563 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11564:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11564 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:13292:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 13292 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:13293:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 13293 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:746:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  746 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:2272:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 2272 |                                                            SimpleStringList *database_exclude_names)
      |                                                                              ^
pg_dumpall.c:136:25: note: previous declaration is here
  136 | static SimpleStringList database_exclude_names = {NULL, NULL};
      |                         ^
pg_dumpall.c:2352:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 2352 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:133:14: note: previous declaration is here
  133 | static char *filename = NULL;
      |              ^
pg_dumpall.c:2409:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 2409 |         ArchiveFormat archDumpFormat;
      |                       ^
pg_dumpall.c:141:22: note: previous declaration is here
  141 | static ArchiveFormat archDumpFormat = archNull;
      |                      ^
3 warnings generated.
pg_resetwal.c:754:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  754 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:65:13: note: previous declaration is here
   65 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:564:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  564 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:625:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:73:23: note: previous declaration is here
   73 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:625:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:74:4: note: previous declaration is here
   74 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4664:11: warning: declaration shadows a local variable [-Wshadow]
 4664 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4632:25: note: previous declaration is here
 4632 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1780:17: warning: declaration shadows a local variable [-Wshadow]
 1780 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:1941:17: warning: declaration shadows a local variable [-Wshadow]
 1941 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2427:13: warning: declaration shadows a local variable [-Wshadow]
 2427 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1588:37: note: previous declaration is here
 1588 | describeOneTableDetails(const char *schemaname,
      |                                     ^
3 warnings generated.
prompt.c:206:24: warning: declaration shadows a local variable [-Wshadow]
  206 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:71:27: note: previous declaration is here
   71 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:393:12: warning: declaration shadows a local variable [-Wshadow]
  393 |                 char       *p = destination;
      |                             ^
prompt.c:77:14: note: previous declaration is here
   77 |         const char *p;
      |                     ^
2 warnings generated.

controldata_utils.c:53:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   53 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:190:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  190 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:702:16: warning: declaration shadows a local variable [-Wshadow]
  702 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:594:11: note: previous declaration is here
  594 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1168:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1168 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:287:13: note: previous declaration is here
  287 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1880:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1880 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3105:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3105 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3109:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3109 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3274:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3274 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4057:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4057 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
bootstrap.c:240:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  240 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2239:12: warning: declaration shadows a local variable [-Wshadow]
 2239 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2256:12: warning: declaration shadows a local variable [-Wshadow]
 2256 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2293:12: warning: declaration shadows a local variable [-Wshadow]
 2293 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
extension.c:1456:13: warning: declaration shadows a local variable [-Wshadow]
 1456 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1250:20: note: previous declaration is here
 1250 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:59: note: previous declaration is here
   52 | CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
      |                                                           ^
1 warning generated.
statscmds.c:352:16: warning: declaration shadows a local variable [-Wshadow]
  352 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:66:9: note: previous declaration is here
   66 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15965:20: warning: declaration shadows a local variable [-Wshadow]
 15965 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:16036:20: warning: declaration shadows a local variable [-Wshadow]
 16036 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
2 warnings generated.
trigger.c:1170:13: warning: declaration shadows a local variable [-Wshadow]
 1170 |                         Node       *qual;
      |                                     ^
trigger.c:190:11: note: previous declaration is here
  190 |         char       *qual;
      |                     ^
1 warning generated.
execExprInterp.c:476:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  476 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:114:21: note: previous declaration is here
  114 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4070:20: warning: declaration shadows a local variable [-Wshadow]
 4070 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3295:8: note: previous declaration is here
 3295 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:121:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  121 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:110:26: note: previous declaration is here
  110 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:284:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  284 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:388:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  388 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:447:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  447 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1238:12: warning: declaration shadows a local variable [-Wshadow]
 1238 |                 Plan       *plan;
      |                             ^
createplan.c:1210:13: note: previous declaration is here
 1210 |         Append     *plan;
      |                     ^
createplan.c:2410:12: warning: declaration shadows a local variable [-Wshadow]
 2410 |                 Plan       *plan;
      |                             ^
createplan.c:2400:13: note: previous declaration is here
 2400 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
dependencies.c:1176:14: warning: declaration shadows a local variable [-Wshadow]
 1176 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1210:22: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1093:10: warning: declaration shadows a local variable [-Wshadow]
 1093 |                         bool            isnull;
      |                                         ^
extended_stats.c:1043:11: note: previous declaration is here
 1043 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:1297:12: warning: declaration shadows a local variable [-Wshadow]
 1297 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:1020:52: note: previous declaration is here
 1020 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1302:11: warning: declaration shadows a local variable [-Wshadow]
 1302 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1292:8: note: previous declaration is here
 1292 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:565:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  565 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:589:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  589 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3155:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3155 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:646:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  646 |         int                     days;
      |                                 ^
datetime.c:85:19: note: previous declaration is here
   85 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
1 warning generated.
formatting.c:3037:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3037 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:1928:24: warning: declaration shadows a local variable [-Wshadow]
 1928 |                                 JsonPathExecResult res;
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1946:24: warning: declaration shadows a local variable [-Wshadow]
 1946 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2131:17: warning: declaration shadows a local variable [-Wshadow]
 2131 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2084:21: note: previous declaration is here
 2084 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4447:16: warning: declaration shadows a local variable [-Wshadow]
 4447 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4420:41: note: previous declaration is here
 4420 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
4 warnings generated.
pg_upgrade_support.c:230:13: warning: declaration shadows a local variable [-Wshadow]
  230 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:187:11: note: previous declaration is here
  187 |         text       *extName;
      |                     ^
1 warning generated.
ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
 13100 |                                                 deparse_context context = {0};
       |                                                                 ^
ruleutils.c:12955:67: note: previous declaration is here
 12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
       |                                                                   ^
1 warning generated.
timestamp.c:485:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  485 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:554:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  554 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1527:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1527 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1529:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1529 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2128:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2128 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2521:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2521 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6219:11: warning: declaration shadows a local variable [-Wshadow]
 6219 |                         int64           val;
      |                                         ^
timestamp.c:6080:5: note: previous declaration is here
 6080 |                                 val;
      |                                 ^
timestamp.c:6308:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6308 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6573:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6573 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:3318:13: warning: declaration shadows a local variable [-Wshadow]
 3318 |                         char       *chunk_start;
      |                                     ^
varlena.c:3253:15: note: previous declaration is here
 3253 |                 const char *chunk_start = p;
      |                             ^
varlena.c:4949:14: warning: declaration shadows a local variable [-Wshadow]
 4949 |                                 char       *str;
      |                                             ^
varlena.c:4784:17: note: previous declaration is here
 4784 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:4005:11: warning: declaration shadows a local variable [-Wshadow]
 4005 |                                 int                     res;
      |                                                         ^
fe-connect.c:2929:14: note: previous declaration is here
 2929 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:936:10: warning: declaration shadows a local variable [-Wshadow]
  936 |                         int                     curr_nl_line;
      |                                                 ^
print.c:670:8: note: previous declaration is here
  670 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:831:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  831 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1065:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1065 |         FILE       *conf_file;
      |                     ^
initdb.c:181:14: note: previous declaration is here
  181 | static char *conf_file;
      |              ^
initdb.c:2166:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2166 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2225:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2225 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2288:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2288 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2540:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2540 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2620:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2620:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1016:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1016 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1272:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1272 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1587:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1587 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1686:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1686 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1723:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1723 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:337:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  337 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:375:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  375 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:453:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  453 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:745:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  745 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:878:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  878 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:940:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  940 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:994:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  994 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1048:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1048 | ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1179:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1179 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1218:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1218 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:414:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  414 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:157:20: note: previous declaration is here
  157 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:129:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  129 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1055:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1055 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:51:19: note: previous declaration is here
   51 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:876:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  876 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:94:14: note: previous declaration is here
   94 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1291:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1291 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1650:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1650 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1709:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1709 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1813:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1813 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:11005:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11005 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11006:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11006 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11563:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11563 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11564:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11564 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:13292:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 13292 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:13293:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 13293 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:746:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  746 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:2352:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 2352 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:133:14: note: previous declaration is here
  133 | static char *filename = NULL;
      |              ^
1 warning generated.
pg_resetwal.c:754:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  754 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:65:13: note: previous declaration is here
   65 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:564:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  564 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:625:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:73:23: note: previous declaration is here
   73 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:625:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:74:4: note: previous declaration is here
   74 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4664:11: warning: declaration shadows a local variable [-Wshadow]
 4664 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4632:25: note: previous declaration is here
 4632 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1780:17: warning: declaration shadows a local variable [-Wshadow]
 1780 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2427:13: warning: declaration shadows a local variable [-Wshadow]
 2427 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1588:37: note: previous declaration is here
 1588 | describeOneTableDetails(const char *schemaname,
      |                                     ^
2 warnings generated.
prompt.c:206:24: warning: declaration shadows a local variable [-Wshadow]
  206 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:71:27: note: previous declaration is here
   71 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:393:12: warning: declaration shadows a local variable [-Wshadow]
  393 |                 char       *p = destination;
      |                             ^
prompt.c:77:14: note: previous declaration is here
   77 |         const char *p;
      |                     ^
2 warnings generated.


Attachments:

  [text/plain] v18-shadow-warnings.txt (56.8K, 2-v18-shadow-warnings.txt)
  download | inline:
controldata_utils.c:52:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   52 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:173:26: note: previous declaration is here
  173 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:189:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:173:26: note: previous declaration is here
  173 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:697:16: warning: declaration shadows a local variable [-Wshadow]
  697 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:589:11: note: previous declaration is here
  589 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:40:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   40 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
xlogdesc.c:165:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  165 |                 int                     wal_level;
      |                                         ^
../../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1228:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1228 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:285:13: note: previous declaration is here
  285 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1928:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1928 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3153:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3153 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:193:24: note: previous declaration is here
  193 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3157:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3157 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3320:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3320 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:190:25: note: previous declaration is here
  190 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4093:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4093 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:193:24: note: previous declaration is here
  193 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
basebackup_incremental.c:599:14: warning: declaration shadows a local variable [-Wshadow]
  599 |                                 unsigned        i;
      |                                                 ^
basebackup_incremental.c:273:8: note: previous declaration is here
  273 |         int                     i;
      |                                 ^
1 warning generated.
bootstrap.c:201:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  201 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2144:12: warning: declaration shadows a local variable [-Wshadow]
 2144 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
objectaddress.c:2161:12: warning: declaration shadows a local variable [-Wshadow]
 2161 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
objectaddress.c:2198:12: warning: declaration shadows a local variable [-Wshadow]
 2198 |                 bool       *nulls;
      |                             ^
objectaddress.c:2123:8: note: previous declaration is here
 2123 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
parse_target.c:1613:13: warning: declaration shadows a local variable [-Wshadow]
 1613 |                                         Index           levelsup;
      |                                                         ^
parse_target.c:1522:56: note: previous declaration is here
 1522 | expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
      |                                                        ^
parse_target.c:1671:13: warning: declaration shadows a local variable [-Wshadow]
 1671 |                                         Index           levelsup;
      |                                                         ^
parse_target.c:1522:56: note: previous declaration is here
 1522 | expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
      |                                                        ^
2 warnings generated.
extension.c:1406:13: warning: declaration shadows a local variable [-Wshadow]
 1406 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1200:20: note: previous declaration is here
 1200 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:39: note: previous declaration is here
   52 | CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
      |                                       ^
1 warning generated.
statscmds.c:321:16: warning: declaration shadows a local variable [-Wshadow]
  321 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:64:9: note: previous declaration is here
   64 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15721:20: warning: declaration shadows a local variable [-Wshadow]
 15721 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15630:67: note: previous declaration is here
 15630 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:15792:20: warning: declaration shadows a local variable [-Wshadow]
 15792 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15630:67: note: previous declaration is here
 15630 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
2 warnings generated.
trigger.c:1169:13: warning: declaration shadows a local variable [-Wshadow]
 1169 |                         Node       *qual;
      |                                     ^
trigger.c:189:11: note: previous declaration is here
  189 |         char       *qual;
      |                     ^
1 warning generated.
execExprInterp.c:474:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  474 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:112:21: note: previous declaration is here
  112 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4073:20: warning: declaration shadows a local variable [-Wshadow]
 4073 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3293:8: note: previous declaration is here
 3293 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:114:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  114 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:107:26: note: previous declaration is here
  107 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:280:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  280 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:384:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  384 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:443:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  443 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1246:12: warning: declaration shadows a local variable [-Wshadow]
 1246 |                 Plan       *plan;
      |                             ^
createplan.c:1218:13: note: previous declaration is here
 1218 |         Append     *plan;
      |                     ^
createplan.c:2559:12: warning: declaration shadows a local variable [-Wshadow]
 2559 |                 Plan       *plan;
      |                             ^
createplan.c:2549:13: note: previous declaration is here
 2549 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
dependencies.c:1192:14: warning: declaration shadows a local variable [-Wshadow]
 1192 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1168:87: note: previous declaration is here
 1168 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1226:22: warning: declaration shadows a local variable [-Wshadow]
 1226 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1168:87: note: previous declaration is here
 1168 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1053:10: warning: declaration shadows a local variable [-Wshadow]
 1053 |                         bool            isnull;
      |                                         ^
extended_stats.c:1005:11: note: previous declaration is here
 1005 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:963:12: warning: declaration shadows a local variable [-Wshadow]
  963 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:790:52: note: previous declaration is here
  790 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1210:11: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1200:8: note: previous declaration is here
 1200 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:572:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  572 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:596:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  596 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3131:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3131 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:645:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  645 |         int                     days;
      |                                 ^
datetime.c:84:19: note: previous declaration is here
   84 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
datetime.c:3288:32: warning: declaration shadows a variable in the global scope [-Wshadow]
 3288 | DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
      |                                ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
datetime.c:3343:36: warning: declaration shadows a variable in the global scope [-Wshadow]
 3343 | DecodeTimezoneNameToTz(const char *tzname)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
formatting.c:3076:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3076 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:538:17: warning: declaration shadows a local variable [-Wshadow]
  538 |                 JsonValueList found = {0};
      |                               ^
jsonpath_exec.c:527:11: note: previous declaration is here
  527 |         List       *found;
      |                     ^
jsonpath_exec.c:1880:24: warning: declaration shadows a local variable [-Wshadow]
 1880 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1781:15: note: previous declaration is here
 1781 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1891:24: warning: declaration shadows a local variable [-Wshadow]
 1891 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1781:15: note: previous declaration is here
 1781 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2067:17: warning: declaration shadows a local variable [-Wshadow]
 2067 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2029:21: note: previous declaration is here
 2029 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4137:16: warning: declaration shadows a local variable [-Wshadow]
 4137 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4110:41: note: previous declaration is here
 4110 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
5 warnings generated.
pg_upgrade_support.c:229:13: warning: declaration shadows a local variable [-Wshadow]
  229 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:186:11: note: previous declaration is here
  186 |         text       *extName;
      |                     ^
1 warning generated.
timestamp.c:493:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  493 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:562:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  562 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1533:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1533 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1535:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1535 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2134:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2134 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2545:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2545 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6243:11: warning: declaration shadows a local variable [-Wshadow]
 6243 |                         int64           val;
      |                                         ^
timestamp.c:6104:5: note: previous declaration is here
 6104 |                                 val;
      |                                 ^
timestamp.c:6332:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6332 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6570:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6570 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:4438:13: warning: declaration shadows a local variable [-Wshadow]
 4438 |                         char       *chunk_start;
      |                                     ^
varlena.c:4373:15: note: previous declaration is here
 4373 |                 const char *chunk_start = p;
      |                             ^
varlena.c:6067:14: warning: declaration shadows a local variable [-Wshadow]
 6067 |                                 char       *str;
      |                                             ^
varlena.c:5902:17: note: previous declaration is here
 5902 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:3988:11: warning: declaration shadows a local variable [-Wshadow]
 3988 |                                 int                     res;
      |                                                         ^
fe-connect.c:2912:14: note: previous declaration is here
 2912 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:956:10: warning: declaration shadows a local variable [-Wshadow]
  956 |                         int                     curr_nl_line;
      |                                                 ^
print.c:654:8: note: previous declaration is here
  654 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:817:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  817 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1049:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1049 |         FILE       *conf_file;
      |                     ^
initdb.c:180:14: note: previous declaration is here
  180 | static char *conf_file;
      |              ^
initdb.c:2143:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2143 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2202:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2202 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2265:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2265 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2517:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2517 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2597:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2597 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2597:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2597 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1015:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1015 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1285:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1285 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1600:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1600 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1699:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1699 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1736:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1736 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:336:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  336 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:374:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  374 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:452:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  452 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:744:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  744 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:877:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  877 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:939:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  939 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:993:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  993 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1047:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1047 | ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1178:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1178 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1217:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1217 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:371:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  371 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:134:20: note: previous declaration is here
  134 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:128:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  128 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1047:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1047 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1064:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1064 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1064:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1064 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:50:19: note: previous declaration is here
   50 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:875:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  875 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:93:14: note: previous declaration is here
   93 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1264:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1264 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1612:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1612 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1671:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1671 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1775:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1775 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:154:12: note: previous declaration is here
  154 | static int      strict_names = 0;
      |                 ^
pg_dump.c:10713:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 10713 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:10714:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 10714 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11231:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11231 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11232:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11232 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
pg_dump.c:12964:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 12964 |         CommentItem *comments;
       |                      ^
pg_dump.c:199:21: note: previous declaration is here
  199 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:12965:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 12965 |         int                     ncomments;
       |                                 ^
pg_dump.c:200:12: note: previous declaration is here
  200 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:533:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  533 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:1840:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 1840 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:120:14: note: previous declaration is here
  120 | static char *filename = NULL;
      |              ^
1 warning generated.
pg_resetwal.c:743:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  743 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:64:13: note: previous declaration is here
   64 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:555:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  555 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:628:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  628 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:74:23: note: previous declaration is here
   74 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:628:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  628 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:75:4: note: previous declaration is here
   75 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:40:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   40 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
xlogdesc.c:165:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  165 |                 int                     wal_level;
      |                                         ^
../../../src/include/access/xlog.h:96:24: note: previous declaration is here
   96 | extern PGDLLIMPORT int wal_level;
      |                        ^
2 warnings generated.
xlogreader.c:107:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  107 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:37:24: note: previous declaration is here
   37 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4654:11: warning: declaration shadows a local variable [-Wshadow]
 4654 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4622:25: note: previous declaration is here
 4622 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1761:17: warning: declaration shadows a local variable [-Wshadow]
 1761 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1579:16: note: previous declaration is here
 1579 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2287:13: warning: declaration shadows a local variable [-Wshadow]
 2287 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1571:37: note: previous declaration is here
 1571 | describeOneTableDetails(const char *schemaname,
      |                                     ^
2 warnings generated.
prompt.c:193:24: warning: declaration shadows a local variable [-Wshadow]
  193 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:68:27: note: previous declaration is here
   68 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:364:12: warning: declaration shadows a local variable [-Wshadow]
  364 |                 char       *p = destination;
      |                             ^
prompt.c:74:14: note: previous declaration is here
   74 |         const char *p;
      |                     ^
2 warnings generated.

  [text/plain] v19-shadow-warnings-master.txt (56.3K, 3-v19-shadow-warnings-master.txt)
  download | inline:
controldata_utils.c:53:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   53 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:190:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  190 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:702:16: warning: declaration shadows a local variable [-Wshadow]
  702 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:594:11: note: previous declaration is here
  594 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1168:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1168 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:287:13: note: previous declaration is here
  287 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1880:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1880 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3105:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3105 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3109:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3109 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3274:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3274 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4057:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4057 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
bootstrap.c:240:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  240 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2239:12: warning: declaration shadows a local variable [-Wshadow]
 2239 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2256:12: warning: declaration shadows a local variable [-Wshadow]
 2256 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2293:12: warning: declaration shadows a local variable [-Wshadow]
 2293 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
extension.c:1456:13: warning: declaration shadows a local variable [-Wshadow]
 1456 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1250:20: note: previous declaration is here
 1250 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:59: note: previous declaration is here
   52 | CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
      |                                                           ^
1 warning generated.
statscmds.c:352:16: warning: declaration shadows a local variable [-Wshadow]
  352 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:66:9: note: previous declaration is here
   66 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15965:20: warning: declaration shadows a local variable [-Wshadow]
 15965 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:16036:20: warning: declaration shadows a local variable [-Wshadow]
 16036 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:22613:15: warning: declaration shadows a local variable [-Wshadow]
 22613 |                 Constraint *constr;
       |                             ^
tablecmds.c:22526:15: note: previous declaration is here
 22526 |         TupleConstr *constr;
       |                      ^
3 warnings generated.
trigger.c:1170:13: warning: declaration shadows a local variable [-Wshadow]
 1170 |                         Node       *qual;
      |                                     ^
trigger.c:190:11: note: previous declaration is here
  190 |         char       *qual;
      |                     ^
1 warning generated.
wait.c:95:12: warning: declaration shadows a local variable [-Wshadow]
   95 |                         double          result;
      |                                         ^
wait.c:44:14: note: previous declaration is here
   44 |         const char *result = "<unset>";
      |                     ^
1 warning generated.
execExprInterp.c:476:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  476 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:114:21: note: previous declaration is here
  114 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4070:20: warning: declaration shadows a local variable [-Wshadow]
 4070 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3295:8: note: previous declaration is here
 3295 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:121:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  121 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:110:26: note: previous declaration is here
  110 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:284:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  284 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:388:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  388 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:447:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  447 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1238:12: warning: declaration shadows a local variable [-Wshadow]
 1238 |                 Plan       *plan;
      |                             ^
createplan.c:1210:13: note: previous declaration is here
 1210 |         Append     *plan;
      |                     ^
createplan.c:2410:12: warning: declaration shadows a local variable [-Wshadow]
 2410 |                 Plan       *plan;
      |                             ^
createplan.c:2400:13: note: previous declaration is here
 2400 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
datachecksum_state.c:549:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  549 |         bool            launcher_running;
      |                         ^
datachecksum_state.c:344:30: note: previous declaration is here
  344 | static volatile sig_atomic_t launcher_running = false;
      |                              ^
1 warning generated.
dependencies.c:1176:14: warning: declaration shadows a local variable [-Wshadow]
 1176 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1210:22: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1093:10: warning: declaration shadows a local variable [-Wshadow]
 1093 |                         bool            isnull;
      |                                         ^
extended_stats.c:1043:11: note: previous declaration is here
 1043 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:1297:12: warning: declaration shadows a local variable [-Wshadow]
 1297 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:1020:52: note: previous declaration is here
 1020 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1302:11: warning: declaration shadows a local variable [-Wshadow]
 1302 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1292:8: note: previous declaration is here
 1292 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:565:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  565 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:589:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  589 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3155:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3155 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:646:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  646 |         int                     days;
      |                                 ^
datetime.c:85:19: note: previous declaration is here
   85 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
1 warning generated.
formatting.c:3037:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3037 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:1928:24: warning: declaration shadows a local variable [-Wshadow]
 1928 |                                 JsonPathExecResult res;
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1946:24: warning: declaration shadows a local variable [-Wshadow]
 1946 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2131:17: warning: declaration shadows a local variable [-Wshadow]
 2131 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2084:21: note: previous declaration is here
 2084 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4447:16: warning: declaration shadows a local variable [-Wshadow]
 4447 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4420:41: note: previous declaration is here
 4420 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
4 warnings generated.
pg_upgrade_support.c:230:13: warning: declaration shadows a local variable [-Wshadow]
  230 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:187:11: note: previous declaration is here
  187 |         text       *extName;
      |                     ^
1 warning generated.
ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
 13100 |                                                 deparse_context context = {0};
       |                                                                 ^
ruleutils.c:12955:67: note: previous declaration is here
 12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
       |                                                                   ^
1 warning generated.
timestamp.c:485:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  485 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:554:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  554 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1527:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1527 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1529:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1529 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2128:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2128 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2521:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2521 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6219:11: warning: declaration shadows a local variable [-Wshadow]
 6219 |                         int64           val;
      |                                         ^
timestamp.c:6080:5: note: previous declaration is here
 6080 |                                 val;
      |                                 ^
timestamp.c:6308:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6308 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6573:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6573 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:3318:13: warning: declaration shadows a local variable [-Wshadow]
 3318 |                         char       *chunk_start;
      |                                     ^
varlena.c:3253:15: note: previous declaration is here
 3253 |                 const char *chunk_start = p;
      |                             ^
varlena.c:4949:14: warning: declaration shadows a local variable [-Wshadow]
 4949 |                                 char       *str;
      |                                             ^
varlena.c:4784:17: note: previous declaration is here
 4784 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:4005:11: warning: declaration shadows a local variable [-Wshadow]
 4005 |                                 int                     res;
      |                                                         ^
fe-connect.c:2929:14: note: previous declaration is here
 2929 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:936:10: warning: declaration shadows a local variable [-Wshadow]
  936 |                         int                     curr_nl_line;
      |                                                 ^
print.c:670:8: note: previous declaration is here
  670 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:831:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  831 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1065:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1065 |         FILE       *conf_file;
      |                     ^
initdb.c:181:14: note: previous declaration is here
  181 | static char *conf_file;
      |              ^
initdb.c:2166:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2166 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2225:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2225 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2288:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2288 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2540:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2540 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2620:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2620:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1016:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1016 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1272:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1272 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1587:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1587 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1686:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1686 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1723:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1723 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:337:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  337 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:375:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  375 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:453:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  453 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:745:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  745 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:878:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  878 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:940:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  940 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:994:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  994 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1048:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1048 | ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1179:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1179 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1218:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1218 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:414:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  414 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:157:20: note: previous declaration is here
  157 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:129:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  129 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1055:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1055 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:51:19: note: previous declaration is here
   51 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:876:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  876 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:94:14: note: previous declaration is here
   94 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1291:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1291 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1650:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1650 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1709:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1709 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1813:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1813 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:11005:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11005 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11006:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11006 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11563:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11563 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11564:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11564 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:13292:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 13292 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:13293:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 13293 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:746:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  746 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:2272:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 2272 |                                                            SimpleStringList *database_exclude_names)
      |                                                                              ^
pg_dumpall.c:136:25: note: previous declaration is here
  136 | static SimpleStringList database_exclude_names = {NULL, NULL};
      |                         ^
pg_dumpall.c:2352:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 2352 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:133:14: note: previous declaration is here
  133 | static char *filename = NULL;
      |              ^
pg_dumpall.c:2409:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 2409 |         ArchiveFormat archDumpFormat;
      |                       ^
pg_dumpall.c:141:22: note: previous declaration is here
  141 | static ArchiveFormat archDumpFormat = archNull;
      |                      ^
3 warnings generated.
pg_resetwal.c:754:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  754 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:65:13: note: previous declaration is here
   65 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:564:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  564 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:625:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:73:23: note: previous declaration is here
   73 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:625:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:74:4: note: previous declaration is here
   74 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4664:11: warning: declaration shadows a local variable [-Wshadow]
 4664 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4632:25: note: previous declaration is here
 4632 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1780:17: warning: declaration shadows a local variable [-Wshadow]
 1780 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:1941:17: warning: declaration shadows a local variable [-Wshadow]
 1941 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2427:13: warning: declaration shadows a local variable [-Wshadow]
 2427 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1588:37: note: previous declaration is here
 1588 | describeOneTableDetails(const char *schemaname,
      |                                     ^
3 warnings generated.
prompt.c:206:24: warning: declaration shadows a local variable [-Wshadow]
  206 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:71:27: note: previous declaration is here
   71 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:393:12: warning: declaration shadows a local variable [-Wshadow]
  393 |                 char       *p = destination;
      |                             ^
prompt.c:77:14: note: previous declaration is here
   77 |         const char *p;
      |                     ^
2 warnings generated.

  [text/plain] v19-shadow-warnings-patched.txt (54.3K, 4-v19-shadow-warnings-patched.txt)
  download | inline:
controldata_utils.c:53:29: warning: declaration shadows a variable in the global scope [-Wshadow]
   53 | get_controlfile(const char *DataDir, bool *crc_ok_p)
      |                             ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
controldata_utils.c:190:32: warning: declaration shadows a variable in the global scope [-Wshadow]
  190 | update_controlfile(const char *DataDir,
      |                                ^
../../src/include/miscadmin.h:175:26: note: previous declaration is here
  175 | extern PGDLLIMPORT char *DataDir;
      |                          ^
2 warnings generated.
pgtz.c:234:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | pg_tzset(const char *tzname)
      |                      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
pgtz.c:324:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  324 |         char            tzname[128];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
2 warnings generated.
brin.c:702:16: warning: declaration shadows a local variable [-Wshadow]
  702 |                         FmgrInfo   *tmp;
      |                                     ^
brin.c:594:11: note: previous declaration is here
  594 |         char       *tmp PG_USED_FOR_ASSERTS_ONLY;
      |                     ^
1 warning generated.
gistbuild.c:1161:23: warning: declaration shadows a local variable [-Wshadow]
 1161 |                         GISTPageSplitInfo *splitinfo = lfirst(lc);
      |                                            ^
gistbuild.c:1061:11: note: previous declaration is here
 1061 |         List       *splitinfo;
      |                     ^
1 warning generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
xlogrecovery.c:1168:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1168 |                                   bool *backupEndRequired, bool *backupFromStandby)
      |                                         ^
xlogrecovery.c:287:13: note: previous declaration is here
  287 | static bool backupEndRequired = false;
      |             ^
xlogrecovery.c:1880:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 1880 | ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
      |                                 ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3105:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 3105 | ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
      |                            ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
xlogrecovery.c:3109:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 3109 |         XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
      |                          ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:3274:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 3274 | XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
      |                               ^
xlogrecovery.c:192:25: note: previous declaration is here
  192 | static XLogReaderState *xlogreader = NULL;
      |                         ^
xlogrecovery.c:4057:38: warning: declaration shadows a variable in the global scope [-Wshadow]
 4057 | ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
      |                                      ^
xlogrecovery.c:195:24: note: previous declaration is here
  195 | static XLogPrefetcher *xlogprefetcher = NULL;
      |                        ^
6 warnings generated.
bootstrap.c:240:11: warning: declaration shadows a variable in the global scope [-Wshadow]
  240 |         char       *progname = argv[0];
      |                     ^
../../../src/include/postmaster/postmaster.h:88:32: note: previous declaration is here
   88 | extern PGDLLIMPORT const char *progname;
      |                                ^
1 warning generated.
objectaddress.c:2239:12: warning: declaration shadows a local variable [-Wshadow]
 2239 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2256:12: warning: declaration shadows a local variable [-Wshadow]
 2256 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
objectaddress.c:2293:12: warning: declaration shadows a local variable [-Wshadow]
 2293 |                 bool       *nulls;
      |                             ^
objectaddress.c:2218:8: note: previous declaration is here
 2218 |         bool            nulls[3];
      |                         ^
3 warnings generated.
pg_constraint.c:864:22: warning: declaration shadows a local variable [-Wshadow]
  864 |                         CookedConstraint *cooked;
      |                                           ^
pg_constraint.c:834:47: note: previous declaration is here
  834 | RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
      |                                               ^
1 warning generated.
extension.c:1456:13: warning: declaration shadows a local variable [-Wshadow]
 1456 |                         char       *schemaName = get_namespace_name(reqschema);
      |                                     ^
extension.c:1250:20: note: previous declaration is here
 1250 |                                                  const char *schemaName)
      |                                                              ^
1 warning generated.
schemacmds.c:208:12: warning: declaration shadows a local variable [-Wshadow]
  208 |                 Node       *stmt = (Node *) lfirst(parsetree_item);
      |                             ^
schemacmds.c:52:59: note: previous declaration is here
   52 | CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt,
      |                                                           ^
1 warning generated.
statscmds.c:352:16: warning: declaration shadows a local variable [-Wshadow]
  352 |                         Bitmapset  *attnums = NULL;
      |                                     ^
statscmds.c:66:9: note: previous declaration is here
   66 |         int16           attnums[STATS_MAX_DIMENSIONS];
      |                         ^
1 warning generated.
tablecmds.c:15965:20: warning: declaration shadows a local variable [-Wshadow]
 15965 |                                 AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
tablecmds.c:16036:20: warning: declaration shadows a local variable [-Wshadow]
 16036 |                                 AlterTableCmd *cmd = makeNode(AlterTableCmd);
       |                                                ^
tablecmds.c:15874:67: note: previous declaration is here
 15874 | ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
       |                                                                   ^
2 warnings generated.
trigger.c:1170:13: warning: declaration shadows a local variable [-Wshadow]
 1170 |                         Node       *qual;
      |                                     ^
trigger.c:190:11: note: previous declaration is here
  190 |         char       *qual;
      |                     ^
1 warning generated.
execExprInterp.c:476:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  476 |         static const void *const dispatch_table[] = {
      |                                  ^
execExprInterp.c:114:21: note: previous declaration is here
  114 | static const void **dispatch_table = NULL;
      |                     ^
1 warning generated.
nodeAgg.c:4070:20: warning: declaration shadows a local variable [-Wshadow]
 4070 |                 AggStatePerPhase phase = &aggstate->phases[phaseidx];
      |                                  ^
nodeAgg.c:3295:8: note: previous declaration is here
 3295 |         int                     phase;
      |                                 ^
1 warning generated.
nodeValuesscan.c:144:16: warning: declaration shadows a local variable [-Wshadow]
  144 |                         ExprState  *estate = (ExprState *) lfirst(lc);
      |                                     ^
nodeValuesscan.c:50:13: note: previous declaration is here
   50 |         EState     *estate;
      |                     ^
1 warning generated.
be-secure-common.c:121:44: warning: declaration shadows a variable in the global scope [-Wshadow]
  121 | check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
      |                                            ^
../../../src/include/libpq/libpq.h:110:26: note: previous declaration is here
  110 | extern PGDLLIMPORT char *ssl_key_file;
      |                          ^
1 warning generated.
main.c:284:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  284 | startup_hacks(const char *progname)
      |                           ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:388:18: warning: declaration shadows a variable in the global scope [-Wshadow]
  388 | help(const char *progname)
      |                  ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
main.c:447:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  447 | check_root(const char *progname)
      |                        ^
main.c:44:13: note: previous declaration is here
   44 | const char *progname;
      |             ^
3 warnings generated.
equivclass.c:879:16: warning: declaration shadows a local variable [-Wshadow]
  879 |                         RelOptInfo *rel = root->simple_rel_array[i];
      |                                     ^
equivclass.c:742:15: note: previous declaration is here
  742 |                                                  Relids rel,
      |                                                         ^
1 warning generated.
createplan.c:1238:12: warning: declaration shadows a local variable [-Wshadow]
 1238 |                 Plan       *plan;
      |                             ^
createplan.c:1210:13: note: previous declaration is here
 1210 |         Append     *plan;
      |                     ^
createplan.c:2410:12: warning: declaration shadows a local variable [-Wshadow]
 2410 |                 Plan       *plan;
      |                             ^
createplan.c:2400:13: note: previous declaration is here
 2400 |         Result     *plan;
      |                     ^
2 warnings generated.
partdesc.c:229:16: warning: declaration shadows a local variable [-Wshadow]
  229 |                         ScanKeyData key[1];
      |                                     ^
partdesc.c:149:15: note: previous declaration is here
  149 |         PartitionKey key = RelationGetPartitionKey(rel);
      |                      ^
1 warning generated.
dependencies.c:1176:14: warning: declaration shadows a local variable [-Wshadow]
 1176 |                 OpExpr     *expr = (OpExpr *) clause;
      |                             ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
dependencies.c:1210:22: warning: declaration shadows a local variable [-Wshadow]
 1210 |                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
      |                                    ^
dependencies.c:1152:87: note: previous declaration is here
 1152 | dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **expr)
      |                                                                                       ^
2 warnings generated.
extended_stats.c:1093:10: warning: declaration shadows a local variable [-Wshadow]
 1093 |                         bool            isnull;
      |                                         ^
extended_stats.c:1043:11: note: previous declaration is here
 1043 |         bool       *isnull;
      |                     ^
1 warning generated.
read_stream.c:1297:12: warning: declaration shadows a local variable [-Wshadow]
 1297 |                 void       *per_buffer_data;
      |                             ^
read_stream.c:1020:52: note: previous declaration is here
 1020 | read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
      |                                                    ^
1 warning generated.
bufmgr.c:1302:11: warning: declaration shadows a local variable [-Wshadow]
 1302 |                 uint32          flags = EB_SKIP_EXTENSION_LOCK;
      |                                 ^
bufmgr.c:1292:8: note: previous declaration is here
 1292 |         int                     flags;
      |                                 ^
1 warning generated.
date.c:565:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  565 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:589:9: warning: declaration shadows a variable in the global scope [-Wshadow]
  589 |         int32           days = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
date.c:3155:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 3155 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
3 warnings generated.
datetime.c:646:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  646 |         int                     days;
      |                                 ^
datetime.c:85:19: note: previous declaration is here
   85 | const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
      |                   ^
1 warning generated.
formatting.c:3037:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 3037 |                                         const char *const *months;
      |                                                            ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
1 warning generated.
jsonpath_exec.c:1928:24: warning: declaration shadows a local variable [-Wshadow]
 1928 |                                 JsonPathExecResult res;
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:1946:24: warning: declaration shadows a local variable [-Wshadow]
 1946 |                                 JsonPathExecResult res =
      |                                                    ^
jsonpath_exec.c:1829:15: note: previous declaration is here
 1829 |         JsonPathBool res;
      |                      ^
jsonpath_exec.c:2131:17: warning: declaration shadows a local variable [-Wshadow]
 2131 |                         JsonPathBool res = exec(pred, lval, rval, param);
      |                                      ^
jsonpath_exec.c:2084:21: note: previous declaration is here
 2084 |         JsonPathExecResult res;
      |                            ^
jsonpath_exec.c:4447:16: warning: declaration shadows a local variable [-Wshadow]
 4447 |                         ExprState  *state = lfirst_node(ExprState, exprlc);
      |                                     ^
jsonpath_exec.c:4420:41: note: previous declaration is here
 4420 | JsonTableInitOpaque(TableFuncScanState *state, int natts)
      |                                         ^
4 warnings generated.
pg_upgrade_support.c:230:13: warning: declaration shadows a local variable [-Wshadow]
  230 |                         char       *extName = TextDatumGetCString(textDatums[i]);
      |                                     ^
pg_upgrade_support.c:187:11: note: previous declaration is here
  187 |         text       *extName;
      |                     ^
1 warning generated.
ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
 13100 |                                                 deparse_context context = {0};
       |                                                                 ^
ruleutils.c:12955:67: note: previous declaration is here
 12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
       |                                                                   ^
1 warning generated.
timestamp.c:485:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  485 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:554:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  554 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:1527:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1527 |         int32           months = PG_GETARG_INT32(1);
      |                         ^
../../../../src/include/utils/datetime.h:259:38: note: previous declaration is here
  259 | extern PGDLLIMPORT const char *const months[];  /* months (3-char
      |                                      ^
timestamp.c:1529:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 1529 |         int32           days = PG_GETARG_INT32(3);
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:2128:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 2128 | dt2local(Timestamp dt, int timezone)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:106:13: note: previous declaration is here
  106 | extern long timezone __DARWIN_ALIAS(timezone);
      |             ^
timestamp.c:2521:9: warning: declaration shadows a variable in the global scope [-Wshadow]
 2521 |         int64           days;
      |                         ^
../../../../src/include/utils/datetime.h:261:38: note: previous declaration is here
  261 | extern PGDLLIMPORT const char *const days[];    /* days (full names) */
      |                                      ^
timestamp.c:6219:11: warning: declaration shadows a local variable [-Wshadow]
 6219 |                         int64           val;
      |                                         ^
timestamp.c:6080:5: note: previous declaration is here
 6080 |                                 val;
      |                                 ^
timestamp.c:6308:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6308 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
timestamp.c:6573:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 6573 |         char            tzname[TZ_STRLEN_MAX + 1];
      |                         ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
9 warnings generated.
varlena.c:3318:13: warning: declaration shadows a local variable [-Wshadow]
 3318 |                         char       *chunk_start;
      |                                     ^
varlena.c:3253:15: note: previous declaration is here
 3253 |                 const char *chunk_start = p;
      |                             ^
varlena.c:4949:14: warning: declaration shadows a local variable [-Wshadow]
 4949 |                                 char       *str;
      |                                             ^
varlena.c:4784:17: note: previous declaration is here
 4784 |         StringInfoData str;
      |                        ^
2 warnings generated.
inval.c:481:2: warning: declaration shadows a local variable [-Wshadow]
  481 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:474:28: note: previous declaration is here
  474 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:511:2: warning: declaration shadows a local variable [-Wshadow]
  511 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:508:28: note: previous declaration is here
  508 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:540:2: warning: declaration shadows a local variable [-Wshadow]
  540 |         ProcessMessageSubGroup(group, RelCacheMsgs,
      |         ^
inval.c:390:31: note: expanded from macro 'ProcessMessageSubGroup'
  390 |                         SharedInvalidationMessage *msg = \
      |                                                    ^
inval.c:536:28: note: previous declaration is here
  536 |         SharedInvalidationMessage msg;
      |                                   ^
inval.c:1053:2: warning: declaration shadows a local variable [-Wshadow]
 1053 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1059:2: warning: declaration shadows a local variable [-Wshadow]
 1059 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1065:2: warning: declaration shadows a local variable [-Wshadow]
 1065 |         ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1071:2: warning: declaration shadows a local variable [-Wshadow]
 1071 |         ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1012:66: note: previous declaration is here
 1012 | xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                                  ^
inval.c:1109:2: warning: declaration shadows a local variable [-Wshadow]
 1109 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
inval.c:1115:2: warning: declaration shadows a local variable [-Wshadow]
 1115 |         ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
      |         ^
inval.c:406:31: note: expanded from macro 'ProcessMessageSubGroupMulti'
  406 |                         SharedInvalidationMessage *msgs = \
      |                                                    ^
inval.c:1088:60: note: previous declaration is here
 1088 | inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
      |                                                            ^
9 warnings generated.
freepage.c:1589:9: warning: declaration shadows a local variable [-Wshadow]
 1589 |                 Size            result;
      |                                 ^
freepage.c:1480:28: note: previous declaration is here
 1480 |         FreePageBtreeSearchResult result;
      |                                   ^
1 warning generated.
fe-connect.c:4005:11: warning: declaration shadows a local variable [-Wshadow]
 4005 |                                 int                     res;
      |                                                         ^
fe-connect.c:2929:14: note: previous declaration is here
 2929 |         PGresult   *res;
      |                     ^
1 warning generated.
descriptor.c:75:46: warning: declaration shadows a variable in the global scope [-Wshadow]
   75 | add_descriptor(const char *name, const char *connection)
      |                                              ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:94:47: warning: declaration shadows a variable in the global scope [-Wshadow]
   94 | drop_descriptor(const char *name, const char *connection)
      |                                               ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
descriptor.c:125:49: warning: declaration shadows a variable in the global scope [-Wshadow]
  125 | lookup_descriptor(const char *name, const char *connection)
      |                                                 ^
./preproc_extern.h:39:14: note: previous declaration is here
   39 | extern char *connection;
      |              ^
3 warnings generated.
ecpg.c:35:18: warning: declaration shadows a variable in the global scope [-Wshadow]
   35 | help(const char *progname)
      |                  ^
ecpg.c:23:20: note: previous declaration is here
   23 | static const char *progname;
      |                    ^
1 warning generated.
preproc.y:182:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  182 | adjust_outofscope_cursor_vars(struct cursor *cur)
      |                                              ^
./preproc_extern.h:53:23: note: previous declaration is here
   53 | extern struct cursor *cur;
      |                       ^
preproc.y:494:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  494 |                         int initializer, int array)
      |                             ^
preproc.y:41:12: note: previous declaration is here
   41 | static int      initializer = 0;
      |                 ^
2 warnings generated.
print.c:936:10: warning: declaration shadows a local variable [-Wshadow]
  936 |                         int                     curr_nl_line;
      |                                                 ^
print.c:670:8: note: previous declaration is here
  670 |                            *curr_nl_line,
      |                             ^
1 warning generated.
findtimezone.c:234:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  234 | score_timezone(const char *tzname, struct tztry *tt)
      |                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:320:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  320 | perfect_timezone_match(const char *tzname, struct tztry *tt)
      |                                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1728:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1728 | validate_zone(const char *tzname)
      |                           ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
findtimezone.c:1759:14: warning: declaration shadows a variable in the global scope [-Wshadow]
 1759 |         const char *tzname;
      |                     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX26.2.sdk/usr/include/_time.h:101:25: note: previous declaration is here
  101 | extern char *_LIBC_CSTR tzname[_LIBC_COUNT(2)];
      |                         ^
4 warnings generated.
initdb.c:831:14: warning: declaration shadows a variable in the global scope [-Wshadow]
  831 |         const char *username;
      |                     ^
initdb.c:153:14: note: previous declaration is here
  153 | static char *username = NULL;
      |              ^
initdb.c:1065:11: warning: declaration shadows a variable in the global scope [-Wshadow]
 1065 |         FILE       *conf_file;
      |                     ^
initdb.c:181:14: note: previous declaration is here
  181 | static char *conf_file;
      |              ^
initdb.c:2166:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 2166 | locale_date_order(const char *locale)
      |                               ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2225:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 2225 | check_locale_name(int category, const char *locale, char **canonname)
      |                                             ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2288:35: warning: declaration shadows a variable in the global scope [-Wshadow]
 2288 | check_locale_encoding(const char *locale, int user_enc)
      |                                   ^
initdb.c:140:14: note: previous declaration is here
  140 | static char *locale = NULL;
      |              ^
initdb.c:2540:19: warning: declaration shadows a variable in the global scope [-Wshadow]
 2540 | usage(const char *progname)
      |                   ^
initdb.c:175:20: note: previous declaration is here
  175 | static const char *progname;
      |                    ^
initdb.c:2620:33: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                 ^
initdb.c:158:20: note: previous declaration is here
  158 | static const char *authmethodlocal = NULL;
      |                    ^
initdb.c:2620:62: warning: declaration shadows a variable in the global scope [-Wshadow]
 2620 | check_need_password(const char *authmethodlocal, const char *authmethodhost)
      |                                                              ^
initdb.c:157:20: note: previous declaration is here
  157 | static const char *authmethodhost = NULL;
      |                    ^
8 warnings generated.
pg_amcheck.c:1183:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1183 | help(const char *progname)
      |                  ^
pg_amcheck.c:141:20: note: previous declaration is here
  141 | static const char *progname = NULL;
      |                    ^
1 warning generated.
pg_basebackup.c:1016:25: warning: declaration shadows a variable in the global scope [-Wshadow]
 1016 | ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
      |                         ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1272:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1272 | ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1587:24: warning: declaration shadows a variable in the global scope [-Wshadow]
 1587 | ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1686:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1686 | ReceiveBackupManifest(PGconn *conn)
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_basebackup.c:1723:39: warning: declaration shadows a variable in the global scope [-Wshadow]
 1723 | ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
      |                                       ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
5 warnings generated.
receivelog.c:337:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  337 | sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:375:40: warning: declaration shadows a variable in the global scope [-Wshadow]
  375 | CheckServerVersionForStreaming(PGconn *conn)
      |                                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:453:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  453 | ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:745:26: warning: declaration shadows a variable in the global scope [-Wshadow]
  745 | HandleCopyStream(PGconn *conn, StreamCtl *stream,
      |                          ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:878:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  878 | CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
      |                        ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:940:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  940 | CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:994:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  994 | ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1048:27: warning: declaration shadows a variable in the global scope [-Wshadow]
 1048 | ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
      |                           ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1179:31: warning: declaration shadows a variable in the global scope [-Wshadow]
 1179 | HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
      |                               ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
receivelog.c:1218:29: warning: declaration shadows a variable in the global scope [-Wshadow]
 1218 | CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
      |                             ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
10 warnings generated.
streamutil.c:276:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  276 | RetrieveWalSegSize(PGconn *conn)
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:355:35: warning: declaration shadows a variable in the global scope [-Wshadow]
  355 | RetrieveDataDirCreatePerm(PGconn *conn)
      |                                   ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:409:27: warning: declaration shadows a variable in the global scope [-Wshadow]
  409 | RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
      |                           ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:490:28: warning: declaration shadows a variable in the global scope [-Wshadow]
  490 | GetSlotInformation(PGconn *conn, const char *slot_name,
      |                            ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:584:31: warning: declaration shadows a variable in the global scope [-Wshadow]
  584 | CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
      |                               ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
streamutil.c:697:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  697 | DropReplicationSlot(PGconn *conn, const char *slot_name)
      |                             ^
streamutil.c:52:12: note: previous declaration is here
   52 | PGconn     *conn = NULL;
      |             ^
6 warnings generated.
pg_createsubscriber.c:414:46: warning: declaration shadows a variable in the global scope [-Wshadow]
  414 | get_exec_path(const char *argv0, const char *progname)
      |                                              ^
pg_createsubscriber.c:157:20: note: previous declaration is here
  157 | static const char *progname;
      |                    ^
1 warning generated.
pg_receivewal.c:280:11: warning: declaration shadows a local variable [-Wshadow]
  280 |                 uint32          tli;
      |                                 ^
pg_receivewal.c:268:28: note: previous declaration is here
  268 | FindStreamingStart(uint32 *tli)
      |                            ^
1 warning generated.
pg_recvlogical.c:129:22: warning: declaration shadows a variable in the global scope [-Wshadow]
  129 | sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
      |                      ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1055:30: warning: declaration shadows a variable in the global scope [-Wshadow]
 1055 | flushAndSendFeedback(PGconn *conn, TimestampTz *now)
      |                              ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:28: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                            ^
./streamutil.h:30:16: note: previous declaration is here
   30 | extern PGconn *conn;
      |                ^
pg_recvlogical.c:1071:45: warning: declaration shadows a variable in the global scope [-Wshadow]
 1071 | prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
      |                                             ^
pg_recvlogical.c:51:19: note: previous declaration is here
   51 | static XLogRecPtr endpos = InvalidXLogRecPtr;
      |                   ^
4 warnings generated.
pg_controldata.c:73:24: warning: declaration shadows a variable in the global scope [-Wshadow]
   73 | wal_level_str(WalLevel wal_level)
      |                        ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
pg_ctl.c:876:36: warning: declaration shadows a variable in the global scope [-Wshadow]
  876 | find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
      |                                    ^
pg_ctl.c:94:14: note: previous declaration is here
   94 | static char *argv0 = NULL;
      |              ^
1 warning generated.
pg_dump.c:1291:18: warning: declaration shadows a variable in the global scope [-Wshadow]
 1291 | help(const char *progname)
      |                  ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
pg_dump.c:1650:13: warning: declaration shadows a variable in the global scope [-Wshadow]
 1650 |                                                         bool strict_names)
      |                                                              ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1709:16: warning: declaration shadows a variable in the global scope [-Wshadow]
 1709 |                                                            bool strict_names)
      |                                                                 ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:1813:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 1813 |                                                    bool strict_names, bool with_child_tables)
      |                                                         ^
pg_dump.c:157:12: note: previous declaration is here
  157 | static int      strict_names = 0;
      |                 ^
pg_dump.c:11005:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11005 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11006:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11006 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:11563:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 11563 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:11564:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 11564 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
pg_dump.c:13292:15: warning: declaration shadows a variable in the global scope [-Wshadow]
 13292 |         CommentItem *comments;
       |                      ^
pg_dump.c:202:21: note: previous declaration is here
  202 | static CommentItem *comments = NULL;
      |                     ^
pg_dump.c:13293:8: warning: declaration shadows a variable in the global scope [-Wshadow]
 13293 |         int                     ncomments;
       |                                 ^
pg_dump.c:203:12: note: previous declaration is here
  203 | static int      ncomments = 0;
      |                 ^
10 warnings generated.
connectdb.c:42:63: warning: declaration shadows a variable in the global scope [-Wshadow]
   42 |                                 trivalue prompt_password, bool fail_on_error, const char *progname,
      |                                                                                           ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_restore.c:746:19: warning: declaration shadows a variable in the global scope [-Wshadow]
  746 | usage(const char *progname)
      |                   ^
./pg_backup_utils.h:28:20: note: previous declaration is here
   28 | extern const char *progname;
      |                    ^
1 warning generated.
pg_dumpall.c:2352:34: warning: declaration shadows a variable in the global scope [-Wshadow]
 2352 | read_dumpall_filters(const char *filename, SimpleStringList *pattern)
      |                                  ^
pg_dumpall.c:133:14: note: previous declaration is here
  133 | static char *filename = NULL;
      |              ^
1 warning generated.
pg_resetwal.c:754:25: warning: declaration shadows a variable in the global scope [-Wshadow]
  754 | PrintControlValues(bool guessed)
      |                         ^
pg_resetwal.c:65:13: note: previous declaration is here
   65 | static bool guessed = false;    /* T if we had to guess at any values */
      |             ^
1 warning generated.
file_ops.c:189:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  189 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:208:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  208 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:231:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  231 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:245:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  245 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:259:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  259 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
file_ops.c:273:8: warning: declaration shadows a variable in the global scope [-Wshadow]
  273 |         char            dstpath[MAXPGPATH];
      |                         ^
file_ops.c:32:13: note: previous declaration is here
   32 | static char dstpath[MAXPGPATH] = "";
      |             ^
6 warnings generated.
pg_rewind.c:92:19: warning: declaration shadows a variable in the global scope [-Wshadow]
   92 | usage(const char *progname)
      |                   ^
pg_rewind.c:63:20: note: previous declaration is here
   63 | static const char *progname;
      |                    ^
pg_rewind.c:564:51: warning: declaration shadows a variable in the global scope [-Wshadow]
  564 | perform_rewind(filemap_t *filemap, rewind_source *source,
      |                                                   ^
pg_rewind.c:89:23: note: previous declaration is here
   89 | static rewind_source *source;
      |                       ^
2 warnings generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pg_test_fsync.c:625:29: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                             ^
pg_test_fsync.c:73:23: note: previous declaration is here
   73 | static struct timeval start_t,
      |                       ^
pg_test_fsync.c:625:53: warning: declaration shadows a variable in the global scope [-Wshadow]
  625 | print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
      |                                                     ^
pg_test_fsync.c:74:4: note: previous declaration is here
   74 |                         stop_t;
      |                         ^
2 warnings generated.
xlogdesc.c:41:26: warning: declaration shadows a variable in the global scope [-Wshadow]
   41 | get_wal_level_string(int wal_level)
      |                          ^
../../../src/include/access/xlog.h:98:24: note: previous declaration is here
   98 | extern PGDLLIMPORT int wal_level;
      |                        ^
1 warning generated.
xlogreader.c:108:24: warning: declaration shadows a variable in the global scope [-Wshadow]
  108 | XLogReaderAllocate(int wal_segment_size, const char *waldir,
      |                        ^
../../../src/include/access/xlog.h:38:24: note: previous declaration is here
   38 | extern PGDLLIMPORT int wal_segment_size;
      |                        ^
1 warning generated.
pgbench.c:4664:11: warning: declaration shadows a local variable [-Wshadow]
 4664 |                         int64           skipped = 0;
      |                                         ^
pgbench.c:4632:25: note: previous declaration is here
 4632 |           StatsData *agg, bool skipped, double latency, double lag)
      |                                ^
1 warning generated.
describe.c:1780:17: warning: declaration shadows a local variable [-Wshadow]
 1780 |                 printQueryOpt myopt = pset.popt;
      |                               ^
describe.c:1596:16: note: previous declaration is here
 1596 |         printTableOpt myopt = pset.popt.topt;
      |                       ^
describe.c:2427:13: warning: declaration shadows a local variable [-Wshadow]
 2427 |                         char       *schemaname = PQgetvalue(result, 0, 0);
      |                                     ^
describe.c:1588:37: note: previous declaration is here
 1588 | describeOneTableDetails(const char *schemaname,
      |                                     ^
2 warnings generated.
prompt.c:206:24: warning: declaration shadows a local variable [-Wshadow]
  206 |                                                 PGpipelineStatus status = PQpipelineStatus(pset.db);
      |                                                                  ^
prompt.c:71:27: note: previous declaration is here
   71 | get_prompt(promptStatus_t status, ConditionalStack cstack)
      |                           ^
prompt.c:393:12: warning: declaration shadows a local variable [-Wshadow]
  393 |                 char       *p = destination;
      |                             ^
prompt.c:77:14: note: previous declaration is here
   77 |         const char *p;
      |                     ^
2 warnings generated.

  [application/octet-stream] v1-0001-Cleanup-v19-introduced-shadow-variable-warnings.patch (8.6K, 5-v1-0001-Cleanup-v19-introduced-shadow-variable-warnings.patch)
  download | inline diff:
From dd204c1fcc6bdec7ba73f55afcb26a3d39c96bd5 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 22 Apr 2026 11:33:16 +0800
Subject: [PATCH v1] Cleanup v19 introduced shadow-variable warnings

Suggested-by: David Rowley <[email protected]>
Author: Chao Li <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/commands/tablecmds.c            | 28 ++++++++++-----------
 src/backend/commands/wait.c                 | 12 ++++-----
 src/backend/postmaster/datachecksum_state.c |  8 +++---
 src/bin/pg_dump/pg_dumpall.c                | 26 +++++++++----------
 src/bin/psql/describe.c                     | 12 ++++-----
 5 files changed, 43 insertions(+), 43 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 1068d7c7b6a..ec8207687c0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -22610,7 +22610,7 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 		bool		ccvalid = constr->check[ccnum].ccvalid;
 		Node	   *ccbin_node;
 		bool		found_whole_row;
-		Constraint *constr;
+		Constraint *con;
 
 		/*
 		 * The partitioned table can not have a NO INHERIT check constraint
@@ -22632,19 +22632,19 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 				 ccname,
 				 RelationGetRelationName(parent_rel));
 
-		constr = makeNode(Constraint);
-		constr->contype = CONSTR_CHECK;
-		constr->conname = pstrdup(ccname);
-		constr->deferrable = false;
-		constr->initdeferred = false;
-		constr->is_enforced = ccenforced;
-		constr->skip_validation = !ccvalid;
-		constr->initially_valid = ccvalid;
-		constr->is_no_inherit = ccnoinherit;
-		constr->raw_expr = NULL;
-		constr->cooked_expr = nodeToString(ccbin_node);
-		constr->location = -1;
-		constraints = lappend(constraints, constr);
+		con = makeNode(Constraint);
+		con->contype = CONSTR_CHECK;
+		con->conname = pstrdup(ccname);
+		con->deferrable = false;
+		con->initdeferred = false;
+		con->is_enforced = ccenforced;
+		con->skip_validation = !ccvalid;
+		con->initially_valid = ccvalid;
+		con->is_no_inherit = ccnoinherit;
+		con->raw_expr = NULL;
+		con->cooked_expr = nodeToString(ccbin_node);
+		con->location = -1;
+		constraints = lappend(constraints, con);
 	}
 
 	/* Install all CHECK constraints. */
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 382d5c2d44f..7fe53a6f045 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -92,7 +92,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -100,7 +100,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -113,20 +113,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			val = rint(val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(val) || !FLOAT8_FITS_IN_INT64(val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index b3e99170669..9f9a2f9c40e 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -546,7 +546,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 {
 	BackgroundWorker bgw;
 	BackgroundWorkerHandle *bgw_handle;
-	bool		launcher_running;
+	bool		is_running;
 	DataChecksumsWorkerOperation launcher_running_op;
 
 #ifdef USE_ASSERT_CHECKING
@@ -565,8 +565,8 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	DataChecksumState->launch_cost_limit = cost_limit;
 
 	/* Is the launcher already running? If so, what is it doing? */
-	launcher_running = DataChecksumState->launcher_running;
-	if (launcher_running)
+	is_running = DataChecksumState->launcher_running;
+	if (is_running)
 		launcher_running_op = DataChecksumState->operation;
 
 	LWLockRelease(DataChecksumsWorkerLock);
@@ -589,7 +589,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	 * already in the desired state, i.e. if the checksums are already enabled
 	 * and you call pg_enable_data_checksums().
 	 */
-	if (!launcher_running)
+	if (!is_running)
 	{
 		/*
 		 * Prepare the BackgroundWorker and launch it.
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 9e904f76baa..847310f258d 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -83,7 +83,7 @@ static void buildShSecLabels(PGconn *conn,
 							 PQExpBuffer buffer);
 static void executeCommand(PGconn *conn, const char *query);
 static void check_for_invalid_global_names(PGconn *conn,
-										   SimpleStringList *database_exclude_names);
+										   SimpleStringList *db_exclude_names);
 static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
 								   SimpleStringList *names);
 static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
@@ -2269,7 +2269,7 @@ executeCommand(PGconn *conn, const char *query)
  */
 static void
 check_for_invalid_global_names(PGconn *conn,
-							   SimpleStringList *database_exclude_names)
+							   SimpleStringList *db_exclude_names)
 {
 	PGresult   *res;
 	int			i;
@@ -2296,7 +2296,7 @@ check_for_invalid_global_names(PGconn *conn,
 
 		/* Skip excluded databases since they won't be in map.dat */
 		if (strcmp(objtype, "database") == 0 &&
-			simple_string_list_member(database_exclude_names, objname))
+			simple_string_list_member(db_exclude_names, objname))
 			continue;
 
 		if (strpbrk(objname, "\n\r"))
@@ -2406,29 +2406,29 @@ read_dumpall_filters(const char *filename, SimpleStringList *pattern)
 static ArchiveFormat
 parseDumpFormat(const char *format)
 {
-	ArchiveFormat archDumpFormat;
+	ArchiveFormat archFormat;
 
 	if (pg_strcasecmp(format, "c") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "custom") == 0)
-		archDumpFormat = archCustom;
+		archFormat = archCustom;
 	else if (pg_strcasecmp(format, "d") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "directory") == 0)
-		archDumpFormat = archDirectory;
+		archFormat = archDirectory;
 	else if (pg_strcasecmp(format, "p") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "plain") == 0)
-		archDumpFormat = archNull;
+		archFormat = archNull;
 	else if (pg_strcasecmp(format, "t") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else if (pg_strcasecmp(format, "tar") == 0)
-		archDumpFormat = archTar;
+		archFormat = archTar;
 	else
 		pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
 				 format);
 
-	return archDumpFormat;
+	return archFormat;
 }
 
 /*
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index dd1179ef927..974dbc5ec2c 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1938,7 +1938,7 @@ describeOneTableDetails(const char *schemaname,
 	 */
 	if (tableinfo.relkind == RELKIND_PROPGRAPH)
 	{
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt mypopt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		printfPQExpBuffer(&buf, "/* %s */\n", _("Get property graph information"));
@@ -1993,12 +1993,12 @@ describeOneTableDetails(const char *schemaname,
 			}
 		}
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		mypopt.footers = footers;
+		mypopt.topt.default_footer = false;
+		mypopt.title = title.data;
+		mypopt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &mypopt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
-- 
2.50.1 (Apple Git-155)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-22 06:32  Peter Smith <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 1 reply; 30+ messages in thread

From: Peter Smith @ 2026-04-22 06:32 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Álvaro Herrera <[email protected]>; David Rowley <[email protected]>; Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>

Hi Chao-San.

A couple of comments for your v1-0001 cleanup patch.

======
src/bin/pg_dump/pg_dumpall.c

I guess you were just making the minimal changes, but I thought
parseDumpFormat could have been simplified more by removing that local
variable entirely.

BEFORE
if (pg_strcasecmp(format, "c") == 0)
  archFormat = archCustom;
else if (pg_strcasecmp(format, "custom") == 0)
  archFormat = archCustom;
else if (pg_strcasecmp(format, "d") == 0)
  archFormat = archDirectory;
else if (pg_strcasecmp(format, "directory") == 0)
  archFormat = archDirectory;
else if (pg_strcasecmp(format, "p") == 0)
  archFormat = archNull;
else if (pg_strcasecmp(format, "plain") == 0)
  archFormat = archNull;
else if (pg_strcasecmp(format, "t") == 0)
  archFormat = archTar;
else if (pg_strcasecmp(format, "tar") == 0)
  archFormat = archTar;

SUGGESTION
if (pg_strcasecmp(format, "c") == 0 ||
  pg_strcasecmp(format, "custom") == 0)
  return archCustom;

if (pg_strcasecmp(format, "d") == 0 ||
  pg_strcasecmp(format, "directory") == 0)
  return archDirectory;

if (pg_strcasecmp(format, "p") == 0 ||
  pg_strcasecmp(format, "plain") == 0)
  return archNull;

if (pg_strcasecmp(format, "t") == 0 ||
  pg_strcasecmp(format, "tar") == 0)
  return archTar;

======
src/bin/psql/describe.c

I know you were addressing only "new" issues, but it seemed a bit
strange to fix only this one when there was the same issue earlier
(~line 1780) in the same function.

if (tableinfo.relkind == RELKIND_SEQUENCE)
{
 PGresult   *result = NULL;
 printQueryOpt myopt = pset.popt;

======
Kind Regards,
Peter Smith.
Fujitsu Australia





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-22 06:34  Yuchen Li <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 0 replies; 30+ messages in thread

From: Yuchen Li @ 2026-04-22 06:34 UTC (permalink / raw)
  To: Chao Li <[email protected]>; Álvaro Herrera <[email protected]>; David Rowley <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>

On 4/22/2026 1:14 PM, Chao Li wrote:
>
>> On Apr 21, 2026, at 21:51, Álvaro Herrera <[email protected]> wrote:
>>
>> On 2026-Apr-21, David Rowley wrote:
>>
>>> On Tue, 21 Apr 2026 at 19:02, Chao Li <[email protected]> wrote:
>>>> PFA v8 - rebased and fixed a few new occurrences.
>>> Which of these are new to v19?  Can you separate those ones out? IMO,
>>> we should commit at least those, as those won't cause any backpatching
>>> pain.
>> I agree.  The others are v20 material.
>>
> Sounds reasonable.
>
> The attached new v1 patch fixes the v19-only shadow warnings. There are not many. I strictly limited it to warnings newly introduced in v19, without touching any pre-existing ones, even where an old occurrence is very close to a new one.
>
> I intentionally left out one occurrence in ruleutils.c:
> ```
> ruleutils.c:13100:23: warning: declaration shadows a local variable [-Wshadow]
>   13100 |                                                 deparse_context context = {0};
>         |                                                                 ^
> ruleutils.c:12955:67: note: previous declaration is here
>   12955 | get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
>         |                                                                   ^
> 1 warning generated.
> ```
>
> I saw there is a thread [1] that will remove this deparse_context context = {0};, so I skipped this one to avoid a potential conflict.
>
> Besides the patch file, I am also attaching three files for reference:
>
> * v18-shadow-warnings.txt - all shadow warnings from branch REL_18_STABLE
> * v19-shadow-warnings-master.txt - all shadow warnings from current master (9d3e094f12c)
> * v19-shadow-warnings-patched.txt - all shadow warnings after applying this v1 patch
>
> Except for the one in ruleutils.c, v19-shadow-warnings-patched.txt is a pure subset of v18-shadow-warnings.txt. You don't need to read these large files; they are attached only for reference.
>
> I will recreate the previous patch set for v20.
>
>> Specifically about 0003 (v20 material for sure, as this is ancient
>> code), I don't like this patch very much.  I wonder if it would be
>> possible to do away with the idea of using these codeFragment things
>> without introducing a performance issue here.  Is that doable by turning
>> these macros into static functions?
>>
> Okay, I will remove 0003 from this patch set, and use a separate patch to try converting the macros to static functions.
>
> [1] http://postgr.es/m/CAHg+QDcLVa2iBnggkHxY4itZbXtDMfsYHEjnCUYe9hNbnxDi-w@mail.gmail.com
>
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
>
>
>
>
The v1 patch LGTM, and “make check-world” passed after applying it.

Regards,
Yuchen Li







^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-22 07:24  Chao Li <[email protected]>
  parent: Peter Smith <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2026-04-22 07:24 UTC (permalink / raw)
  To: Peter Smith <[email protected]>; Álvaro Herrera <[email protected]>; David Rowley <[email protected]>; +Cc: Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>



> On Apr 22, 2026, at 14:32, Peter Smith <[email protected]> wrote:
> 
> Hi Chao-San.
> 
> A couple of comments for your v1-0001 cleanup patch.

Hi Peter, thank you very much for reviewing.

> 
> ======
> src/bin/pg_dump/pg_dumpall.c
> 
> I guess you were just making the minimal changes, but I thought
> parseDumpFormat could have been simplified more by removing that local
> variable entirely.
> 
> BEFORE
> if (pg_strcasecmp(format, "c") == 0)
>  archFormat = archCustom;
> else if (pg_strcasecmp(format, "custom") == 0)
>  archFormat = archCustom;
> else if (pg_strcasecmp(format, "d") == 0)
>  archFormat = archDirectory;
> else if (pg_strcasecmp(format, "directory") == 0)
>  archFormat = archDirectory;
> else if (pg_strcasecmp(format, "p") == 0)
>  archFormat = archNull;
> else if (pg_strcasecmp(format, "plain") == 0)
>  archFormat = archNull;
> else if (pg_strcasecmp(format, "t") == 0)
>  archFormat = archTar;
> else if (pg_strcasecmp(format, "tar") == 0)
>  archFormat = archTar;
> 
> SUGGESTION
> if (pg_strcasecmp(format, "c") == 0 ||
>  pg_strcasecmp(format, "custom") == 0)
>  return archCustom;
> 
> if (pg_strcasecmp(format, "d") == 0 ||
>  pg_strcasecmp(format, "directory") == 0)
>  return archDirectory;
> 
> if (pg_strcasecmp(format, "p") == 0 ||
>  pg_strcasecmp(format, "plain") == 0)
>  return archNull;
> 
> if (pg_strcasecmp(format, "t") == 0 ||
>  pg_strcasecmp(format, "tar") == 0)
>  return archTar;
> 

Yes, I was trying to keep the changes minimal. Consider that if we later submit a trivial patch just to refactor this function as you suggested, it might be hard to get it through the process. So, as touching the code, it might make sense to do the refactoring now.

Looks like ending a non-void function with pg_fatal() does not trigger a compile warning. I also noticed that get_encoding_id() in initdb.c returns int and has pg_fatal() as its last statement, which makes me more comfortable doing this refactoring.

> ======
> src/bin/psql/describe.c
> 
> I know you were addressing only "new" issues, but it seemed a bit
> strange to fix only this one when there was the same issue earlier
> (~line 1780) in the same function.
> 
> if (tableinfo.relkind == RELKIND_SEQUENCE)
> {
> PGresult   *result = NULL;
> printQueryOpt myopt = pset.popt;
> 

I also found that a bit odd, which is why I specially said in my previous email: "I strictly limited it to warnings newly introduced in v19, without touching any pre-existing ones, even where an old occurrence is very close to a new one.”

So for this case, I’d prefer to hear David’s or Alvaro’s view, since they asked to limit this to v19-only occurrences.

PFA v2: refactoring parseDumpFormat as Peter suggested.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Attachments:

  [application/octet-stream] v2-0001-Cleanup-v19-introduced-shadow-variable-warnings.patch (8.9K, 2-v2-0001-Cleanup-v19-introduced-shadow-variable-warnings.patch)
  download | inline diff:
From ba90cf5ce8dd34594234651bed461f26e5b7f99e Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 22 Apr 2026 11:33:16 +0800
Subject: [PATCH v2] Cleanup v19 introduced shadow-variable warnings

Suggested-by: David Rowley <[email protected]>
Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Reviewed-by: Yuchen Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/commands/tablecmds.c            | 28 ++++++-------
 src/backend/commands/wait.c                 | 12 +++---
 src/backend/postmaster/datachecksum_state.c |  8 ++--
 src/bin/pg_dump/pg_dumpall.c                | 45 +++++++++------------
 src/bin/psql/describe.c                     | 12 +++---
 5 files changed, 50 insertions(+), 55 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 1068d7c7b6a..ec8207687c0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -22610,7 +22610,7 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 		bool		ccvalid = constr->check[ccnum].ccvalid;
 		Node	   *ccbin_node;
 		bool		found_whole_row;
-		Constraint *constr;
+		Constraint *con;
 
 		/*
 		 * The partitioned table can not have a NO INHERIT check constraint
@@ -22632,19 +22632,19 @@ createTableConstraints(List **wqueue, AlteredTableInfo *tab,
 				 ccname,
 				 RelationGetRelationName(parent_rel));
 
-		constr = makeNode(Constraint);
-		constr->contype = CONSTR_CHECK;
-		constr->conname = pstrdup(ccname);
-		constr->deferrable = false;
-		constr->initdeferred = false;
-		constr->is_enforced = ccenforced;
-		constr->skip_validation = !ccvalid;
-		constr->initially_valid = ccvalid;
-		constr->is_no_inherit = ccnoinherit;
-		constr->raw_expr = NULL;
-		constr->cooked_expr = nodeToString(ccbin_node);
-		constr->location = -1;
-		constraints = lappend(constraints, constr);
+		con = makeNode(Constraint);
+		con->contype = CONSTR_CHECK;
+		con->conname = pstrdup(ccname);
+		con->deferrable = false;
+		con->initdeferred = false;
+		con->is_enforced = ccenforced;
+		con->skip_validation = !ccvalid;
+		con->initially_valid = ccvalid;
+		con->is_no_inherit = ccnoinherit;
+		con->raw_expr = NULL;
+		con->cooked_expr = nodeToString(ccbin_node);
+		con->location = -1;
+		constraints = lappend(constraints, con);
 	}
 
 	/* Install all CHECK constraints. */
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 382d5c2d44f..7fe53a6f045 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -92,7 +92,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -100,7 +100,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -113,20 +113,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			val = rint(val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(val) || !FLOAT8_FITS_IN_INT64(val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index b3e99170669..9f9a2f9c40e 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -546,7 +546,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 {
 	BackgroundWorker bgw;
 	BackgroundWorkerHandle *bgw_handle;
-	bool		launcher_running;
+	bool		is_running;
 	DataChecksumsWorkerOperation launcher_running_op;
 
 #ifdef USE_ASSERT_CHECKING
@@ -565,8 +565,8 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	DataChecksumState->launch_cost_limit = cost_limit;
 
 	/* Is the launcher already running? If so, what is it doing? */
-	launcher_running = DataChecksumState->launcher_running;
-	if (launcher_running)
+	is_running = DataChecksumState->launcher_running;
+	if (is_running)
 		launcher_running_op = DataChecksumState->operation;
 
 	LWLockRelease(DataChecksumsWorkerLock);
@@ -589,7 +589,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	 * already in the desired state, i.e. if the checksums are already enabled
 	 * and you call pg_enable_data_checksums().
 	 */
-	if (!launcher_running)
+	if (!is_running)
 	{
 		/*
 		 * Prepare the BackgroundWorker and launch it.
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 9e904f76baa..ba780bd6c29 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -83,7 +83,7 @@ static void buildShSecLabels(PGconn *conn,
 							 PQExpBuffer buffer);
 static void executeCommand(PGconn *conn, const char *query);
 static void check_for_invalid_global_names(PGconn *conn,
-										   SimpleStringList *database_exclude_names);
+										   SimpleStringList *db_exclude_names);
 static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
 								   SimpleStringList *names);
 static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
@@ -2269,7 +2269,7 @@ executeCommand(PGconn *conn, const char *query)
  */
 static void
 check_for_invalid_global_names(PGconn *conn,
-							   SimpleStringList *database_exclude_names)
+							   SimpleStringList *db_exclude_names)
 {
 	PGresult   *res;
 	int			i;
@@ -2296,7 +2296,7 @@ check_for_invalid_global_names(PGconn *conn,
 
 		/* Skip excluded databases since they won't be in map.dat */
 		if (strcmp(objtype, "database") == 0 &&
-			simple_string_list_member(database_exclude_names, objname))
+			simple_string_list_member(db_exclude_names, objname))
 			continue;
 
 		if (strpbrk(objname, "\n\r"))
@@ -2406,29 +2406,24 @@ read_dumpall_filters(const char *filename, SimpleStringList *pattern)
 static ArchiveFormat
 parseDumpFormat(const char *format)
 {
-	ArchiveFormat archDumpFormat;
-
-	if (pg_strcasecmp(format, "c") == 0)
-		archDumpFormat = archCustom;
-	else if (pg_strcasecmp(format, "custom") == 0)
-		archDumpFormat = archCustom;
-	else if (pg_strcasecmp(format, "d") == 0)
-		archDumpFormat = archDirectory;
-	else if (pg_strcasecmp(format, "directory") == 0)
-		archDumpFormat = archDirectory;
-	else if (pg_strcasecmp(format, "p") == 0)
-		archDumpFormat = archNull;
-	else if (pg_strcasecmp(format, "plain") == 0)
-		archDumpFormat = archNull;
-	else if (pg_strcasecmp(format, "t") == 0)
-		archDumpFormat = archTar;
-	else if (pg_strcasecmp(format, "tar") == 0)
-		archDumpFormat = archTar;
-	else
-		pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
-				 format);
+	if (pg_strcasecmp(format, "c") == 0 ||
+		pg_strcasecmp(format, "custom") == 0)
+		return archCustom;
+
+	if (pg_strcasecmp(format, "d") == 0 ||
+		pg_strcasecmp(format, "directory") == 0)
+		return archDirectory;
+
+	if (pg_strcasecmp(format, "p") == 0 ||
+		pg_strcasecmp(format, "plain") == 0)
+		return archNull;
+
+	if (pg_strcasecmp(format, "t") == 0 ||
+		pg_strcasecmp(format, "tar") == 0)
+		return archTar;
 
-	return archDumpFormat;
+	pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
+			 format);
 }
 
 /*
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index dd1179ef927..974dbc5ec2c 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1938,7 +1938,7 @@ describeOneTableDetails(const char *schemaname,
 	 */
 	if (tableinfo.relkind == RELKIND_PROPGRAPH)
 	{
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt mypopt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		printfPQExpBuffer(&buf, "/* %s */\n", _("Get property graph information"));
@@ -1993,12 +1993,12 @@ describeOneTableDetails(const char *schemaname,
 			}
 		}
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		mypopt.footers = footers;
+		mypopt.topt.default_footer = false;
+		mypopt.title = title.data;
+		mypopt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &mypopt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
-- 
2.50.1 (Apple Git-155)



^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-23 05:19  David Rowley <[email protected]>
  parent: Chao Li <[email protected]>
  2 siblings, 1 reply; 30+ messages in thread

From: David Rowley @ 2026-04-23 05:19 UTC (permalink / raw)
  To: Chao Li <[email protected]>; +Cc: Álvaro Herrera <[email protected]>; Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>

On Wed, 22 Apr 2026 at 17:14, Chao Li <[email protected]> wrote:
> The attached new v1 patch fixes the v19-only shadow warnings. There are not many. I strictly limited it to warnings newly introduced in v19, without touching any pre-existing ones, even where an old occurrence is very close to a new one.

Thank you. I pushed those after some adjustments.

While doing that, I did think more on if we should do more of this for
v20. I keep thinking back to the times when I've had to write 6
different versions of a patch to back patch to 6 different branches.
It's rarely that bad, but it sure does make you swear when the 6th
"git am" fails, especially when you find out that it was for a very
trivial thing, such as a spelling mistake fix. You really have to
fight off the temptation of complacency after the first 3 or so failed
git ams.

A worse category of problems that this particular set of patches could
cause is no conflict when we want one. I personally always write bug
fixes for master and back-patch them, but if anyone were to work
forward to newer versions, then imagine someone adding some code to a
function that does something with a local variable that's shadowed
globally. If they forward patch that to a version where the local
variable has been renamed, everything compiles and might appear to
work, but it's now the global that's being changed when the new code
was meant to change the local. Maybe no committers work that way, but
if they do, it's a real risk.

IMO, without any references to recent bugs that have been fixed due to
shadowing, then I can't see beyond the fact that this might be more
likely to cause bugs than to prevent them. As I recall, we were about
borderline on doing -Wshadow=compatible-local.  At least for
non-compatible variables, I'd expect you'd get a warning or error
during compilation. For the record, I got motivated for Justin's work
on the compatible-local due to af7d270dd. I removed a shadowed
variable which was incorrect. In my view, Justin Pryzby's proposal to
do something about this was well timed. I'm not seeing the same thing
happen here. Maybe I missed it?

David





^ permalink  raw  reply  [nested|flat] 30+ messages in thread

* Re: Cleanup shadows variable warnings, round 1
@ 2026-04-23 06:34  Chao Li <[email protected]>
  parent: David Rowley <[email protected]>
  0 siblings, 0 replies; 30+ messages in thread

From: Chao Li @ 2026-04-23 06:34 UTC (permalink / raw)
  To: David Rowley <[email protected]>; +Cc: Álvaro Herrera <[email protected]>; Postgres hackers <[email protected]>; Peter Eisentraut <[email protected]>; Peter Smith <[email protected]>



> On Apr 23, 2026, at 13:19, David Rowley <[email protected]> wrote:
> 
> On Wed, 22 Apr 2026 at 17:14, Chao Li <[email protected]> wrote:
>> The attached new v1 patch fixes the v19-only shadow warnings. There are not many. I strictly limited it to warnings newly introduced in v19, without touching any pre-existing ones, even where an old occurrence is very close to a new one.
> 
> Thank you. I pushed those after some adjustments.
> 
> While doing that, I did think more on if we should do more of this for
> v20. I keep thinking back to the times when I've had to write 6
> different versions of a patch to back patch to 6 different branches.
> It's rarely that bad, but it sure does make you swear when the 6th
> "git am" fails, especially when you find out that it was for a very
> trivial thing, such as a spelling mistake fix. You really have to
> fight off the temptation of complacency after the first 3 or so failed
> git ams.
> 
> A worse category of problems that this particular set of patches could
> cause is no conflict when we want one. I personally always write bug
> fixes for master and back-patch them, but if anyone were to work
> forward to newer versions, then imagine someone adding some code to a
> function that does something with a local variable that's shadowed
> globally. If they forward patch that to a version where the local
> variable has been renamed, everything compiles and might appear to
> work, but it's now the global that's being changed when the new code
> was meant to change the local. Maybe no committers work that way, but
> if they do, it's a real risk.
> 
> IMO, without any references to recent bugs that have been fixed due to
> shadowing, then I can't see beyond the fact that this might be more
> likely to cause bugs than to prevent them. As I recall, we were about
> borderline on doing -Wshadow=compatible-local.  At least for
> non-compatible variables, I'd expect you'd get a warning or error
> during compilation. For the record, I got motivated for Justin's work
> on the compatible-local due to af7d270dd. I removed a shadowed
> variable which was incorrect. In my view, Justin Pryzby's proposal to
> do something about this was well timed. I'm not seeing the same thing
> happen here. Maybe I missed it?
> 
> David

Hi David,

Thank you very much for accepting this v19-only patch.

I helped prepare back-patch diff files for [1] today, from v10 to v18. It was only a tiny change, but I still ended up with 3 diff files across 9 branches, which was quite painful. I can understand that, as a committer, you probably run into that kind of pain regularly, and would prefer to avoid adding more of it.

I’ll hold off on the rest of this cleanup unless there is a concrete reason to revisit it in the future.

[1] https://postgr.es/[email protected]

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 30+ messages in thread


end of thread, other threads:[~2026-04-23 06:34 UTC | newest]

Thread overview: 30+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-11-28 08:16 Cleanup shadows variable warnings, round 1 Chao Li <[email protected]>
2025-11-28 09:11 ` Heikki Linnakangas <[email protected]>
2025-12-04 00:56   ` Michael Paquier <[email protected]>
2025-11-28 13:39 ` Chao Li <[email protected]>
2025-11-29 15:29 ` Peter Eisentraut <[email protected]>
2025-12-03 02:28   ` Chao Li <[email protected]>
2025-12-03 06:42     ` Peter Smith <[email protected]>
2025-12-03 06:52       ` Chao Li <[email protected]>
2025-12-03 14:36         ` Álvaro Herrera <[email protected]>
2025-12-03 21:00           ` Peter Smith <[email protected]>
2025-12-03 23:04             ` Chao Li <[email protected]>
2025-12-03 23:24           ` Chao Li <[email protected]>
2025-12-04 11:21             ` Álvaro Herrera <[email protected]>
2025-12-04 13:04               ` Bilal Yavuz <[email protected]>
2025-12-04 01:08       ` Peter Smith <[email protected]>
2025-12-04 09:10         ` Chao Li <[email protected]>
2026-03-03 09:04           ` Chao Li <[email protected]>
2025-12-03 10:56     ` Chao Li <[email protected]>
2025-12-03 15:17     ` Andres Freund <[email protected]>
2026-03-03 11:55 ` Chao Li <[email protected]>
2026-03-04 06:17 ` Chao Li <[email protected]>
2026-04-21 07:01   ` Chao Li <[email protected]>
2026-04-21 11:02     ` David Rowley <[email protected]>
2026-04-21 13:51       ` Álvaro Herrera <[email protected]>
2026-04-22 05:14         ` Chao Li <[email protected]>
2026-04-22 06:32           ` Peter Smith <[email protected]>
2026-04-22 07:24             ` Chao Li <[email protected]>
2026-04-22 06:34           ` Yuchen Li <[email protected]>
2026-04-23 05:19           ` David Rowley <[email protected]>
2026-04-23 06:34             ` Chao Li <[email protected]>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox