public inbox for [email protected]  
help / color / mirror / Atom feed
From: Chao Li <[email protected]>
To: Postgres hackers <[email protected]>
Cc: Peter Eisentraut <[email protected]>
Cc: Peter Smith <[email protected]>
Subject: Re: Cleanup shadows variable warnings, round 1
Date: Tue, 3 Mar 2026 17:04:47 +0800
Message-ID: <[email protected]> (raw)
In-Reply-To: <CAEoWx2mrQt1ymaCFkrO2bKe01sdRBSxOWBCEPxzJU2k4TpNttg@mail.gmail.com>
References: <CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com>
	<[email protected]>
	<CAEoWx2kjuQTQg=ZO76R7yKSj27zEHqehhL15UaK2D=vAw2JgYw@mail.gmail.com>
	<CAHut+PvrcSUabnsuH+77+yEwvjiLHy0XJiLuTtVHWed_MHdwMw@mail.gmail.com>
	<CAHut+PveN-xpSAPeFunXr1sYQEPL729k_NAFiEoCBA=XdR82SA@mail.gmail.com>
	<CAEoWx2mrQt1ymaCFkrO2bKe01sdRBSxOWBCEPxzJU2k4TpNttg@mail.gmail.com>



> 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)



view thread (30+ messages)  latest in thread

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected], [email protected]
  Subject: Re: Cleanup shadows variable warnings, round 1
  In-Reply-To: <[email protected]>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

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