public inbox for [email protected]
help / color / mirror / Atom feedFrom: Chao Li <[email protected]>
To: Álvaro Herrera <[email protected]>
Cc: Peter Smith <[email protected]>
Cc: Peter Eisentraut <[email protected]>
Cc: Postgres hackers <[email protected]>
Subject: Re: Cleanup shadows variable warnings, round 1
Date: Thu, 4 Dec 2025 07:24:36 +0800
Message-ID: <CAEoWx2mgTMAvXDi0AZVMeKys0owGa5tdQUJ0gonAjsdBOYMNkg@mail.gmail.com> (raw)
In-Reply-To: <[email protected]>
References: <[email protected]>
<[email protected]>
On Wed, Dec 3, 2025 at 10:36 PM Álvaro Herrera <[email protected]> wrote:
> On 2025-Dec-03, Chao Li wrote:
>
> > Unfortunately that doesn’t work for my compiler (clang on MacOS),
> > that’s why I renamed “I" to “u”.
>
> I think you're missing his point. He's suggesting to change not only
> this variable, but also the other uses of "i" in this function.
>
> I'd also change "unsigned" to "unsigned int", just because I dislike
> using unadorned "unsigned" as a type name (I know it's a legal type
> name.) This could be left alone, I guess -- not important.
>
> --
> Álvaro Herrera PostgreSQL Developer —
> https://www.EnterpriseDB.com/
I misunderstood Peter's message yesterday. I have addressed both comments
(changing all "for" and changing "unsigned" to "unsigned int") in v4.
On Wed, Dec 3, 2025 at 11:17 PM Andres Freund <[email protected]> wrote:
>
> On 2025-12-03 10:28:36 +0800, Chao Li wrote:
> > I know -Wshadow=compatible-local is not supported by all compilers, some
> > compilers may fallback to -Wshadow and some may just ignore it. This
> patch
> > set has cleaned up all shadow-variable warnings, once the cleanup is
> done,
> > in theory, we should be able to enable -Wshadow.
> >
> > 0001 - simple cases of local variable shadowing local variable by
> changing
> > inner variable to for loop variable (also need to rename the for loop
> var)
> > 0002 - simple cases of local variable shadowing local variable by
> renaming
> > inner variable
> > 0003 - simple cases of local variable shadowing local variable by
> renaming
> > outer variable. In this commit, outer local variables are used much less
> > than inner variables, thus renaming outer is simpler than renaming inner.
> > 0004 - still local shadows local, but caused by a macro definition, only
> > in inval.c
> > 0005 - cases of global wal_level and wal_segment_size shadow local ones,
> > fixed by renaming local variables
> > 0006 - in xlogrecovery.c, some static file-scope variables shadow local
> > variables, fixed by renaming local variables
> > 0007 - cases of global progname shadows local, fixed by renaming local to
> > myprogname
> > 0008 - in file_ops.c, some static file-scope variables shadow local,
> fixed
> > by renaming local variables
> > 0009 - simple cases of local variables are shadowed by global, fixed by
> > renaming local variables
> > 0010 - a few more cases of static file-scope variables shadow local
> > variables, fixed by renaming local variables
> > 0011 - cases of global conn shadows local variables, fixed by renaming
> > local conn to myconn
> > 0012 - fixed shadowing in ecpg.header
> > 0013 - fixed shadowing in all time-related modules. Heikki had a concern
> > where there is a global named “days”, so there could be some discussions
> > for this commit. For now, I just renamed local variables to avoid
> shadowing.
>
> This seems like a *lot* of noise / backpatching pain for relatively little
> gain.
>
I agree the patch set is large, which is why I split it into smaller
commits, each independent and self-contained.
The motivation is that CF’s CI currently fails on shadow-variable warnings.
If you touch a file like a.c, and that file already has a legacy shadowing
issue, CI will still fail your patch even if your changes are correct. Then
you’re forced to fix unrelated shadow-variable problems just to get a clean
CI run. I’ve run into this myself, and it’s disruptive for both patch
authors and reviewers.
By cleaning up all existing shadow-variable warnings now, they won’t
interfere with future patches, and it also allows us to enable -Wshadow by
default so new shadowing issues won’t be introduced.
On Wed, Dec 3, 2025 at 11:17 PM Andres Freund <[email protected]> wrote:
>
> > /*
> > - * Find a string representation for wal_level
> > + * Find a string representation for wallevel
> > */
> > static const char *
> > -get_wal_level_string(int wal_level)
> > +get_wal_level_string(int wallevel)
> > {
> > const struct config_enum_entry *entry;
> > - const char *wal_level_str = "?";
> > + const char *wallevel_str = "?";
>
> This sounds like it's talking about walls not, the WAL.
>
>
Fixed in v4.
V4 addressed all comments received so far, and fixed a mistake that caused
CI failure.
Best regards,
Chao Li (Evan)
---------------------
HighGo Software Co., Ltd.
https://www.highgo.com/
Attachments:
[application/octet-stream] v4-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch (4.1K, 3-v4-0001-cleanup-rename-loop-variables-to-avoid-local-shad.patch)
download | inline diff:
From 8ac41ad94b8feb57eed17970aa4010049a4f7d67 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:22:47 +0800
Subject: [PATCH v4 01/13] cleanup: rename loop variables to avoid local
shadowing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
This commit adjusts several code locations where a local variable was
shadowed by another in the same scope. The changes update loop-variable
names in basebackup_incremental.c and parse_target.c so that each
variable is uniquely scoped within its block.
Author: Chao Li <[email protected]>
Reviewed-by: Peter Smith <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/backup/basebackup_incremental.c | 10 ++++------
src/backend/parser/parse_target.c | 10 ++++------
2 files changed, 8 insertions(+), 12 deletions(-)
diff --git a/src/backend/backup/basebackup_incremental.c b/src/backend/backup/basebackup_incremental.c
index 852ab577045..844d7319c82 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -270,7 +270,6 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
ListCell *lc;
TimeLineHistoryEntry **tlep;
int num_wal_ranges;
- int i;
bool found_backup_start_tli = false;
TimeLineID earliest_wal_range_tli = 0;
XLogRecPtr earliest_wal_range_start_lsn = InvalidXLogRecPtr;
@@ -312,7 +311,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
*/
expectedTLEs = readTimeLineHistory(backup_state->starttli);
tlep = palloc0(num_wal_ranges * sizeof(TimeLineHistoryEntry *));
- for (i = 0; i < num_wal_ranges; ++i)
+ for (int i = 0; i < num_wal_ranges; ++i)
{
backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
bool saw_earliest_wal_range_tli = false;
@@ -400,7 +399,7 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
* anything here. However, if there's a problem staring us right in the
* face, it's best to report it, so we do.
*/
- for (i = 0; i < num_wal_ranges; ++i)
+ for (int i = 0; i < num_wal_ranges; ++i)
{
backup_wal_range *range = list_nth(ib->manifest_wal_ranges, i);
@@ -595,15 +594,14 @@ PrepareForIncrementalBackup(IncrementalBackupInfo *ib,
while (1)
{
- unsigned nblocks;
- unsigned i;
+ unsigned int nblocks;
nblocks = BlockRefTableReaderGetBlocks(reader, blocks,
BLOCKS_PER_READ);
if (nblocks == 0)
break;
- for (i = 0; i < nblocks; ++i)
+ for (unsigned int i = 0; i < nblocks; ++i)
BlockRefTableMarkBlockModified(ib->brtab, &rlocator,
forknum, blocks[i]);
}
diff --git a/src/backend/parser/parse_target.c b/src/backend/parser/parse_target.c
index 905c975d83b..046f96d4132 100644
--- a/src/backend/parser/parse_target.c
+++ b/src/backend/parser/parse_target.c
@@ -1609,10 +1609,9 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
* subselect must have that outer level as parent.
*/
ParseState mypstate = {0};
- Index levelsup;
/* this loop must work, since GetRTEByRangeTablePosn did */
- for (levelsup = 0; levelsup < netlevelsup; levelsup++)
+ for (Index level = 0; level < netlevelsup; level++)
pstate = pstate->parentParseState;
mypstate.parentParseState = pstate;
mypstate.p_rtable = rte->subquery->rtable;
@@ -1667,12 +1666,11 @@ expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
* could be an outer CTE (compare SUBQUERY case above).
*/
ParseState mypstate = {0};
- Index levelsup;
/* this loop must work, since GetCTEForRTE did */
- for (levelsup = 0;
- levelsup < rte->ctelevelsup + netlevelsup;
- levelsup++)
+ for (Index level = 0;
+ level < rte->ctelevelsup + netlevelsup;
+ level++)
pstate = pstate->parentParseState;
mypstate.parentParseState = pstate;
mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch (6.1K, 4-v4-0004-cleanup-fix-macro-induced-variable-shadowing-in-i.patch)
download | inline diff:
From 714f5178e4af179cf7e1edb4aea5771cb7d4bab2 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 12:08:03 +0800
Subject: [PATCH v4 04/13] cleanup: fix macro-induced variable shadowing in
inval.c
This commit resolves a shadowing issue in inval.c where variables defined
inside the ProcessMessageSubGroup and ProcessMessageSubGroupMulti macros
conflicted with an existing local name. The fix renames the macro-scoped
variable so it no longer shadows the local variable at the call site.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/utils/cache/inval.c | 44 ++++++++++++++++-----------------
1 file changed, 22 insertions(+), 22 deletions(-)
diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 06f736cab45..30bf79fb1c1 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -387,7 +387,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
int _endmsg = (group)->nextmsg[subgroup]; \
for (; _msgindex < _endmsg; _msgindex++) \
{ \
- SharedInvalidationMessage *msg = \
+ SharedInvalidationMessage *_msg = \
&InvalMessageArrays[subgroup].msgs[_msgindex]; \
codeFragment; \
} \
@@ -403,7 +403,7 @@ AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest,
do { \
int n = NumMessagesInSubGroup(group, subgroup); \
if (n > 0) { \
- SharedInvalidationMessage *msgs = \
+ SharedInvalidationMessage *_msgs = \
&InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
codeFragment; \
} \
@@ -479,9 +479,9 @@ AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group,
* don't need to add individual ones when it is present.
*/
ProcessMessageSubGroup(group, RelCacheMsgs,
- if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
- (msg->rc.relId == relId ||
- msg->rc.relId == InvalidOid))
+ if (_msg->rc.id == SHAREDINVALRELCACHE_ID &&
+ (_msg->rc.relId == relId ||
+ _msg->rc.relId == InvalidOid))
return);
/* OK, add the item */
@@ -509,9 +509,9 @@ AddRelsyncInvalidationMessage(InvalidationMsgsGroup *group,
/* Don't add a duplicate item. */
ProcessMessageSubGroup(group, RelCacheMsgs,
- if (msg->rc.id == SHAREDINVALRELSYNC_ID &&
- (msg->rc.relId == relId ||
- msg->rc.relId == InvalidOid))
+ if (_msg->rc.id == SHAREDINVALRELSYNC_ID &&
+ (_msg->rc.relId == relId ||
+ _msg->rc.relId == InvalidOid))
return);
/* OK, add the item */
@@ -538,8 +538,8 @@ AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group,
/* Don't add a duplicate item */
/* We assume dbId need not be checked because it will never change */
ProcessMessageSubGroup(group, RelCacheMsgs,
- if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
- msg->sn.relId == relId)
+ if (_msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
+ _msg->sn.relId == relId)
return);
/* OK, add the item */
@@ -574,8 +574,8 @@ static void
ProcessInvalidationMessages(InvalidationMsgsGroup *group,
void (*func) (SharedInvalidationMessage *msg))
{
- ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
- ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
+ ProcessMessageSubGroup(group, CatCacheMsgs, func(_msg));
+ ProcessMessageSubGroup(group, RelCacheMsgs, func(_msg));
}
/*
@@ -586,8 +586,8 @@ static void
ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group,
void (*func) (const SharedInvalidationMessage *msgs, int n))
{
- ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
- ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
+ ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(_msgs, n));
+ ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(_msgs, n));
}
/* ----------------------------------------------------------------
@@ -1053,25 +1053,25 @@ xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
CatCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
CatCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
ProcessMessageSubGroupMulti(&transInvalInfo->PriorCmdInvalidMsgs,
RelCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
ProcessMessageSubGroupMulti(&transInvalInfo->ii.CurrentCmdInvalidMsgs,
RelCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
Assert(nmsgs == nummsgs);
@@ -1109,13 +1109,13 @@ inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs,
ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
CatCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
ProcessMessageSubGroupMulti(&inplaceInvalInfo->CurrentCmdInvalidMsgs,
RelCacheMsgs,
(memcpy(msgarray + nmsgs,
- msgs,
+ _msgs,
n * sizeof(SharedInvalidationMessage)),
nmsgs += n));
Assert(nmsgs == nummsgs);
@@ -1955,10 +1955,10 @@ LogLogicalInvalidations(void)
XLogBeginInsert();
XLogRegisterData(&xlrec, MinSizeOfXactInvals);
ProcessMessageSubGroupMulti(group, CatCacheMsgs,
- XLogRegisterData(msgs,
+ XLogRegisterData(_msgs,
n * sizeof(SharedInvalidationMessage)));
ProcessMessageSubGroupMulti(group, RelCacheMsgs,
- XLogRegisterData(msgs,
+ XLogRegisterData(_msgs,
n * sizeof(SharedInvalidationMessage)));
XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
}
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch (6.4K, 5-v4-0003-cleanup-rename-outer-variables-to-avoid-shadowing.patch)
download | inline diff:
From 511c222fc7b2ef73bc58eb403f03fb386d44f56d Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 11:51:01 +0800
Subject: [PATCH v4 03/13] cleanup: rename outer variables to avoid shadowing
inner locals
This commit resolves several cases where an outer-scope variable shared
a name with a more frequently used inner variable. The fixes rename the
outer variables so each identifier remains distinct within its scope.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/catalog/objectaddress.c | 10 +++++-----
src/backend/catalog/pg_constraint.c | 4 ++--
src/backend/optimizer/path/equivclass.c | 6 +++---
src/backend/partitioning/partdesc.c | 6 +++---
src/backend/storage/aio/read_stream.c | 6 +++---
src/bin/pg_basebackup/pg_receivewal.c | 4 ++--
6 files changed, 18 insertions(+), 18 deletions(-)
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index c75b7131ed7..296de7647bc 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2119,7 +2119,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
ObjectAddress addr;
TupleDesc tupdesc;
Datum values[3];
- bool nulls[3];
+ bool isnulls[3];
HeapTuple htup;
Relation relation;
@@ -2374,11 +2374,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
values[0] = ObjectIdGetDatum(addr.classId);
values[1] = ObjectIdGetDatum(addr.objectId);
values[2] = Int32GetDatum(addr.objectSubId);
- nulls[0] = false;
- nulls[1] = false;
- nulls[2] = false;
+ isnulls[0] = false;
+ isnulls[1] = false;
+ isnulls[2] = false;
- htup = heap_form_tuple(tupdesc, values, nulls);
+ htup = heap_form_tuple(tupdesc, values, isnulls);
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
}
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 9944e4bd2d1..b86f93aeb4f 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -814,7 +814,7 @@ AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
* 'include_noinh' determines whether to include NO INHERIT constraints or not.
*/
List *
-RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
+RelationGetNotNullConstraints(Oid relid, bool want_cooked, bool include_noinh)
{
List *notnulls = NIL;
Relation constrRel;
@@ -842,7 +842,7 @@ RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
colnum = extractNotNullColumn(htup);
- if (cooked)
+ if (want_cooked)
{
CookedConstraint *cooked;
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 441f12f6c50..d350aa8a3b0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -739,7 +739,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
Oid opcintype,
Oid collation,
Index sortref,
- Relids rel,
+ Relids relids,
bool create_it)
{
JoinDomain *jdomain;
@@ -782,14 +782,14 @@ get_eclass_for_sort_expr(PlannerInfo *root,
if (!equal(opfamilies, cur_ec->ec_opfamilies))
continue;
- setup_eclass_member_iterator(&it, cur_ec, rel);
+ setup_eclass_member_iterator(&it, cur_ec, relids);
while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
{
/*
* Ignore child members unless they match the request.
*/
if (cur_em->em_is_child &&
- !bms_equal(cur_em->em_relids, rel))
+ !bms_equal(cur_em->em_relids, relids))
continue;
/*
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 328b4d450e4..6fd46cf2c91 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -146,7 +146,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
int i,
nparts;
bool retried = false;
- PartitionKey key = RelationGetPartitionKey(rel);
+ PartitionKey partkey = RelationGetPartitionKey(rel);
MemoryContext new_pdcxt;
MemoryContext oldcxt;
int *mapping;
@@ -308,7 +308,7 @@ retry:
* This could fail, but we haven't done any damage if so.
*/
if (nparts > 0)
- boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
+ boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
/*
* Now build the actual relcache partition descriptor, copying all the
@@ -329,7 +329,7 @@ retry:
if (nparts > 0)
{
oldcxt = MemoryContextSwitchTo(new_pdcxt);
- partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
+ partdesc->boundinfo = partition_bounds_copy(boundinfo, partkey);
/* Initialize caching fields for speeding up ExecFindPartition */
partdesc->last_found_datum_index = -1;
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 031fde9f4cb..edc2279ead4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -788,7 +788,7 @@ read_stream_begin_smgr_relation(int flags,
* the stream early at any time by calling read_stream_end().
*/
Buffer
-read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
+read_stream_next_buffer(ReadStream *stream, void **pper_buffer_data)
{
Buffer buffer;
int16 oldest_buffer_index;
@@ -903,8 +903,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
Assert(oldest_buffer_index >= 0 &&
oldest_buffer_index < stream->queue_size);
buffer = stream->buffers[oldest_buffer_index];
- if (per_buffer_data)
- *per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+ if (pper_buffer_data)
+ *pper_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
Assert(BufferIsValid(buffer));
diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 46e553dce4b..785bf7b11dc 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -265,7 +265,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
* If there are no WAL files in the directory, returns InvalidXLogRecPtr.
*/
static XLogRecPtr
-FindStreamingStart(uint32 *tli)
+FindStreamingStart(uint32 *ptli)
{
DIR *dir;
struct dirent *dirent;
@@ -486,7 +486,7 @@ FindStreamingStart(uint32 *tli)
XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
- *tli = high_tli;
+ *ptli = high_tli;
return high_ptr;
}
else
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch (36.0K, 6-v4-0002-cleanup-rename-inner-variables-to-avoid-shadowing.patch)
download | inline diff:
From 9fe96f2babd0268c8aea6da7b6882bd113cec7c9 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v4 02/13] cleanup: rename inner variables to avoid shadowing
by outer locals
This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/access/brin/brin.c | 8 ++--
src/backend/access/gist/gistbuild.c | 10 ++---
src/backend/commands/extension.c | 8 ++--
src/backend/commands/schemacmds.c | 4 +-
src/backend/commands/statscmds.c | 6 +--
src/backend/commands/tablecmds.c | 28 +++++++-------
src/backend/commands/trigger.c | 14 +++----
src/backend/commands/wait.c | 12 +++---
src/backend/executor/nodeAgg.c | 16 ++++----
src/backend/executor/nodeValuesscan.c | 4 +-
src/backend/optimizer/plan/createplan.c | 44 +++++++++++-----------
src/backend/statistics/dependencies.c | 26 ++++++-------
src/backend/statistics/extended_stats.c | 6 +--
src/backend/storage/buffer/bufmgr.c | 6 +--
src/backend/utils/adt/jsonpath_exec.c | 30 +++++++--------
src/backend/utils/adt/pg_upgrade_support.c | 4 +-
src/backend/utils/adt/varlena.c | 20 +++++-----
src/backend/utils/mmgr/freepage.c | 6 +--
src/bin/pgbench/pgbench.c | 6 +--
src/bin/psql/describe.c | 18 ++++-----
src/bin/psql/prompt.c | 12 +++---
src/fe_utils/print.c | 10 ++---
src/interfaces/libpq/fe-connect.c | 8 ++--
23 files changed, 154 insertions(+), 152 deletions(-)
diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index cb3331921cb..0aee0c013ff 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -694,15 +694,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
*/
if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
{
- FmgrInfo *tmp;
+ FmgrInfo *tmpfi;
/* First time we see this attribute, so no key/null keys. */
Assert(nkeys[keyattno - 1] == 0);
Assert(nnullkeys[keyattno - 1] == 0);
- tmp = index_getprocinfo(idxRel, keyattno,
- BRIN_PROCNUM_CONSISTENT);
- fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+ tmpfi = index_getprocinfo(idxRel, keyattno,
+ BRIN_PROCNUM_CONSISTENT);
+ fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
CurrentMemoryContext);
}
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index be0fd5b753d..7d975652ad3 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1158,7 +1158,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
i = 0;
foreach(lc, splitinfo)
{
- GISTPageSplitInfo *splitinfo = lfirst(lc);
+ GISTPageSplitInfo *si = lfirst(lc);
/*
* Remember the parent of each new child page in our parent map.
@@ -1169,7 +1169,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
*/
if (level > 0)
gistMemorizeParent(buildstate,
- BufferGetBlockNumber(splitinfo->buf),
+ BufferGetBlockNumber(si->buf),
BufferGetBlockNumber(parentBuffer));
/*
@@ -1179,14 +1179,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
* harm).
*/
if (level > 1)
- gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+ gistMemorizeAllDownlinks(buildstate, si->buf);
/*
* Since there's no concurrent access, we can release the lower
* level buffers immediately. This includes the original page.
*/
- UnlockReleaseBuffer(splitinfo->buf);
- downlinks[i++] = splitinfo->downlink;
+ UnlockReleaseBuffer(si->buf);
+ downlinks[i++] = si->downlink;
}
/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index ebc204c4462..0ef657bf919 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1274,8 +1274,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
Datum old = t_sql;
char *reqextname = (char *) lfirst(lc);
Oid reqschema = lfirst_oid(lc2);
- char *schemaName = get_namespace_name(reqschema);
- const char *qSchemaName = quote_identifier(schemaName);
+ char *reqSchemaName = get_namespace_name(reqschema);
+ const char *qReqSchemaName = quote_identifier(reqSchemaName);
char *repltoken;
repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1283,8 +1283,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
C_COLLATION_OID,
t_sql,
CStringGetTextDatum(repltoken),
- CStringGetTextDatum(qSchemaName));
- if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+ CStringGetTextDatum(qReqSchemaName));
+ if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 3cc1472103a..bc8e8fb1eaa 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -205,14 +205,14 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
*/
foreach(parsetree_item, parsetree_list)
{
- Node *stmt = (Node *) lfirst(parsetree_item);
+ Node *substmt = (Node *) lfirst(parsetree_item);
PlannedStmt *wrapper;
/* need to make a wrapper PlannedStmt */
wrapper = makeNode(PlannedStmt);
wrapper->commandType = CMD_UTILITY;
wrapper->canSetTag = false;
- wrapper->utilityStmt = stmt;
+ wrapper->utilityStmt = substmt;
wrapper->stmt_location = stmt_location;
wrapper->stmt_len = stmt_len;
wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 77b1a6e2dc5..dc3500b8fa5 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
Node *expr = selem->expr;
Oid atttype;
TypeCacheEntry *type;
- Bitmapset *attnums = NULL;
+ Bitmapset *attnumsbm = NULL;
int k;
Assert(expr != NULL);
- pull_varattnos(expr, 1, &attnums);
+ pull_varattnos(expr, 1, &attnumsbm);
k = -1;
- while ((k = bms_next_member(attnums, k)) >= 0)
+ while ((k = bms_next_member(attnumsbm, k)) >= 0)
{
AttrNumber attnum = k + FirstLowInvalidHeapAttributeNumber;
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 07e5b95782e..5173038cdf0 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15708,14 +15708,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
foreach(lcmd, stmt->cmds)
{
- AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+ AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
- if (cmd->subtype == AT_AddIndex)
+ if (subcmd->subtype == AT_AddIndex)
{
IndexStmt *indstmt;
Oid indoid;
- indstmt = castNode(IndexStmt, cmd->def);
+ indstmt = castNode(IndexStmt, subcmd->def);
indoid = get_constraint_index(oldId);
if (!rewrite)
@@ -15725,9 +15725,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
RelationRelationId, 0);
indstmt->reset_default_tblspc = true;
- cmd->subtype = AT_ReAddIndex;
+ subcmd->subtype = AT_ReAddIndex;
tab->subcmds[AT_PASS_OLD_INDEX] =
- lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+ lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
/* recreate any comment on the constraint */
RebuildConstraintComment(tab,
@@ -15737,9 +15737,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
NIL,
indstmt->idxname);
}
- else if (cmd->subtype == AT_AddConstraint)
+ else if (subcmd->subtype == AT_AddConstraint)
{
- Constraint *con = castNode(Constraint, cmd->def);
+ Constraint *con = castNode(Constraint, subcmd->def);
con->old_pktable_oid = refRelId;
/* rewriting neither side of a FK */
@@ -15747,9 +15747,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
!rewrite && tab->rewrite == 0)
TryReuseForeignKey(oldId, con);
con->reset_default_tblspc = true;
- cmd->subtype = AT_ReAddConstraint;
+ subcmd->subtype = AT_ReAddConstraint;
tab->subcmds[AT_PASS_OLD_CONSTR] =
- lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+ lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
/*
* Recreate any comment on the constraint. If we have
@@ -15769,7 +15769,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
}
else
elog(ERROR, "unexpected statement subtype: %d",
- (int) cmd->subtype);
+ (int) subcmd->subtype);
}
}
else if (IsA(stm, AlterDomainStmt))
@@ -15779,12 +15779,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
if (stmt->subtype == AD_AddConstraint)
{
Constraint *con = castNode(Constraint, stmt->def);
- AlterTableCmd *cmd = makeNode(AlterTableCmd);
+ AlterTableCmd *subcmd = makeNode(AlterTableCmd);
- cmd->subtype = AT_ReAddDomainConstraint;
- cmd->def = (Node *) stmt;
+ subcmd->subtype = AT_ReAddDomainConstraint;
+ subcmd->def = (Node *) stmt;
tab->subcmds[AT_PASS_OLD_CONSTR] =
- lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+ lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
/* recreate any comment on the constraint */
RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 579ac8d76ae..45d41adf570 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
{
CreateTrigStmt *childStmt;
Relation childTbl;
- Node *qual;
+ Node *partqual;
childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
childStmt->whenClause = NULL;
/* If there is a WHEN clause, create a modified copy of it */
- qual = copyObject(whenClause);
- qual = (Node *)
- map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+ partqual = copyObject(whenClause);
+ partqual = (Node *)
+ map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
childTbl, rel);
- qual = (Node *)
- map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+ partqual = (Node *)
+ map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
childTbl, rel);
CreateTriggerFiringOn(childStmt, queryString,
partdesc->oids[i], refRelOid,
InvalidOid, InvalidOid,
- funcoid, trigoid, qual,
+ funcoid, trigoid, partqual,
isInternal, true, trigger_fires_when);
table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index a37bddaefb2..e93d9e19de7 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -51,7 +51,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
{
char *timeout_str;
const char *hintmsg;
- double result;
+ double timeout_val;
if (timeout_specified)
errorConflictingDefElem(defel, pstate);
@@ -59,7 +59,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
timeout_str = defGetString(defel);
- if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+ if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
{
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -72,20 +72,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
* don't fail on just-out-of-range values that would round into
* range.
*/
- result = rint(result);
+ timeout_val = rint(timeout_val);
/* Range check */
- if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+ if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
ereport(ERROR,
errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("timeout value is out of range"));
- if (result < 0)
+ if (timeout_val < 0)
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("timeout cannot be negative"));
- timeout = (int64) result;
+ timeout = (int64) timeout_val;
}
else if (strcmp(defel->defname, "no_throw") == 0)
{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 0b02fd32107..e4c539e3917 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4070,12 +4070,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
*/
for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
{
- AggStatePerPhase phase = &aggstate->phases[phaseidx];
+ AggStatePerPhase curphase = &aggstate->phases[phaseidx];
bool dohash = false;
bool dosort = false;
/* phase 0 doesn't necessarily exist */
- if (!phase->aggnode)
+ if (!curphase->aggnode)
continue;
if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4096,13 +4096,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
*/
continue;
}
- else if (phase->aggstrategy == AGG_PLAIN ||
- phase->aggstrategy == AGG_SORTED)
+ else if (curphase->aggstrategy == AGG_PLAIN ||
+ curphase->aggstrategy == AGG_SORTED)
{
dohash = false;
dosort = true;
}
- else if (phase->aggstrategy == AGG_HASHED)
+ else if (curphase->aggstrategy == AGG_HASHED)
{
dohash = true;
dosort = false;
@@ -4110,11 +4110,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
else
Assert(false);
- phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
- false);
+ curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+ false);
/* cache compiled expression for outer slot without NULL check */
- phase->evaltrans_cache[0][0] = phase->evaltrans;
+ curphase->evaltrans_cache[0][0] = curphase->evaltrans;
}
return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index 8e85a5f2e9a..0d366546966 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -141,11 +141,11 @@ ValuesNext(ValuesScanState *node)
resind = 0;
foreach(lc, exprstatelist)
{
- ExprState *estate = (ExprState *) lfirst(lc);
+ ExprState *exprstate = (ExprState *) lfirst(lc);
CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
resind);
- values[resind] = ExecEvalExpr(estate,
+ values[resind] = ExecEvalExpr(exprstate,
econtext,
&isnull[resind]);
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 8af091ba647..92e46a31898 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1236,16 +1236,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
if (best_path->subpaths == NIL)
{
/* Generate a Result plan with constant-FALSE gating qual */
- Plan *plan;
+ Plan *resplan;
- plan = (Plan *) make_one_row_result(tlist,
- (Node *) list_make1(makeBoolConst(false,
- false)),
- best_path->path.parent);
+ resplan = (Plan *) make_one_row_result(tlist,
+ (Node *) list_make1(makeBoolConst(false,
+ false)),
+ best_path->path.parent);
- copy_generic_path_info(plan, (Path *) best_path);
+ copy_generic_path_info(resplan, (Path *) best_path);
- return plan;
+ return resplan;
}
/*
@@ -2406,7 +2406,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
PlannerInfo *subroot = mminfo->subroot;
Query *subparse = subroot->parse;
- Plan *plan;
+ Plan *initplan;
/*
* Generate the plan for the subquery. We already have a Path, but we
@@ -2414,25 +2414,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
* Since we are entering a different planner context (subroot),
* recurse to create_plan not create_plan_recurse.
*/
- plan = create_plan(subroot, mminfo->path);
+ initplan = create_plan(subroot, mminfo->path);
- plan = (Plan *) make_limit(plan,
- subparse->limitOffset,
- subparse->limitCount,
- subparse->limitOption,
- 0, NULL, NULL, NULL);
+ initplan = (Plan *) make_limit(initplan,
+ subparse->limitOffset,
+ subparse->limitCount,
+ subparse->limitOption,
+ 0, NULL, NULL, NULL);
/* Must apply correct cost/width data to Limit node */
- plan->disabled_nodes = mminfo->path->disabled_nodes;
- plan->startup_cost = mminfo->path->startup_cost;
- plan->total_cost = mminfo->pathcost;
- plan->plan_rows = 1;
- plan->plan_width = mminfo->path->pathtarget->width;
- plan->parallel_aware = false;
- plan->parallel_safe = mminfo->path->parallel_safe;
+ initplan->disabled_nodes = mminfo->path->disabled_nodes;
+ initplan->startup_cost = mminfo->path->startup_cost;
+ initplan->total_cost = mminfo->pathcost;
+ initplan->plan_rows = 1;
+ initplan->plan_width = mminfo->path->pathtarget->width;
+ initplan->parallel_aware = false;
+ initplan->parallel_safe = mminfo->path->parallel_safe;
/* Convert the plan into an InitPlan in the outer query. */
- SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+ SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
}
/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index d7bf6b7e846..28e05d5adc0 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1098,17 +1098,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
if (is_opclause(clause))
{
/* If it's an opclause, check for Var = Const or Const = Var. */
- OpExpr *expr = (OpExpr *) clause;
+ OpExpr *opexpr = (OpExpr *) clause;
/* Only expressions with two arguments are candidates. */
- if (list_length(expr->args) != 2)
+ if (list_length(opexpr->args) != 2)
return false;
/* Make sure non-selected argument is a pseudoconstant. */
- if (is_pseudo_constant_clause(lsecond(expr->args)))
- clause_expr = linitial(expr->args);
- else if (is_pseudo_constant_clause(linitial(expr->args)))
- clause_expr = lsecond(expr->args);
+ if (is_pseudo_constant_clause(lsecond(opexpr->args)))
+ clause_expr = linitial(opexpr->args);
+ else if (is_pseudo_constant_clause(linitial(opexpr->args)))
+ clause_expr = lsecond(opexpr->args);
else
return false;
@@ -1124,7 +1124,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
* selectivity functions, and to be more consistent with decisions
* elsewhere in the planner.
*/
- if (get_oprrest(expr->opno) != F_EQSEL)
+ if (get_oprrest(opexpr->opno) != F_EQSEL)
return false;
/* OK to proceed with checking "var" */
@@ -1132,7 +1132,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
else if (IsA(clause, ScalarArrayOpExpr))
{
/* If it's a scalar array operator, check for Var IN Const. */
- ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+ ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) clause;
/*
* Reject ALL() variant, we only care about ANY/IN.
@@ -1140,21 +1140,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
* FIXME Maybe we should check if all the values are the same, and
* allow ALL in that case? Doesn't seem very practical, though.
*/
- if (!expr->useOr)
+ if (!opexpr->useOr)
return false;
/* Only expressions with two arguments are candidates. */
- if (list_length(expr->args) != 2)
+ if (list_length(opexpr->args) != 2)
return false;
/*
* We know it's always (Var IN Const), so we assume the var is the
* first argument, and pseudoconstant is the second one.
*/
- if (!is_pseudo_constant_clause(lsecond(expr->args)))
+ if (!is_pseudo_constant_clause(lsecond(opexpr->args)))
return false;
- clause_expr = linitial(expr->args);
+ clause_expr = linitial(opexpr->args);
/*
* If it's not an "=" operator, just ignore the clause, as it's not
@@ -1163,7 +1163,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
* selectivity. That's a bit strange, but it's what other similar
* places do.
*/
- if (get_oprrest(expr->opno) != F_EQSEL)
+ if (get_oprrest(opexpr->opno) != F_EQSEL)
return false;
/* OK to proceed with checking "var" */
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index f003d7b4a73..ae2c82475d4 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -991,7 +991,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
Size len;
SortItem *items;
Datum *values;
- bool *isnull;
+ bool *isnulls;
char *ptr;
int *typlen;
@@ -1011,7 +1011,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
values = (Datum *) ptr;
ptr += nvalues * sizeof(Datum);
- isnull = (bool *) ptr;
+ isnulls = (bool *) ptr;
ptr += nvalues * sizeof(bool);
/* make sure we consumed the whole buffer exactly */
@@ -1022,7 +1022,7 @@ build_sorted_items(StatsBuildData *data, int *nitems,
for (i = 0; i < data->numrows; i++)
{
items[nrows].values = &values[nrows * numattrs];
- items[nrows].isnull = &isnull[nrows * numattrs];
+ items[nrows].isnull = &isnulls[nrows * numattrs];
nrows++;
}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f373cead95f..887c7d4d337 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1188,7 +1188,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
*/
if (unlikely(blockNum == P_NEW))
{
- uint32 flags = EB_SKIP_EXTENSION_LOCK;
+ uint32 uflags = EB_SKIP_EXTENSION_LOCK;
/*
* Since no-one else can be looking at the page contents yet, there is
@@ -1196,9 +1196,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
* lock.
*/
if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
- flags |= EB_LOCK_FIRST;
+ uflags |= EB_LOCK_FIRST;
- return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+ return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
}
if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 8156695e97e..4b837ff0766 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
MemoryContext oldcontext;
Jsonb *vars;
bool silent;
- JsonValueList found = {0};
+ JsonValueList foundJV = {0};
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
countVariablesFromJsonb,
- jb, !silent, &found, tz);
+ jb, !silent, &foundJV, tz);
- funcctx->user_fctx = JsonValueListGetList(&found);
+ funcctx->user_fctx = JsonValueListGetList(&foundJV);
MemoryContextSwitchTo(oldcontext);
}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
* check that there are no errors at all.
*/
JsonValueList vals = {0};
- JsonPathExecResult res =
+ JsonPathExecResult execres =
executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
false, &vals);
- if (jperIsError(res))
+ if (jperIsError(execres))
return jpbUnknown;
return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
}
else
{
- JsonPathExecResult res =
+ JsonPathExecResult execres =
executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
false, NULL);
- if (jperIsError(res))
+ if (jperIsError(execres))
return jpbUnknown;
- return res == jperOk ? jpbTrue : jpbFalse;
+ return execres == jperOk ? jpbTrue : jpbFalse;
}
default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
/* Loop over right arg sequence or do single pass otherwise */
while (rarg ? (rval != NULL) : first)
{
- JsonPathBool res = exec(pred, lval, rval, param);
+ JsonPathBool boolres = exec(pred, lval, rval, param);
- if (res == jpbUnknown)
+ if (boolres == jpbUnknown)
{
if (jspStrictAbsenceOfErrors(cxt))
return jpbUnknown;
error = true;
}
- else if (res == jpbTrue)
+ else if (boolres == jpbTrue)
{
if (!jspStrictAbsenceOfErrors(cxt))
return jpbTrue;
@@ -4136,20 +4136,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
forboth(exprlc, state->passingvalexprs,
namelc, je->passing_names)
{
- ExprState *state = lfirst_node(ExprState, exprlc);
+ ExprState *exprstate = lfirst_node(ExprState, exprlc);
String *name = lfirst_node(String, namelc);
JsonPathVariable *var = palloc(sizeof(*var));
var->name = pstrdup(name->sval);
var->namelen = strlen(var->name);
- var->typid = exprType((Node *) state->expr);
- var->typmod = exprTypmod((Node *) state->expr);
+ var->typid = exprType((Node *) exprstate->expr);
+ var->typmod = exprTypmod((Node *) exprstate->expr);
/*
* Evaluate the expression and save the value to be returned by
* GetJsonPathVar().
*/
- var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+ var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
&var->isnull);
args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index a4f8b4faa90..cfaa8f8a3b7 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
for (i = 0; i < ndatums; i++)
{
- char *extName = TextDatumGetCString(textDatums[i]);
- Oid extOid = get_extension_oid(extName, false);
+ char *extNameStr = TextDatumGetCString(textDatums[i]);
+ Oid extOid = get_extension_oid(extNameStr, false);
requiredExtensions = lappend_oid(requiredExtensions, extOid);
}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 3894457ab40..84f6074f0f5 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3273,14 +3273,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
* Copy the text that is back reference of regexp. Note so and eo
* are counted in characters not bytes.
*/
- char *chunk_start;
- int chunk_len;
+ char *start;
+ int len;
Assert(so >= data_pos);
- chunk_start = start_ptr;
- chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
- chunk_len = charlen_to_bytelen(chunk_start, eo - so);
- appendBinaryStringInfo(str, chunk_start, chunk_len);
+ start = start_ptr;
+ start += charlen_to_bytelen(start, so - data_pos);
+ len = charlen_to_bytelen(start, eo - so);
+ appendBinaryStringInfo(str, start, len);
}
}
}
@@ -4899,7 +4899,7 @@ text_format(PG_FUNCTION_ARGS)
else
{
/* For less-usual datatypes, convert to text then to int */
- char *str;
+ char *s;
if (typid != prev_width_type)
{
@@ -4911,12 +4911,12 @@ text_format(PG_FUNCTION_ARGS)
prev_width_type = typid;
}
- str = OutputFunctionCall(&typoutputinfo_width, value);
+ s = OutputFunctionCall(&typoutputinfo_width, value);
/* pg_strtoint32 will complain about bad data or overflow */
- width = pg_strtoint32(str);
+ width = pg_strtoint32(s);
- pfree(str);
+ pfree(s);
}
}
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index 27d3e6e100c..9836d872aec 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
{
bool remove_next = false;
- Size result;
+ Size nprevpages;
Assert(prevkey->first_page + prevkey->npages == first_page);
prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
/* Put the span on the correct freelist and save size. */
FreePagePopSpanLeader(fpm, prevkey->first_page);
FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
- result = prevkey->npages;
+ nprevpages = prevkey->npages;
/*
* If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
if (remove_next)
FreePageBtreeRemove(fpm, np, nindex);
- return result;
+ return nprevpages;
}
/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 68774a59efd..48cb5636908 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
double lag_sum2 = 0.0;
double lag_min = 0.0;
double lag_max = 0.0;
- int64 skipped = 0;
+ int64 skips = 0;
int64 serialization_failures = 0;
int64 deadlock_failures = 0;
int64 other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
lag_max);
if (latency_limit)
- skipped = agg->skipped;
- fprintf(logfile, " " INT64_FORMAT, skipped);
+ skips = agg->skipped;
+ fprintf(logfile, " " INT64_FORMAT, skips);
if (max_tries != 1)
{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 36f24502842..472cd2b782b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
if (tableinfo.relkind == RELKIND_SEQUENCE)
{
PGresult *result = NULL;
- printQueryOpt myopt = pset.popt;
+ printQueryOpt popt = pset.popt;
char *footers[3] = {NULL, NULL, NULL};
if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
schemaname, relationname);
- myopt.footers = footers;
- myopt.topt.default_footer = false;
- myopt.title = title.data;
- myopt.translate_header = true;
+ popt.footers = footers;
+ popt.topt.default_footer = false;
+ popt.title = title.data;
+ popt.translate_header = true;
- printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+ printQuery(res, &popt, pset.queryFout, false, pset.logfile);
free(footers[0]);
free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
if (PQntuples(result) == 1)
{
- char *schemaname = PQgetvalue(result, 0, 0);
- char *relname = PQgetvalue(result, 0, 1);
+ const char *schema = PQgetvalue(result, 0, 0);
+ const char *relname = PQgetvalue(result, 0, 1);
printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
- schemaname, relname);
+ schema, relname);
printTableAddFooter(&cont, tmpbuf.data);
}
PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 59a2ceee07a..941fa894910 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -200,11 +200,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
/* pipeline status */
case 'P':
{
- PGpipelineStatus status = PQpipelineStatus(pset.db);
+ PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
- if (status == PQ_PIPELINE_ON)
+ if (pipelinestatus == PQ_PIPELINE_ON)
strlcpy(buf, "on", sizeof(buf));
- else if (status == PQ_PIPELINE_ABORTED)
+ else if (pipelinestatus == PQ_PIPELINE_ABORTED)
strlcpy(buf, "abort", sizeof(buf));
else
strlcpy(buf, "off", sizeof(buf));
@@ -372,10 +372,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
/* Compute the visible width of PROMPT1, for PROMPT2's %w */
if (prompt_string == pset.prompt1)
{
- char *p = destination;
- char *end = p + strlen(p);
+ const char *end;
bool visible = true;
+ p = (const char *) destination;
+ end = p + strlen(p);
+
last_prompt1_width = 0;
while (*p)
{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 4d97ad2ddeb..94ea4dffea3 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
if (!opt_tuples_only)
{
int more_col_wrapping;
- int curr_nl_line;
+ int curr_line;
if (opt_border == 2)
_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
col_lineptrs[i], max_nl_lines[i]);
more_col_wrapping = col_count;
- curr_nl_line = 0;
+ curr_line = 0;
if (col_count > 0)
memset(header_done, false, col_count * sizeof(bool));
while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
for (i = 0; i < cont->ncolumns; i++)
{
- struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+ struct lineptr *this_line = col_lineptrs[i] + curr_line;
unsigned int nbspace;
if (opt_border != 0 ||
(!format->wrap_right_border && i > 0))
- fputs(curr_nl_line ? format->header_nl_left : " ",
+ fputs(curr_line ? format->header_nl_left : " ",
fout);
if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
if (opt_border != 0 && col_count > 0 && i < col_count - 1)
fputs(dformat->midvrule, fout);
}
- curr_nl_line++;
+ curr_line++;
if (opt_border == 2)
fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index c3a2448dce5..24185a2602d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3999,7 +3999,7 @@ keep_going: /* We will come back to here until there is
int msgLength;
int avail;
AuthRequest areq;
- int res;
+ int status;
bool async;
/*
@@ -4198,9 +4198,9 @@ keep_going: /* We will come back to here until there is
* Note that conn->pghost must be non-NULL if we are going to
* avoid the Kerberos code doing a hostname look-up.
*/
- res = pg_fe_sendauth(areq, msgLength, conn, &async);
+ status = pg_fe_sendauth(areq, msgLength, conn, &async);
- if (async && (res == STATUS_OK))
+ if (async && (status == STATUS_OK))
{
/*
* We'll come back later once we're ready to respond.
@@ -4217,7 +4217,7 @@ keep_going: /* We will come back to here until there is
*/
conn->inStart = conn->inCursor;
- if (res != STATUS_OK)
+ if (status != STATUS_OK)
{
/*
* OAuth connections may perform two-step discovery, where
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch (3.3K, 7-v4-0005-cleanup-avoid-local-wal_level-and-wal_segment_siz.patch)
download | inline diff:
From 3e024391ab366ea890a2f28b7aba66ee5de9c06a Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 13:45:05 +0800
Subject: [PATCH v4 05/13] cleanup: avoid local wal_level and wal_segment_size
being shadowed by globals
This commit fixes cases where local variables named wal_level and
wal_segment_size were shadowed by global identifiers of the same names.
The local variables are renamed so they are no longer shadowed by the
globals.
Author: Chao Li <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/access/rmgrdesc/xlogdesc.c | 12 ++++++------
src/backend/access/transam/xlogreader.c | 4 ++--
src/bin/pg_controldata/pg_controldata.c | 4 ++--
3 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index cd6c2a2f650..bf6a120af68 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -34,17 +34,17 @@ const struct config_enum_entry wal_level_options[] = {
};
/*
- * Find a string representation for wal_level
+ * Find a string representation for wal level
*/
static const char *
-get_wal_level_string(int wal_level)
+get_wal_level_string(int level)
{
const struct config_enum_entry *entry;
const char *wal_level_str = "?";
for (entry = wal_level_options; entry->name; entry++)
{
- if (entry->val == wal_level)
+ if (entry->val == level)
{
wal_level_str = entry->name;
break;
@@ -162,10 +162,10 @@ xlog_desc(StringInfo buf, XLogReaderState *record)
}
else if (info == XLOG_CHECKPOINT_REDO)
{
- int wal_level;
+ int level;
- memcpy(&wal_level, rec, sizeof(int));
- appendStringInfo(buf, "wal_level %s", get_wal_level_string(wal_level));
+ memcpy(&level, rec, sizeof(int));
+ appendStringInfo(buf, "wal_level %s", get_wal_level_string(level));
}
}
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 9cc7488e892..0ae4e05f8f2 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -104,7 +104,7 @@ XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
* Returns NULL if the xlogreader couldn't be allocated.
*/
XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wal_seg_size, const char *waldir,
XLogReaderRoutine *routine, void *private_data)
{
XLogReaderState *state;
@@ -134,7 +134,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
}
/* Initialize segment info. */
- WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+ WALOpenSegmentInit(&state->seg, &state->segcxt, wal_seg_size,
waldir);
/* system_identifier initialized to zeroes above */
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 30ad46912e1..8cb56f12146 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -70,9 +70,9 @@ dbState(DBState state)
}
static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
{
- switch (wal_level)
+ switch (level)
{
case WAL_LEVEL_MINIMAL:
return "minimal";
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch (4.0K, 8-v4-0008-cleanup-avoid-local-variables-shadowed-by-static-.patch)
download | inline diff:
From d2e5e401831867a6a184f00c88bd569aef63a6e1 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:53 +0800
Subject: [PATCH v4 08/13] cleanup: avoid local variables shadowed by static
file-scope ones in file_ops.c
This commit fixes several cases in file_ops.c where local variables used
names that conflicted with static variables defined at file scope. The
local identifiers are renamed so they are no longer shadowed by the file-
scope variables and remain unambiguous within their respective blocks.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/bin/pg_rewind/file_ops.c | 50 ++++++++++++++++++------------------
1 file changed, 25 insertions(+), 25 deletions(-)
diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c
index 55659ce201f..3867233e8a8 100644
--- a/src/bin/pg_rewind/file_ops.c
+++ b/src/bin/pg_rewind/file_ops.c
@@ -186,41 +186,41 @@ create_target(file_entry_t *entry)
void
remove_target_file(const char *path, bool missing_ok)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
- if (unlink(dstpath) != 0)
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+ if (unlink(pathbuf) != 0)
{
if (errno == ENOENT && missing_ok)
return;
pg_fatal("could not remove file \"%s\": %m",
- dstpath);
+ pathbuf);
}
}
void
truncate_target_file(const char *path, off_t newsize)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
int fd;
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
- fd = open(dstpath, O_WRONLY, pg_file_create_mode);
+ fd = open(pathbuf, O_WRONLY, pg_file_create_mode);
if (fd < 0)
pg_fatal("could not open file \"%s\" for truncation: %m",
- dstpath);
+ pathbuf);
if (ftruncate(fd, newsize) != 0)
pg_fatal("could not truncate file \"%s\" to %u: %m",
- dstpath, (unsigned int) newsize);
+ pathbuf, (unsigned int) newsize);
close(fd);
}
@@ -228,57 +228,57 @@ truncate_target_file(const char *path, off_t newsize)
static void
create_target_dir(const char *path)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
- if (mkdir(dstpath, pg_dir_create_mode) != 0)
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+ if (mkdir(pathbuf, pg_dir_create_mode) != 0)
pg_fatal("could not create directory \"%s\": %m",
- dstpath);
+ pathbuf);
}
static void
remove_target_dir(const char *path)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
- if (rmdir(dstpath) != 0)
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+ if (rmdir(pathbuf) != 0)
pg_fatal("could not remove directory \"%s\": %m",
- dstpath);
+ pathbuf);
}
static void
create_target_symlink(const char *path, const char *link)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
- if (symlink(link, dstpath) != 0)
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+ if (symlink(link, pathbuf) != 0)
pg_fatal("could not create symbolic link at \"%s\": %m",
- dstpath);
+ pathbuf);
}
static void
remove_target_symlink(const char *path)
{
- char dstpath[MAXPGPATH];
+ char pathbuf[MAXPGPATH];
if (dry_run)
return;
- snprintf(dstpath, sizeof(dstpath), "%s/%s", datadir_target, path);
- if (unlink(dstpath) != 0)
+ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", datadir_target, path);
+ if (unlink(pathbuf) != 0)
pg_fatal("could not remove symbolic link \"%s\": %m",
- dstpath);
+ pathbuf);
}
/*
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch (5.4K, 9-v4-0010-cleanup-avoid-local-variables-shadowed-by-static-.patch)
download | inline diff:
From 66cdc67b20b2c92fc7ef851e4ba01d76d2d193fe Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:26:51 +0800
Subject: [PATCH v4 10/13] cleanup: avoid local variables shadowed by static
file-scope ones in several files
This commit fixes multiple cases where local variables used names that
conflicted with static variables defined at file scope. The affected
locals are renamed so they are no longer shadowed by the file-scope
identifiers and remain unambiguous within their respective scopes.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/executor/execExprInterp.c | 6 +++---
src/bin/pg_ctl/pg_ctl.c | 6 +++---
src/bin/pg_dump/pg_dumpall.c | 6 +++---
src/bin/pg_resetwal/pg_resetwal.c | 6 +++---
src/bin/pg_test_fsync/pg_test_fsync.c | 6 +++---
5 files changed, 15 insertions(+), 15 deletions(-)
diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 5e7bd933afc..da8a7609d86 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -471,7 +471,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
* This array has to be in the same order as enum ExprEvalOp.
*/
#if defined(EEO_USE_COMPUTED_GOTO)
- static const void *const dispatch_table[] = {
+ static const void *const _dispatch_table[] = {
&&CASE_EEOP_DONE_RETURN,
&&CASE_EEOP_DONE_NO_RETURN,
&&CASE_EEOP_INNER_FETCHSOME,
@@ -595,11 +595,11 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
&&CASE_EEOP_LAST
};
- StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
+ StaticAssertDecl(lengthof(_dispatch_table) == EEOP_LAST + 1,
"dispatch_table out of whack with ExprEvalOp");
if (unlikely(state == NULL))
- return PointerGetDatum(dispatch_table);
+ return PointerGetDatum(_dispatch_table);
#else
Assert(state != NULL);
#endif /* EEO_USE_COMPUTED_GOTO */
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 4f666d91036..d2b8d83d1ca 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -873,18 +873,18 @@ trap_sigint_during_startup(SIGNAL_ARGS)
}
static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *myargv0, const char *target, const char *versionstr)
{
int ret;
char *found_path;
found_path = pg_malloc(MAXPGPATH);
- if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+ if ((ret = find_other_exec(myargv0, target, versionstr, found_path)) < 0)
{
char full_path[MAXPGPATH];
- if (find_my_exec(argv0, full_path) < 0)
+ if (find_my_exec(myargv0, full_path) < 0)
strlcpy(full_path, progname, sizeof(full_path));
if (ret == -1)
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index bb451c1bae1..5dc06b4d2b9 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1814,20 +1814,20 @@ dumpTimestamp(const char *msg)
* read_dumpall_filters - retrieve database identifier patterns from file
*
* Parse the specified filter file for include and exclude patterns, and add
- * them to the relevant lists. If the filename is "-" then filters will be
+ * them to the relevant lists. If the fname is "-" then filters will be
* read from STDIN rather than a file.
*
* At the moment, the only allowed filter is for database exclusion.
*/
static void
-read_dumpall_filters(const char *filename, SimpleStringList *pattern)
+read_dumpall_filters(const char *fname, SimpleStringList *pattern)
{
FilterStateData fstate;
char *objname;
FilterCommandType comtype;
FilterObjectType objtype;
- filter_init(&fstate, filename, exit);
+ filter_init(&fstate, fname, exit);
while (filter_read_item(&fstate, &objname, &comtype, &objtype))
{
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 8d5d9805279..5b5249537e6 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -719,15 +719,15 @@ GuessControlValues(void)
/*
- * Print the guessed pg_control values when we had to guess.
+ * Print the bGuessed pg_control values when we had to guess.
*
* NB: this display should be just those fields that will not be
* reset by RewriteControlFile().
*/
static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool bGuessed)
{
- if (guessed)
+ if (bGuessed)
printf(_("Guessed pg_control values:\n\n"));
else
printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 0060ea15902..d393b0ecfb0 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -625,10 +625,10 @@ pg_fsync_writethrough(int fd)
* print out the writes per second for tests
*/
static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start_time, struct timeval stop_time, int ops)
{
- double total_time = (stop_t.tv_sec - start_t.tv_sec) +
- (stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+ double total_time = (stop_time.tv_sec - start_time.tv_sec) +
+ (stop_time.tv_usec - start_time.tv_usec) * 0.000001;
double per_second = ops / total_time;
double avg_op_time_us = (total_time / ops) * USECS_SEC;
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0007-cleanup-rename-local-progname-variables-to-avoid-.patch (25.5K, 10-v4-0007-cleanup-rename-local-progname-variables-to-avoid-.patch)
download | inline diff:
From 32d1df734aaf251416e83f9f8aad958ad13fca05 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:59:43 +0800
Subject: [PATCH v4 07/13] cleanup: rename local progname variables to avoid
shadowing the global
This commit updates all functions that declared a local variable named
'progname', renaming each to 'myprogname'. The change prevents shadowing
of the global progname variable and keeps identifier usage unambiguous
within each scope.
A few additional shadowing fixes in the same files are included as well.
These unrelated cases are addressed here only because they occur in the
same code locations touched by the progname change, and bundling them
keeps the commit self-contained.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/bootstrap/bootstrap.c | 8 +-
src/backend/main/main.c | 14 ++--
src/bin/initdb/initdb.c | 60 +++++++-------
src/bin/pg_amcheck/pg_amcheck.c | 6 +-
src/bin/pg_basebackup/pg_createsubscriber.c | 14 ++--
src/bin/pg_dump/connectdb.c | 4 +-
src/bin/pg_dump/pg_dump.c | 90 ++++++++++-----------
src/bin/pg_dump/pg_restore.c | 6 +-
src/bin/pg_rewind/pg_rewind.c | 22 ++---
src/interfaces/ecpg/preproc/ecpg.c | 6 +-
10 files changed, 115 insertions(+), 115 deletions(-)
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index fc8638c1b61..f649c00113d 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -200,7 +200,7 @@ void
BootstrapModeMain(int argc, char *argv[], bool check_only)
{
int i;
- char *progname = argv[0];
+ char *myprogname = argv[0];
int flag;
char *userDoption = NULL;
uint32 bootstrap_data_checksum_version = 0; /* No checksum */
@@ -296,7 +296,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
break;
default:
write_stderr("Try \"%s --help\" for more information.\n",
- progname);
+ myprogname);
proc_exit(1);
break;
}
@@ -304,12 +304,12 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
if (argc != optind)
{
- write_stderr("%s: invalid command-line arguments\n", progname);
+ write_stderr("%s: invalid command-line arguments\n", myprogname);
proc_exit(1);
}
/* Acquire configuration parameters */
- if (!SelectConfigFiles(userDoption, progname))
+ if (!SelectConfigFiles(userDoption, myprogname))
proc_exit(1);
/*
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index 72aaee36a68..eeb64d09608 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -281,7 +281,7 @@ parse_dispatch_option(const char *name)
* without help. Avoid adding more here, if you can.
*/
static void
-startup_hacks(const char *progname)
+startup_hacks(const char *myprogname)
{
/*
* Windows-specific execution environment hacking.
@@ -300,7 +300,7 @@ startup_hacks(const char *progname)
if (err != 0)
{
write_stderr("%s: WSAStartup failed: %d\n",
- progname, err);
+ myprogname, err);
exit(1);
}
@@ -385,10 +385,10 @@ init_locale(const char *categoryname, int category, const char *locale)
* Messages emitted in write_console() do not exhibit this problem.
*/
static void
-help(const char *progname)
+help(const char *myprogname)
{
- printf(_("%s is the PostgreSQL server.\n\n"), progname);
- printf(_("Usage:\n %s [OPTION]...\n\n"), progname);
+ printf(_("%s is the PostgreSQL server.\n\n"), myprogname);
+ printf(_("Usage:\n %s [OPTION]...\n\n"), myprogname);
printf(_("Options:\n"));
printf(_(" -B NBUFFERS number of shared buffers\n"));
printf(_(" -c NAME=VALUE set run-time parameter\n"));
@@ -444,7 +444,7 @@ help(const char *progname)
static void
-check_root(const char *progname)
+check_root(const char *myprogname)
{
#ifndef WIN32
if (geteuid() == 0)
@@ -467,7 +467,7 @@ check_root(const char *progname)
if (getuid() != geteuid())
{
write_stderr("%s: real and effective user IDs must match\n",
- progname);
+ myprogname);
exit(1);
}
#else /* WIN32 */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 92fe2f531f7..d8e95ca2fe1 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -814,7 +814,7 @@ cleanup_directories_atexit(void)
static char *
get_id(void)
{
- const char *username;
+ const char *user;
#ifndef WIN32
if (geteuid() == 0) /* 0 is root's uid */
@@ -825,9 +825,9 @@ get_id(void)
}
#endif
- username = get_user_name_or_exit(progname);
+ user = get_user_name_or_exit(progname);
- return pg_strdup(username);
+ return pg_strdup(user);
}
static char *
@@ -1046,14 +1046,14 @@ write_version_file(const char *extrapath)
static void
set_null_conf(void)
{
- FILE *conf_file;
+ FILE *file;
char *path;
path = psprintf("%s/postgresql.conf", pg_data);
- conf_file = fopen(path, PG_BINARY_W);
- if (conf_file == NULL)
+ file = fopen(path, PG_BINARY_W);
+ if (file == NULL)
pg_fatal("could not open file \"%s\" for writing: %m", path);
- if (fclose(conf_file))
+ if (fclose(file))
pg_fatal("could not write file \"%s\": %m", path);
free(path);
}
@@ -2137,7 +2137,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
* Determine likely date order from locale
*/
static int
-locale_date_order(const char *locale)
+locale_date_order(const char *mylocale)
{
struct tm testtime;
char buf[128];
@@ -2152,7 +2152,7 @@ locale_date_order(const char *locale)
save = save_global_locale(LC_TIME);
- setlocale(LC_TIME, locale);
+ setlocale(LC_TIME, mylocale);
memset(&testtime, 0, sizeof(testtime));
testtime.tm_mday = 22;
@@ -2196,14 +2196,14 @@ locale_date_order(const char *locale)
* this should match the backend's check_locale() function
*/
static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *mylocale, char **canonname)
{
save_locale_t save;
char *res;
/* Don't let Windows' non-ASCII locale names in. */
- if (locale && !pg_is_ascii(locale))
- pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
+ if (mylocale && !pg_is_ascii(mylocale))
+ pg_fatal("locale name \"%s\" contains non-ASCII characters", mylocale);
if (canonname)
*canonname = NULL; /* in case of failure */
@@ -2211,11 +2211,11 @@ check_locale_name(int category, const char *locale, char **canonname)
save = save_global_locale(category);
/* for setlocale() call */
- if (!locale)
- locale = "";
+ if (!mylocale)
+ mylocale = "";
/* set the locale with setlocale, to see if it accepts it. */
- res = setlocale(category, locale);
+ res = setlocale(category, mylocale);
/* save canonical name if requested. */
if (res && canonname)
@@ -2227,9 +2227,9 @@ check_locale_name(int category, const char *locale, char **canonname)
/* complain if locale wasn't valid */
if (res == NULL)
{
- if (*locale)
+ if (*mylocale)
{
- pg_log_error("invalid locale name \"%s\"", locale);
+ pg_log_error("invalid locale name \"%s\"", mylocale);
pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale.");
exit(1);
}
@@ -2259,11 +2259,11 @@ check_locale_name(int category, const char *locale, char **canonname)
* this should match the similar check in the backend createdb() function
*/
static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *mylocale, int user_enc)
{
int locale_enc;
- locale_enc = pg_get_encoding_from_locale(locale, true);
+ locale_enc = pg_get_encoding_from_locale(mylocale, true);
/* See notes in createdb() to understand these tests */
if (!(locale_enc == user_enc ||
@@ -2511,11 +2511,11 @@ setlocales(void)
* print help text
*/
static void
-usage(const char *progname)
+usage(const char *myprogname)
{
- printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+ printf(_("%s initializes a PostgreSQL database cluster.\n\n"), myprogname);
printf(_("Usage:\n"));
- printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
+ printf(_(" %s [OPTION]... [DATADIR]\n"), myprogname);
printf(_("\nOptions:\n"));
printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
@@ -2591,14 +2591,14 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
}
static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
-{
- if ((strcmp(authmethodlocal, "md5") == 0 ||
- strcmp(authmethodlocal, "password") == 0 ||
- strcmp(authmethodlocal, "scram-sha-256") == 0) &&
- (strcmp(authmethodhost, "md5") == 0 ||
- strcmp(authmethodhost, "password") == 0 ||
- strcmp(authmethodhost, "scram-sha-256") == 0) &&
+check_need_password(const char *myauthmethodlocal, const char *myauthmethodhost)
+{
+ if ((strcmp(myauthmethodlocal, "md5") == 0 ||
+ strcmp(myauthmethodlocal, "password") == 0 ||
+ strcmp(myauthmethodlocal, "scram-sha-256") == 0) &&
+ (strcmp(myauthmethodhost, "md5") == 0 ||
+ strcmp(myauthmethodhost, "password") == 0 ||
+ strcmp(myauthmethodhost, "scram-sha-256") == 0) &&
!(pwprompt || pwfilename))
pg_fatal("must specify a password for the superuser to enable password authentication");
}
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index 2b1fd566c35..06a97712e18 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -1180,11 +1180,11 @@ verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
* progname: the name of the executed program, such as "pg_amcheck"
*/
static void
-help(const char *progname)
+help(const char *myprogname)
{
- printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
+ printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), myprogname);
printf(_("Usage:\n"));
- printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
+ printf(_(" %s [OPTION]... [DBNAME]\n"), myprogname);
printf(_("\nTarget options:\n"));
printf(_(" -a, --all check all databases\n"));
printf(_(" -d, --database=PATTERN check matching database(s)\n"));
diff --git a/src/bin/pg_basebackup/pg_createsubscriber.c b/src/bin/pg_basebackup/pg_createsubscriber.c
index 43dc6ff7693..04210e60bca 100644
--- a/src/bin/pg_basebackup/pg_createsubscriber.c
+++ b/src/bin/pg_basebackup/pg_createsubscriber.c
@@ -363,32 +363,32 @@ get_sub_conninfo(const struct CreateSubscriberOptions *opt)
* path of the progname.
*/
static char *
-get_exec_path(const char *argv0, const char *progname)
+get_exec_path(const char *argv0, const char *myprogname)
{
char *versionstr;
char *exec_path;
int ret;
- versionstr = psprintf("%s (PostgreSQL) %s\n", progname, PG_VERSION);
+ versionstr = psprintf("%s (PostgreSQL) %s\n", myprogname, PG_VERSION);
exec_path = pg_malloc(MAXPGPATH);
- ret = find_other_exec(argv0, progname, versionstr, exec_path);
+ ret = find_other_exec(argv0, myprogname, versionstr, exec_path);
if (ret < 0)
{
char full_path[MAXPGPATH];
if (find_my_exec(argv0, full_path) < 0)
- strlcpy(full_path, progname, sizeof(full_path));
+ strlcpy(full_path, myprogname, sizeof(full_path));
if (ret == -1)
pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
- progname, "pg_createsubscriber", full_path);
+ myprogname, "pg_createsubscriber", full_path);
else
pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
- progname, full_path, "pg_createsubscriber");
+ myprogname, full_path, "pg_createsubscriber");
}
- pg_log_debug("%s path is: %s", progname, exec_path);
+ pg_log_debug("%s path is: %s", myprogname, exec_path);
return exec_path;
}
diff --git a/src/bin/pg_dump/connectdb.c b/src/bin/pg_dump/connectdb.c
index d55d53dbeea..a2a1bad254b 100644
--- a/src/bin/pg_dump/connectdb.c
+++ b/src/bin/pg_dump/connectdb.c
@@ -39,7 +39,7 @@ static char *constructConnStr(const char **keywords, const char **values);
PGconn *
ConnectDatabase(const char *dbname, const char *connection_string,
const char *pghost, const char *pgport, const char *pguser,
- trivalue prompt_password, bool fail_on_error, const char *progname,
+ trivalue prompt_password, bool fail_on_error, const char *myprogname,
const char **connstr, int *server_version, char *password,
char *override_dbname)
{
@@ -221,7 +221,7 @@ ConnectDatabase(const char *dbname, const char *connection_string,
{
pg_log_error("aborting because of server version mismatch");
pg_log_error_detail("server version: %s; %s version: %s",
- remoteversion_str, progname, PG_VERSION);
+ remoteversion_str, myprogname, PG_VERSION);
exit_nicely(1);
}
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 2445085dbbd..d2b54916a0e 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -1301,11 +1301,11 @@ main(int argc, char **argv)
static void
-help(const char *progname)
+help(const char *myprogname)
{
- printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), progname);
+ printf(_("%s exports a PostgreSQL database as an SQL script or to other formats.\n\n"), myprogname);
printf(_("Usage:\n"));
- printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
+ printf(_(" %s [OPTION]... [DBNAME]\n"), myprogname);
printf(_("\nGeneral options:\n"));
printf(_(" -f, --file=FILENAME output file or directory name\n"));
@@ -1649,7 +1649,7 @@ static void
expand_schema_name_patterns(Archive *fout,
SimpleStringList *patterns,
SimpleOidList *oids,
- bool strict_names)
+ bool strict)
{
PQExpBuffer query;
PGresult *res;
@@ -1685,7 +1685,7 @@ expand_schema_name_patterns(Archive *fout,
termPQExpBuffer(&dbbuf);
res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
- if (strict_names && PQntuples(res) == 0)
+ if (strict && PQntuples(res) == 0)
pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
for (i = 0; i < PQntuples(res); i++)
@@ -1708,7 +1708,7 @@ static void
expand_extension_name_patterns(Archive *fout,
SimpleStringList *patterns,
SimpleOidList *oids,
- bool strict_names)
+ bool strict)
{
PQExpBuffer query;
PGresult *res;
@@ -1738,7 +1738,7 @@ expand_extension_name_patterns(Archive *fout,
cell->val);
res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
- if (strict_names && PQntuples(res) == 0)
+ if (strict && PQntuples(res) == 0)
pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
for (i = 0; i < PQntuples(res); i++)
@@ -1812,7 +1812,7 @@ expand_foreign_server_name_patterns(Archive *fout,
static void
expand_table_name_patterns(Archive *fout,
SimpleStringList *patterns, SimpleOidList *oids,
- bool strict_names, bool with_child_tables)
+ bool strict, bool with_child_tables)
{
PQExpBuffer query;
PGresult *res;
@@ -1884,7 +1884,7 @@ expand_table_name_patterns(Archive *fout,
res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
PQclear(ExecuteSqlQueryForSingleRow(fout,
ALWAYS_SECURE_SEARCH_PATH_SQL));
- if (strict_names && PQntuples(res) == 0)
+ if (strict && PQntuples(res) == 0)
pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
for (i = 0; i < PQntuples(res); i++)
@@ -10870,8 +10870,8 @@ dumpCommentExtended(Archive *fout, const char *type,
const char *initdb_comment)
{
DumpOptions *dopt = fout->dopt;
- CommentItem *comments;
- int ncomments;
+ CommentItem *comment_items;
+ int n_comment_items;
/* do nothing, if --no-comments is supplied */
if (dopt->no_comments)
@@ -10891,16 +10891,16 @@ dumpCommentExtended(Archive *fout, const char *type,
}
/* Search for comments associated with catalogId, using table */
- ncomments = findComments(catalogId.tableoid, catalogId.oid,
- &comments);
+ n_comment_items = findComments(catalogId.tableoid, catalogId.oid,
+ &comment_items);
/* Is there one matching the subid? */
- while (ncomments > 0)
+ while (n_comment_items > 0)
{
- if (comments->objsubid == subid)
+ if (comment_items->objsubid == subid)
break;
- comments++;
- ncomments--;
+ comment_items++;
+ n_comment_items--;
}
if (initdb_comment != NULL)
@@ -10913,17 +10913,17 @@ dumpCommentExtended(Archive *fout, const char *type,
* non-superuser use of pg_dump. When the DBA has removed initdb's
* comment, replicate that.
*/
- if (ncomments == 0)
+ if (n_comment_items == 0)
{
- comments = &empty_comment;
- ncomments = 1;
+ comment_items = &empty_comment;
+ n_comment_items = 1;
}
- else if (strcmp(comments->descr, initdb_comment) == 0)
- ncomments = 0;
+ else if (strcmp(comment_items->descr, initdb_comment) == 0)
+ n_comment_items = 0;
}
/* If a comment exists, build COMMENT ON statement */
- if (ncomments > 0)
+ if (n_comment_items > 0)
{
PQExpBuffer query = createPQExpBuffer();
PQExpBuffer tag = createPQExpBuffer();
@@ -10932,7 +10932,7 @@ dumpCommentExtended(Archive *fout, const char *type,
if (namespace && *namespace)
appendPQExpBuffer(query, "%s.", fmtId(namespace));
appendPQExpBuffer(query, "%s IS ", name);
- appendStringLiteralAH(query, comments->descr, fout);
+ appendStringLiteralAH(query, comment_items->descr, fout);
appendPQExpBufferStr(query, ";\n");
appendPQExpBuffer(tag, "%s %s", type, name);
@@ -11388,8 +11388,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
const char *reltypename)
{
DumpOptions *dopt = fout->dopt;
- CommentItem *comments;
- int ncomments;
+ CommentItem *comment_items;
+ int n_comment_items;
PQExpBuffer query;
PQExpBuffer tag;
@@ -11402,21 +11402,21 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
return;
/* Search for comments associated with relation, using table */
- ncomments = findComments(tbinfo->dobj.catId.tableoid,
- tbinfo->dobj.catId.oid,
- &comments);
+ n_comment_items = findComments(tbinfo->dobj.catId.tableoid,
+ tbinfo->dobj.catId.oid,
+ &comment_items);
/* If comments exist, build COMMENT ON statements */
- if (ncomments <= 0)
+ if (n_comment_items <= 0)
return;
query = createPQExpBuffer();
tag = createPQExpBuffer();
- while (ncomments > 0)
+ while (n_comment_items > 0)
{
- const char *descr = comments->descr;
- int objsubid = comments->objsubid;
+ const char *descr = comment_items->descr;
+ int objsubid = comment_items->objsubid;
if (objsubid == 0)
{
@@ -11466,8 +11466,8 @@ dumpTableComment(Archive *fout, const TableInfo *tbinfo,
.nDeps = 1));
}
- comments++;
- ncomments--;
+ comment_items++;
+ n_comment_items--;
}
destroyPQExpBuffer(query);
@@ -13116,8 +13116,8 @@ static void
dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
PGresult *res)
{
- CommentItem *comments;
- int ncomments;
+ CommentItem *comment_items;
+ int n_comment_items;
PQExpBuffer query;
PQExpBuffer target;
int i;
@@ -13131,11 +13131,11 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
return;
/* Search for comments associated with type's pg_class OID */
- ncomments = findComments(RelationRelationId, tyinfo->typrelid,
- &comments);
+ n_comment_items = findComments(RelationRelationId, tyinfo->typrelid,
+ &comment_items);
/* If no comments exist, we're done */
- if (ncomments <= 0)
+ if (n_comment_items <= 0)
return;
/* Build COMMENT ON statements */
@@ -13146,14 +13146,14 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
i_attnum = PQfnumber(res, "attnum");
i_attname = PQfnumber(res, "attname");
i_attisdropped = PQfnumber(res, "attisdropped");
- while (ncomments > 0)
+ while (n_comment_items > 0)
{
const char *attname;
attname = NULL;
for (i = 0; i < ntups; i++)
{
- if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
+ if (atoi(PQgetvalue(res, i, i_attnum)) == comment_items->objsubid &&
PQgetvalue(res, i, i_attisdropped)[0] != 't')
{
attname = PQgetvalue(res, i, i_attname);
@@ -13162,7 +13162,7 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
}
if (attname) /* just in case we don't find it */
{
- const char *descr = comments->descr;
+ const char *descr = comment_items->descr;
resetPQExpBuffer(target);
appendPQExpBuffer(target, "COLUMN %s.",
@@ -13187,8 +13187,8 @@ dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
.nDeps = 1));
}
- comments++;
- ncomments--;
+ comment_items++;
+ n_comment_items--;
}
destroyPQExpBuffer(query);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index c9776306c5c..5f778ec9e77 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -517,11 +517,11 @@ main(int argc, char **argv)
}
static void
-usage(const char *progname)
+usage(const char *myprogname)
{
- printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+ printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), myprogname);
printf(_("Usage:\n"));
- printf(_(" %s [OPTION]... [FILE]\n"), progname);
+ printf(_(" %s [OPTION]... [FILE]\n"), myprogname);
printf(_("\nGeneral options:\n"));
printf(_(" -d, --dbname=NAME connect to database name\n"));
diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c
index e9364d04f76..4bacd9e9d34 100644
--- a/src/bin/pg_rewind/pg_rewind.c
+++ b/src/bin/pg_rewind/pg_rewind.c
@@ -89,9 +89,9 @@ static PGconn *conn;
static rewind_source *source;
static void
-usage(const char *progname)
+usage(const char *myprogname)
{
- printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
+ printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), myprogname);
printf(_("Usage:\n %s [OPTION]...\n\n"), progname);
printf(_("Options:\n"));
printf(_(" -c, --restore-target-wal use \"restore_command\" in target configuration to\n"
@@ -561,7 +561,7 @@ main(int argc, char **argv)
* target and the source.
*/
static void
-perform_rewind(filemap_t *filemap, rewind_source *source,
+perform_rewind(filemap_t *filemap, rewind_source *rewindsource,
XLogRecPtr chkptrec,
TimeLineID chkpttli,
XLogRecPtr chkptredo)
@@ -595,7 +595,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
while (datapagemap_next(iter, &blkno))
{
offset = blkno * BLCKSZ;
- source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
+ rewindsource->queue_fetch_range(rewindsource, entry->path, offset, BLCKSZ);
}
pg_free(iter);
}
@@ -607,7 +607,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
break;
case FILE_ACTION_COPY:
- source->queue_fetch_file(source, entry->path, entry->source_size);
+ rewindsource->queue_fetch_file(rewindsource, entry->path, entry->source_size);
break;
case FILE_ACTION_TRUNCATE:
@@ -615,9 +615,9 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
break;
case FILE_ACTION_COPY_TAIL:
- source->queue_fetch_range(source, entry->path,
- entry->target_size,
- entry->source_size - entry->target_size);
+ rewindsource->queue_fetch_range(rewindsource, entry->path,
+ entry->target_size,
+ entry->source_size - entry->target_size);
break;
case FILE_ACTION_REMOVE:
@@ -635,7 +635,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
}
/* Complete any remaining range-fetches that we queued up above. */
- source->finish_fetch(source);
+ rewindsource->finish_fetch(rewindsource);
close_target_file();
@@ -645,7 +645,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
* Fetch the control file from the source last. This ensures that the
* minRecoveryPoint is up-to-date.
*/
- buffer = source->fetch_file(source, XLOG_CONTROL_FILE, &size);
+ buffer = rewindsource->fetch_file(rewindsource, XLOG_CONTROL_FILE, &size);
digestControlFile(&ControlFile_source_after, buffer, size);
pg_free(buffer);
@@ -717,7 +717,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source,
if (ControlFile_source_after.state != DB_IN_PRODUCTION)
pg_fatal("source system was in unexpected state at end of rewind");
- endrec = source->get_current_wal_insert_lsn(source);
+ endrec = rewindsource->get_current_wal_insert_lsn(rewindsource);
endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
ControlFile_source_after.minRecoveryPointTLI);
}
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index 3f0f10e654a..525988a2302 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -32,13 +32,13 @@ struct _defines *defines = NULL;
struct declared_list *g_declared_list = NULL;
static void
-help(const char *progname)
+help(const char *myprogname)
{
printf(_("%s is the PostgreSQL embedded SQL preprocessor for C programs.\n\n"),
- progname);
+ myprogname);
printf(_("Usage:\n"
" %s [OPTION]... FILE...\n\n"),
- progname);
+ myprogname);
printf(_("Options:\n"));
printf(_(" -c automatically generate C code from embedded SQL code;\n"
" this affects EXEC SQL TYPE\n"));
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch (13.6K, 11-v4-0006-cleanup-avoid-local-variables-shadowed-by-static-.patch)
download | inline diff:
From 37dde5b77786e6ebd7883dff2a79efb3af8392ab Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 14:01:31 +0800
Subject: [PATCH v4 06/13] cleanup: avoid local variables shadowed by static
file-scope ones in xlogrecovery.c
This commit fixes several cases in xlogrecovery.c where local variables
used names that conflicted with static variables defined at file scope.
The local identifiers are renamed so they are no longer shadowed by the
static ones.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/access/transam/xlogrecovery.c | 100 +++++++++++-----------
1 file changed, 50 insertions(+), 50 deletions(-)
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 21b8f179ba0..903e2afe5ed 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1208,7 +1208,7 @@ validateRecoveryParameters(void)
* Returns true if a backup_label was found (and fills the checkpoint
* location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
* returns false if not. If this backup_label came from a streamed backup,
- * *backupEndRequired is set to true. If this backup_label was created during
+ * *backupEndNeeded is set to true. If this backup_label was created during
* recovery, *backupFromStandby is set to true.
*
* Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
@@ -1216,7 +1216,7 @@ validateRecoveryParameters(void)
*/
static bool
read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
- bool *backupEndRequired, bool *backupFromStandby)
+ bool *backupEndNeeded, bool *backupFromStandby)
{
char startxlogfilename[MAXFNAMELEN];
TimeLineID tli_from_walseg,
@@ -1233,7 +1233,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
/* suppress possible uninitialized-variable warnings */
*checkPointLoc = InvalidXLogRecPtr;
*backupLabelTLI = 0;
- *backupEndRequired = false;
+ *backupEndNeeded = false;
*backupFromStandby = false;
/*
@@ -1277,13 +1277,13 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
* other option today being from pg_rewind). If this was a streamed
* backup then we know that we need to play through until we get to the
* end of the WAL which was generated during the backup (at which point we
- * will have reached consistency and backupEndRequired will be reset to be
+ * will have reached consistency and backupEndNeeded will be reset to be
* false).
*/
if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
{
if (strcmp(backuptype, "streamed") == 0)
- *backupEndRequired = true;
+ *backupEndNeeded = true;
}
/*
@@ -1927,14 +1927,14 @@ PerformWalRecovery(void)
* Subroutine of PerformWalRecovery, to apply one WAL record.
*/
static void
-ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
+ApplyWalRecord(XLogReaderState *reader, XLogRecord *record, TimeLineID *replayTLI)
{
ErrorContextCallback errcallback;
bool switchedTLI = false;
/* Setup error traceback support for ereport() */
errcallback.callback = rm_redo_error_callback;
- errcallback.arg = xlogreader;
+ errcallback.arg = reader;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
@@ -1961,7 +1961,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
{
CheckPoint checkPoint;
- memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+ memcpy(&checkPoint, XLogRecGetData(reader), sizeof(CheckPoint));
newReplayTLI = checkPoint.ThisTimeLineID;
prevReplayTLI = checkPoint.PrevTimeLineID;
}
@@ -1969,7 +1969,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
{
xl_end_of_recovery xlrec;
- memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
+ memcpy(&xlrec, XLogRecGetData(reader), sizeof(xl_end_of_recovery));
newReplayTLI = xlrec.ThisTimeLineID;
prevReplayTLI = xlrec.PrevTimeLineID;
}
@@ -1977,7 +1977,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
if (newReplayTLI != *replayTLI)
{
/* Check that it's OK to switch to this TLI */
- checkTimeLineSwitch(xlogreader->EndRecPtr,
+ checkTimeLineSwitch(reader->EndRecPtr,
newReplayTLI, prevReplayTLI, *replayTLI);
/* Following WAL records should be run with new TLI */
@@ -1991,7 +1991,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
* XLogFlush will update minRecoveryPoint correctly.
*/
SpinLockAcquire(&XLogRecoveryCtl->info_lck);
- XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
+ XLogRecoveryCtl->replayEndRecPtr = reader->EndRecPtr;
XLogRecoveryCtl->replayEndTLI = *replayTLI;
SpinLockRelease(&XLogRecoveryCtl->info_lck);
@@ -2007,10 +2007,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
* directly here, rather than in xlog_redo()
*/
if (record->xl_rmid == RM_XLOG_ID)
- xlogrecovery_redo(xlogreader, *replayTLI);
+ xlogrecovery_redo(reader, *replayTLI);
/* Now apply the WAL record itself */
- GetRmgr(record->xl_rmid).rm_redo(xlogreader);
+ GetRmgr(record->xl_rmid).rm_redo(reader);
/*
* After redo, check whether the backup pages associated with the WAL
@@ -2018,7 +2018,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
* if consistency check is enabled for this record.
*/
if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
- verifyBackupPageConsistency(xlogreader);
+ verifyBackupPageConsistency(reader);
/* Pop the error context stack */
error_context_stack = errcallback.previous;
@@ -2028,8 +2028,8 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
* replayed.
*/
SpinLockAcquire(&XLogRecoveryCtl->info_lck);
- XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
- XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
+ XLogRecoveryCtl->lastReplayedReadRecPtr = reader->ReadRecPtr;
+ XLogRecoveryCtl->lastReplayedEndRecPtr = reader->EndRecPtr;
XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
SpinLockRelease(&XLogRecoveryCtl->info_lck);
@@ -2079,7 +2079,7 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
* Before we continue on the new timeline, clean up any (possibly
* bogus) future WAL segments on the old timeline.
*/
- RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
+ RemoveNonParentXlogFiles(reader->EndRecPtr, *replayTLI);
/* Reset the prefetcher. */
XLogPrefetchReconfigure();
@@ -3152,19 +3152,19 @@ ConfirmRecoveryPaused(void)
* record is available.
*/
static XLogRecord *
-ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
+ReadRecord(XLogPrefetcher *prefetcher, int emode,
bool fetching_ckpt, TimeLineID replayTLI)
{
XLogRecord *record;
- XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
- XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+ XLogReaderState *reader = XLogPrefetcherGetReader(prefetcher);
+ XLogPageReadPrivate *private = (XLogPageReadPrivate *) reader->private_data;
Assert(AmStartupProcess() || !IsUnderPostmaster);
/* Pass through parameters to XLogPageRead */
private->fetching_ckpt = fetching_ckpt;
private->emode = emode;
- private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
+ private->randAccess = !XLogRecPtrIsValid(reader->ReadRecPtr);
private->replayTLI = replayTLI;
/* This is the first attempt to read this page. */
@@ -3174,7 +3174,7 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
{
char *errormsg;
- record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
+ record = XLogPrefetcherReadRecord(prefetcher, &errormsg);
if (record == NULL)
{
/*
@@ -3190,10 +3190,10 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
* overwrite contrecord in the wrong place, breaking everything.
*/
if (!ArchiveRecoveryRequested &&
- XLogRecPtrIsValid(xlogreader->abortedRecPtr))
+ XLogRecPtrIsValid(reader->abortedRecPtr))
{
- abortedRecPtr = xlogreader->abortedRecPtr;
- missingContrecPtr = xlogreader->missingContrecPtr;
+ abortedRecPtr = reader->abortedRecPtr;
+ missingContrecPtr = reader->missingContrecPtr;
}
if (readFile >= 0)
@@ -3209,29 +3209,29 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
* shouldn't loop anymore in that case.
*/
if (errormsg)
- ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+ ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
(errmsg_internal("%s", errormsg) /* already translated */ ));
}
/*
* Check page TLI is one of the expected values.
*/
- else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
+ else if (!tliInHistory(reader->latestPageTLI, expectedTLEs))
{
char fname[MAXFNAMELEN];
XLogSegNo segno;
int32 offset;
- XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
- offset = XLogSegmentOffset(xlogreader->latestPagePtr,
+ XLByteToSeg(reader->latestPagePtr, segno, wal_segment_size);
+ offset = XLogSegmentOffset(reader->latestPagePtr,
wal_segment_size);
- XLogFileName(fname, xlogreader->seg.ws_tli, segno,
+ XLogFileName(fname, reader->seg.ws_tli, segno,
wal_segment_size);
- ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
+ ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
- xlogreader->latestPageTLI,
+ reader->latestPageTLI,
fname,
- LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
+ LSN_FORMAT_ARGS(reader->latestPagePtr),
offset));
record = NULL;
}
@@ -3267,8 +3267,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
if (StandbyModeRequested)
EnableStandbyMode();
- SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
- minRecoveryPoint = xlogreader->EndRecPtr;
+ SwitchIntoArchiveRecovery(reader->EndRecPtr, replayTLI);
+ minRecoveryPoint = reader->EndRecPtr;
minRecoveryPointTLI = replayTLI;
CheckRecoveryConsistency();
@@ -3321,11 +3321,11 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
* sleep and retry.
*/
static int
-XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
+XLogPageRead(XLogReaderState *reader, XLogRecPtr targetPagePtr, int reqLen,
XLogRecPtr targetRecPtr, char *readBuf)
{
XLogPageReadPrivate *private =
- (XLogPageReadPrivate *) xlogreader->private_data;
+ (XLogPageReadPrivate *) reader->private_data;
int emode = private->emode;
uint32 targetPageOff;
XLogSegNo targetSegNo PG_USED_FOR_ASSERTS_ONLY;
@@ -3372,7 +3372,7 @@ retry:
flushedUpto < targetPagePtr + reqLen))
{
if (readFile >= 0 &&
- xlogreader->nonblocking &&
+ reader->nonblocking &&
readSource == XLOG_FROM_STREAM &&
flushedUpto < targetPagePtr + reqLen)
return XLREAD_WOULDBLOCK;
@@ -3382,8 +3382,8 @@ retry:
private->fetching_ckpt,
targetRecPtr,
private->replayTLI,
- xlogreader->EndRecPtr,
- xlogreader->nonblocking))
+ reader->EndRecPtr,
+ reader->nonblocking))
{
case XLREAD_WOULDBLOCK:
return XLREAD_WOULDBLOCK;
@@ -3467,7 +3467,7 @@ retry:
Assert(targetPageOff == readOff);
Assert(reqLen <= readLen);
- xlogreader->seg.ws_tli = curFileTLI;
+ reader->seg.ws_tli = curFileTLI;
/*
* Check the page header immediately, so that we can retry immediately if
@@ -3503,18 +3503,18 @@ retry:
*/
if (StandbyMode &&
(targetPagePtr % wal_segment_size) == 0 &&
- !XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
+ !XLogReaderValidatePageHeader(reader, targetPagePtr, readBuf))
{
/*
* Emit this error right now then retry this page immediately. Use
* errmsg_internal() because the message was already translated.
*/
- if (xlogreader->errormsg_buf[0])
- ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
- (errmsg_internal("%s", xlogreader->errormsg_buf)));
+ if (reader->errormsg_buf[0])
+ ereport(emode_for_corrupt_record(emode, reader->EndRecPtr),
+ (errmsg_internal("%s", reader->errormsg_buf)));
/* reset any error XLogReaderValidatePageHeader() might have set */
- XLogReaderResetError(xlogreader);
+ XLogReaderResetError(reader);
goto next_record_is_invalid;
}
@@ -3526,7 +3526,7 @@ next_record_is_invalid:
* If we're reading ahead, give up fast. Retries and error reporting will
* be handled by a later read when recovery catches up to this point.
*/
- if (xlogreader->nonblocking)
+ if (reader->nonblocking)
return XLREAD_WOULDBLOCK;
lastSourceFailed = true;
@@ -4104,7 +4104,7 @@ emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
* Subroutine to try to fetch and validate a prior checkpoint record.
*/
static XLogRecord *
-ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
+ReadCheckpointRecord(XLogPrefetcher *prefetcher, XLogRecPtr RecPtr,
TimeLineID replayTLI)
{
XLogRecord *record;
@@ -4119,8 +4119,8 @@ ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
return NULL;
}
- XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
- record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
+ XLogPrefetcherBeginRead(prefetcher, RecPtr);
+ record = ReadRecord(prefetcher, LOG, true, replayTLI);
if (record == NULL)
{
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch (6.8K, 12-v4-0009-cleanup-avoid-local-variables-shadowed-by-globals.patch)
download | inline diff:
From 1a8ebf5384398a32ee3c7a67f48ffc2fa21454e8 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 15:05:05 +0800
Subject: [PATCH v4 09/13] cleanup: avoid local variables shadowed by globals
across several files
This commit fixes multiple instances where local variables used the same
names as global identifiers in various modules. The affected locals are
renamed so they are no longer shadowed by the globals and remain clear
within their respective scopes.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/libpq/be-secure-common.c | 12 ++++-----
src/common/controldata_utils.c | 8 +++---
src/interfaces/ecpg/preproc/descriptor.c | 34 ++++++++++++------------
3 files changed, 27 insertions(+), 27 deletions(-)
diff --git a/src/backend/libpq/be-secure-common.c b/src/backend/libpq/be-secure-common.c
index e8b837d1fa7..8b674435bd2 100644
--- a/src/backend/libpq/be-secure-common.c
+++ b/src/backend/libpq/be-secure-common.c
@@ -111,17 +111,17 @@ error:
* Check permissions for SSL key files.
*/
bool
-check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
+check_ssl_key_file_permissions(const char *sslKeyFile, bool isServerStart)
{
int loglevel = isServerStart ? FATAL : LOG;
struct stat buf;
- if (stat(ssl_key_file, &buf) != 0)
+ if (stat(sslKeyFile, &buf) != 0)
{
ereport(loglevel,
(errcode_for_file_access(),
errmsg("could not access private key file \"%s\": %m",
- ssl_key_file)));
+ sslKeyFile)));
return false;
}
@@ -131,7 +131,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
ereport(loglevel,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("private key file \"%s\" is not a regular file",
- ssl_key_file)));
+ sslKeyFile)));
return false;
}
@@ -157,7 +157,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
ereport(loglevel,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("private key file \"%s\" must be owned by the database user or root",
- ssl_key_file)));
+ sslKeyFile)));
return false;
}
@@ -167,7 +167,7 @@ check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
ereport(loglevel,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("private key file \"%s\" has group or world access",
- ssl_key_file),
+ sslKeyFile),
errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
return false;
}
diff --git a/src/common/controldata_utils.c b/src/common/controldata_utils.c
index fa375dc9129..78464e8237f 100644
--- a/src/common/controldata_utils.c
+++ b/src/common/controldata_utils.c
@@ -49,11 +49,11 @@
* file data is correct.
*/
ControlFileData *
-get_controlfile(const char *DataDir, bool *crc_ok_p)
+get_controlfile(const char *data_dir, bool *crc_ok_p)
{
char ControlFilePath[MAXPGPATH];
- snprintf(ControlFilePath, MAXPGPATH, "%s/%s", DataDir, XLOG_CONTROL_FILE);
+ snprintf(ControlFilePath, MAXPGPATH, "%s/%s", data_dir, XLOG_CONTROL_FILE);
return get_controlfile_by_exact_path(ControlFilePath, crc_ok_p);
}
@@ -186,7 +186,7 @@ retry:
* routine in the backend.
*/
void
-update_controlfile(const char *DataDir,
+update_controlfile(const char *data_dir,
ControlFileData *ControlFile, bool do_sync)
{
int fd;
@@ -211,7 +211,7 @@ update_controlfile(const char *DataDir,
memset(buffer, 0, PG_CONTROL_FILE_SIZE);
memcpy(buffer, ControlFile, sizeof(ControlFileData));
- snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", DataDir, XLOG_CONTROL_FILE);
+ snprintf(ControlFilePath, sizeof(ControlFilePath), "%s/%s", data_dir, XLOG_CONTROL_FILE);
#ifndef FRONTEND
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index e8c7016bdc1..9dac761e393 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -72,7 +72,7 @@ ECPGnumeric_lvalue(char *name)
static struct descriptor *descriptors;
void
-add_descriptor(const char *name, const char *connection)
+add_descriptor(const char *name, const char *conn_str)
{
struct descriptor *new;
@@ -83,15 +83,15 @@ add_descriptor(const char *name, const char *connection)
new->next = descriptors;
new->name = mm_strdup(name);
- if (connection)
- new->connection = mm_strdup(connection);
+ if (conn_str)
+ new->connection = mm_strdup(conn_str);
else
new->connection = NULL;
descriptors = new;
}
void
-drop_descriptor(const char *name, const char *connection)
+drop_descriptor(const char *name, const char *conn_str)
{
struct descriptor *i;
struct descriptor **lastptr = &descriptors;
@@ -103,9 +103,9 @@ drop_descriptor(const char *name, const char *connection)
{
if (strcmp(name, i->name) == 0)
{
- if ((!connection && !i->connection)
- || (connection && i->connection
- && strcmp(connection, i->connection) == 0))
+ if ((!conn_str && !i->connection)
+ || (conn_str && i->connection
+ && strcmp(conn_str, i->connection) == 0))
{
*lastptr = i->next;
free(i->connection);
@@ -115,14 +115,14 @@ drop_descriptor(const char *name, const char *connection)
}
}
}
- if (connection)
- mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+ if (conn_str)
+ mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
else
mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
}
struct descriptor *
-lookup_descriptor(const char *name, const char *connection)
+lookup_descriptor(const char *name, const char *conn_str)
{
struct descriptor *i;
@@ -133,20 +133,20 @@ lookup_descriptor(const char *name, const char *connection)
{
if (strcmp(name, i->name) == 0)
{
- if ((!connection && !i->connection)
- || (connection && i->connection
- && strcmp(connection, i->connection) == 0))
+ if ((!conn_str && !i->connection)
+ || (conn_str && i->connection
+ && strcmp(conn_str, i->connection) == 0))
return i;
- if (connection && !i->connection)
+ if (conn_str && !i->connection)
{
/* overwrite descriptor's connection */
- i->connection = mm_strdup(connection);
+ i->connection = mm_strdup(conn_str);
return i;
}
}
}
- if (connection)
- mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, connection);
+ if (conn_str)
+ mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to connection %s does not exist", name, conn_str);
else
mmerror(PARSE_ERROR, ET_WARNING, "descriptor %s bound to the default connection does not exist", name);
return NULL;
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch (20.6K, 13-v4-0013-cleanup-avoid-local-variables-shadowed-by-globals.patch)
download | inline diff:
From 5a897eb7a96df958c5de4c4567dea6ad69b37894 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 08:44:46 +0800
Subject: [PATCH v4 13/13] cleanup: avoid local variables shadowed by globals
across time-related modules
This commit renames several local variables in date/time and timezone
code that were shadowed by global identifiers of the same names. The
updated local identifiers ensure clearer separation of scope throughout
the affected modules.
A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/backend/utils/adt/date.c | 20 +++----
src/backend/utils/adt/datetime.c | 20 +++----
src/backend/utils/adt/formatting.c | 8 +--
src/backend/utils/adt/timestamp.c | 92 +++++++++++++++---------------
src/bin/initdb/findtimezone.c | 38 ++++++------
src/timezone/pgtz.c | 16 +++---
6 files changed, 97 insertions(+), 97 deletions(-)
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index c4b8125dd66..6afbfbabccb 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -570,16 +570,16 @@ Datum
date_pli(PG_FUNCTION_ARGS)
{
DateADT dateVal = PG_GETARG_DATEADT(0);
- int32 days = PG_GETARG_INT32(1);
+ int32 dayVal = PG_GETARG_INT32(1);
DateADT result;
if (DATE_NOT_FINITE(dateVal))
PG_RETURN_DATEADT(dateVal); /* can't change infinity */
- result = dateVal + days;
+ result = dateVal + dayVal;
/* Check for integer overflow and out-of-allowed-range */
- if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+ if ((dayVal >= 0 ? (result < dateVal) : (result > dateVal)) ||
!IS_VALID_DATE(result))
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -594,16 +594,16 @@ Datum
date_mii(PG_FUNCTION_ARGS)
{
DateADT dateVal = PG_GETARG_DATEADT(0);
- int32 days = PG_GETARG_INT32(1);
+ int32 dayVal = PG_GETARG_INT32(1);
DateADT result;
if (DATE_NOT_FINITE(dateVal))
PG_RETURN_DATEADT(dateVal); /* can't change infinity */
- result = dateVal - days;
+ result = dateVal - dayVal;
/* Check for integer overflow and out-of-allowed-range */
- if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+ if ((dayVal >= 0 ? (result > dateVal) : (result < dateVal)) ||
!IS_VALID_DATE(result))
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -3159,7 +3159,7 @@ timetz_zone(PG_FUNCTION_ARGS)
TimeTzADT *t = PG_GETARG_TIMETZADT_P(1);
TimeTzADT *result;
int tz;
- char tzname[TZ_STRLEN_MAX + 1];
+ char tz_name[TZ_STRLEN_MAX + 1];
int type,
val;
pg_tz *tzp;
@@ -3167,9 +3167,9 @@ timetz_zone(PG_FUNCTION_ARGS)
/*
* Look up the requested timezone.
*/
- text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+ text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
- type = DecodeTimezoneName(tzname, &val, &tzp);
+ type = DecodeTimezoneName(tz_name, &val, &tzp);
if (type == TZNAME_FIXED_OFFSET)
{
@@ -3182,7 +3182,7 @@ timetz_zone(PG_FUNCTION_ARGS)
TimestampTz now = GetCurrentTransactionStartTimestamp();
int isdst;
- tz = DetermineTimeZoneAbbrevOffsetTS(now, tzname, tzp, &isdst);
+ tz = DetermineTimeZoneAbbrevOffsetTS(now, tz_name, tzp, &isdst);
}
else
{
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 680fee2a844..d8240beafc2 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -642,12 +642,12 @@ AdjustMicroseconds(int64 val, double fval, int64 scale,
static bool
AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
{
- int days;
+ int dayVal;
if (val < INT_MIN || val > INT_MAX)
return false;
- return !pg_mul_s32_overflow((int32) val, scale, &days) &&
- !pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
+ return !pg_mul_s32_overflow((int32) val, scale, &dayVal) &&
+ !pg_add_s32_overflow(itm_in->tm_mday, dayVal, &itm_in->tm_mday);
}
/*
@@ -3285,7 +3285,7 @@ DecodeSpecial(int field, const char *lowtoken, int *val)
* the zone name or the abbreviation's underlying zone.
*/
int
-DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
+DecodeTimezoneName(const char *tz_name, int *offset, pg_tz **tz)
{
char *lowzone;
int dterr,
@@ -3302,8 +3302,8 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
*/
/* DecodeTimezoneAbbrev requires lowercase input */
- lowzone = downcase_truncate_identifier(tzname,
- strlen(tzname),
+ lowzone = downcase_truncate_identifier(tz_name,
+ strlen(tz_name),
false);
dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
@@ -3323,11 +3323,11 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
else
{
/* try it as a full zone name */
- *tz = pg_tzset(tzname);
+ *tz = pg_tzset(tz_name);
if (*tz == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("time zone \"%s\" not recognized", tzname)));
+ errmsg("time zone \"%s\" not recognized", tz_name)));
return TZNAME_ZONE;
}
}
@@ -3340,12 +3340,12 @@ DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
* result in all cases.
*/
pg_tz *
-DecodeTimezoneNameToTz(const char *tzname)
+DecodeTimezoneNameToTz(const char *tz_name)
{
pg_tz *result;
int offset;
- if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
+ if (DecodeTimezoneName(tz_name, &offset, &result) == TZNAME_FIXED_OFFSET)
{
/* fixed-offset abbreviation, get a pg_tz descriptor for that */
result = pg_tzset_offset(-offset); /* flip to POSIX sign convention */
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 5bfeda2ffde..d385591b53e 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -3041,12 +3041,12 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
else
{
int mon = 0;
- const char *const *months;
+ const char *const *pmonths;
if (n->key->id == DCH_RM)
- months = rm_months_upper;
+ pmonths = rm_months_upper;
else
- months = rm_months_lower;
+ pmonths = rm_months_lower;
/*
* Compute the position in the roman-numeral array. Note
@@ -3081,7 +3081,7 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
}
sprintf(s, "%*s", IS_SUFFIX_FM(n->suffix) ? 0 : -4,
- months[mon]);
+ pmonths[mon]);
s += strlen(s);
}
break;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 2dc90a2b8a9..027711a99ca 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -490,11 +490,11 @@ timestamptz_in(PG_FUNCTION_ARGS)
static int
parse_sane_timezone(struct pg_tm *tm, text *zone)
{
- char tzname[TZ_STRLEN_MAX + 1];
+ char tz_name[TZ_STRLEN_MAX + 1];
int dterr;
int tz;
- text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+ text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
/*
* Look up the requested timezone. First we try to interpret it as a
@@ -506,14 +506,14 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
* as invalid, it's enough to disallow having a digit in the first
* position of our input string.
*/
- if (isdigit((unsigned char) *tzname))
+ if (isdigit((unsigned char) *tz_name))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid input syntax for type %s: \"%s\"",
- "numeric time zone", tzname),
+ "numeric time zone", tz_name),
errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
- dterr = DecodeTimezone(tzname, &tz);
+ dterr = DecodeTimezone(tz_name, &tz);
if (dterr != 0)
{
int type,
@@ -523,13 +523,13 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
if (dterr == DTERR_TZDISP_OVERFLOW)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("numeric time zone \"%s\" out of range", tzname)));
+ errmsg("numeric time zone \"%s\" out of range", tz_name)));
else if (dterr != DTERR_BAD_FORMAT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("time zone \"%s\" not recognized", tzname)));
+ errmsg("time zone \"%s\" not recognized", tz_name)));
- type = DecodeTimezoneName(tzname, &val, &tzp);
+ type = DecodeTimezoneName(tz_name, &val, &tzp);
if (type == TZNAME_FIXED_OFFSET)
{
@@ -539,7 +539,7 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
else if (type == TZNAME_DYNTZ)
{
/* dynamic-offset abbreviation, resolve using specified time */
- tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
+ tz = DetermineTimeZoneAbbrevOffset(tm, tz_name, tzp);
}
else
{
@@ -559,11 +559,11 @@ parse_sane_timezone(struct pg_tm *tm, text *zone)
static pg_tz *
lookup_timezone(text *zone)
{
- char tzname[TZ_STRLEN_MAX + 1];
+ char tz_name[TZ_STRLEN_MAX + 1];
- text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+ text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
- return DecodeTimezoneNameToTz(tzname);
+ return DecodeTimezoneNameToTz(tz_name);
}
/*
@@ -1529,41 +1529,41 @@ AdjustIntervalForTypmod(Interval *interval, int32 typmod,
Datum
make_interval(PG_FUNCTION_ARGS)
{
- int32 years = PG_GETARG_INT32(0);
- int32 months = PG_GETARG_INT32(1);
- int32 weeks = PG_GETARG_INT32(2);
- int32 days = PG_GETARG_INT32(3);
- int32 hours = PG_GETARG_INT32(4);
- int32 mins = PG_GETARG_INT32(5);
- double secs = PG_GETARG_FLOAT8(6);
+ int32 yearVal = PG_GETARG_INT32(0);
+ int32 monthVal = PG_GETARG_INT32(1);
+ int32 weekVal = PG_GETARG_INT32(2);
+ int32 dayVal = PG_GETARG_INT32(3);
+ int32 hourVal = PG_GETARG_INT32(4);
+ int32 minVal = PG_GETARG_INT32(5);
+ double secVal = PG_GETARG_FLOAT8(6);
Interval *result;
/*
* Reject out-of-range inputs. We reject any input values that cause
* integer overflow of the corresponding interval fields.
*/
- if (isinf(secs) || isnan(secs))
+ if (isinf(secVal) || isnan(secVal))
goto out_of_range;
result = (Interval *) palloc(sizeof(Interval));
/* years and months -> months */
- if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
- pg_add_s32_overflow(result->month, months, &result->month))
+ if (pg_mul_s32_overflow(yearVal, MONTHS_PER_YEAR, &result->month) ||
+ pg_add_s32_overflow(result->month, monthVal, &result->month))
goto out_of_range;
/* weeks and days -> days */
- if (pg_mul_s32_overflow(weeks, DAYS_PER_WEEK, &result->day) ||
- pg_add_s32_overflow(result->day, days, &result->day))
+ if (pg_mul_s32_overflow(weekVal, DAYS_PER_WEEK, &result->day) ||
+ pg_add_s32_overflow(result->day, dayVal, &result->day))
goto out_of_range;
/* hours and mins -> usecs (cannot overflow 64-bit) */
- result->time = hours * USECS_PER_HOUR + mins * USECS_PER_MINUTE;
+ result->time = hourVal * USECS_PER_HOUR + minVal * USECS_PER_MINUTE;
/* secs -> usecs */
- secs = rint(float8_mul(secs, USECS_PER_SEC));
- if (!FLOAT8_FITS_IN_INT64(secs) ||
- pg_add_s64_overflow(result->time, (int64) secs, &result->time))
+ secVal = rint(float8_mul(secVal, USECS_PER_SEC));
+ if (!FLOAT8_FITS_IN_INT64(secVal) ||
+ pg_add_s64_overflow(result->time, (int64) secVal, &result->time))
goto out_of_range;
/* make sure that the result is finite */
@@ -2131,9 +2131,9 @@ time2t(const int hour, const int min, const int sec, const fsec_t fsec)
}
static Timestamp
-dt2local(Timestamp dt, int timezone)
+dt2local(Timestamp dt, int tz)
{
- dt -= (timezone * USECS_PER_SEC);
+ dt -= (tz * USECS_PER_SEC);
return dt;
}
@@ -2524,20 +2524,20 @@ static inline INT128
interval_cmp_value(const Interval *interval)
{
INT128 span;
- int64 days;
+ int64 dayVal;
/*
* Combine the month and day fields into an integral number of days.
* Because the inputs are int32, int64 arithmetic suffices here.
*/
- days = interval->month * INT64CONST(30);
- days += interval->day;
+ dayVal = interval->month * INT64CONST(30);
+ dayVal += interval->day;
/* Widen time field to 128 bits */
span = int64_to_int128(interval->time);
/* Scale up days to microseconds, forming a 128-bit product */
- int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+ int128_add_int64_mul_int64(&span, dayVal, USECS_PER_DAY);
return span;
}
@@ -6222,7 +6222,7 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
{
Numeric result;
int64 secs_from_day_month;
- int64 val;
+ int64 value;
/*
* To do this calculation in integer arithmetic even though
@@ -6245,9 +6245,9 @@ interval_part_common(PG_FUNCTION_ARGS, bool retnumeric)
* numeric (slower). This overflow happens around 10^9 days, so
* not common in practice.
*/
- if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &val) &&
- !pg_add_s64_overflow(val, interval->time, &val))
- result = int64_div_fast_to_numeric(val, 6);
+ if (!pg_mul_s64_overflow(secs_from_day_month, 1000000, &value) &&
+ !pg_add_s64_overflow(value, interval->time, &value))
+ result = int64_div_fast_to_numeric(value, 6);
else
result =
numeric_add_safe(int64_div_fast_to_numeric(interval->time, 6),
@@ -6311,7 +6311,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
TimestampTz result;
int tz;
- char tzname[TZ_STRLEN_MAX + 1];
+ char tz_name[TZ_STRLEN_MAX + 1];
int type,
val;
pg_tz *tzp;
@@ -6324,9 +6324,9 @@ timestamp_zone(PG_FUNCTION_ARGS)
/*
* Look up the requested timezone.
*/
- text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+ text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
- type = DecodeTimezoneName(tzname, &val, &tzp);
+ type = DecodeTimezoneName(tz_name, &val, &tzp);
if (type == TZNAME_FIXED_OFFSET)
{
@@ -6341,7 +6341,7 @@ timestamp_zone(PG_FUNCTION_ARGS)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
- tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
+ tz = -DetermineTimeZoneAbbrevOffset(&tm, tz_name, tzp);
result = dt2local(timestamp, tz);
}
else
@@ -6566,7 +6566,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
Timestamp result;
int tz;
- char tzname[TZ_STRLEN_MAX + 1];
+ char tz_name[TZ_STRLEN_MAX + 1];
int type,
val;
pg_tz *tzp;
@@ -6577,9 +6577,9 @@ timestamptz_zone(PG_FUNCTION_ARGS)
/*
* Look up the requested timezone.
*/
- text_to_cstring_buffer(zone, tzname, sizeof(tzname));
+ text_to_cstring_buffer(zone, tz_name, sizeof(tz_name));
- type = DecodeTimezoneName(tzname, &val, &tzp);
+ type = DecodeTimezoneName(tz_name, &val, &tzp);
if (type == TZNAME_FIXED_OFFSET)
{
@@ -6592,7 +6592,7 @@ timestamptz_zone(PG_FUNCTION_ARGS)
/* dynamic-offset abbreviation, resolve using specified time */
int isdst;
- tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
+ tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tz_name, tzp, &isdst);
result = dt2local(timestamp, tz);
}
else
diff --git a/src/bin/initdb/findtimezone.c b/src/bin/initdb/findtimezone.c
index 2b2ae39adf3..97d55e19c13 100644
--- a/src/bin/initdb/findtimezone.c
+++ b/src/bin/initdb/findtimezone.c
@@ -231,7 +231,7 @@ compare_tm(struct tm *s, struct pg_tm *p)
* test time.
*/
static int
-score_timezone(const char *tzname, struct tztry *tt)
+score_timezone(const char *tz_name, struct tztry *tt)
{
int i;
pg_time_t pgtt;
@@ -241,7 +241,7 @@ score_timezone(const char *tzname, struct tztry *tt)
pg_tz *tz;
/* Load timezone definition */
- tz = pg_load_tz(tzname);
+ tz = pg_load_tz(tz_name);
if (!tz)
return -1; /* unrecognized zone name */
@@ -249,7 +249,7 @@ score_timezone(const char *tzname, struct tztry *tt)
if (!pg_tz_acceptable(tz))
{
#ifdef DEBUG_IDENTIFY_TIMEZONE
- fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
+ fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tz_name);
#endif
return -1;
}
@@ -266,7 +266,7 @@ score_timezone(const char *tzname, struct tztry *tt)
{
#ifdef DEBUG_IDENTIFY_TIMEZONE
fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
- tzname, i, (long) pgtt,
+ tz_name, i, (long) pgtt,
pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
pgtm->tm_isdst ? "dst" : "std");
@@ -277,7 +277,7 @@ score_timezone(const char *tzname, struct tztry *tt)
{
#ifdef DEBUG_IDENTIFY_TIMEZONE
fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
- tzname, i, (long) pgtt,
+ tz_name, i, (long) pgtt,
pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
pgtm->tm_isdst ? "dst" : "std",
@@ -298,7 +298,7 @@ score_timezone(const char *tzname, struct tztry *tt)
{
#ifdef DEBUG_IDENTIFY_TIMEZONE
fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
- tzname, i, (long) pgtt,
+ tz_name, i, (long) pgtt,
pgtm->tm_zone, cbuf);
#endif
return i;
@@ -307,7 +307,7 @@ score_timezone(const char *tzname, struct tztry *tt)
}
#ifdef DEBUG_IDENTIFY_TIMEZONE
- fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
+ fprintf(stderr, "TZ \"%s\" gets max score %d\n", tz_name, i);
#endif
return i;
@@ -317,9 +317,9 @@ score_timezone(const char *tzname, struct tztry *tt)
* Test whether given zone name is a perfect match to localtime() behavior
*/
static bool
-perfect_timezone_match(const char *tzname, struct tztry *tt)
+perfect_timezone_match(const char *tz_name, struct tztry *tt)
{
- return (score_timezone(tzname, tt) == tt->n_test_times);
+ return (score_timezone(tz_name, tt) == tt->n_test_times);
}
@@ -1725,14 +1725,14 @@ identify_system_timezone(void)
* Return true if the given zone name is valid and is an "acceptable" zone.
*/
static bool
-validate_zone(const char *tzname)
+validate_zone(const char *zone)
{
pg_tz *tz;
- if (!tzname || !tzname[0])
+ if (!zone || !zone[0])
return false;
- tz = pg_load_tz(tzname);
+ tz = pg_load_tz(zone);
if (!tz)
return false;
@@ -1756,7 +1756,7 @@ validate_zone(const char *tzname)
const char *
select_default_timezone(const char *share_path)
{
- const char *tzname;
+ const char *tz;
/* Initialize timezone directory path, if needed */
#ifndef SYSTEMTZDIR
@@ -1764,14 +1764,14 @@ select_default_timezone(const char *share_path)
#endif
/* Check TZ environment variable */
- tzname = getenv("TZ");
- if (validate_zone(tzname))
- return tzname;
+ tz = getenv("TZ");
+ if (validate_zone(tz))
+ return tz;
/* Nope, so try to identify the system timezone */
- tzname = identify_system_timezone();
- if (validate_zone(tzname))
- return tzname;
+ tz = identify_system_timezone();
+ if (validate_zone(tz))
+ return tz;
return NULL;
}
diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
index 504c0235ffb..a44bd230d80 100644
--- a/src/timezone/pgtz.c
+++ b/src/timezone/pgtz.c
@@ -231,7 +231,7 @@ init_timezone_hashtable(void)
* default timezone setting is later overridden from postgresql.conf.
*/
pg_tz *
-pg_tzset(const char *tzname)
+pg_tzset(const char *zone)
{
pg_tz_cache *tzp;
struct state tzstate;
@@ -239,7 +239,7 @@ pg_tzset(const char *tzname)
char canonname[TZ_STRLEN_MAX + 1];
char *p;
- if (strlen(tzname) > TZ_STRLEN_MAX)
+ if (strlen(zone) > TZ_STRLEN_MAX)
return NULL; /* not going to fit */
if (!timezone_cache)
@@ -253,8 +253,8 @@ pg_tzset(const char *tzname)
* a POSIX-style timezone spec.)
*/
p = uppername;
- while (*tzname)
- *p++ = pg_toupper((unsigned char) *tzname++);
+ while (*zone)
+ *p++ = pg_toupper((unsigned char) *zone++);
*p = '\0';
tzp = (pg_tz_cache *) hash_search(timezone_cache,
@@ -321,7 +321,7 @@ pg_tzset_offset(long gmtoffset)
{
long absoffset = (gmtoffset < 0) ? -gmtoffset : gmtoffset;
char offsetstr[64];
- char tzname[128];
+ char zone[128];
snprintf(offsetstr, sizeof(offsetstr),
"%02ld", absoffset / SECS_PER_HOUR);
@@ -338,13 +338,13 @@ pg_tzset_offset(long gmtoffset)
":%02ld", absoffset);
}
if (gmtoffset > 0)
- snprintf(tzname, sizeof(tzname), "<-%s>+%s",
+ snprintf(zone, sizeof(zone), "<-%s>+%s",
offsetstr, offsetstr);
else
- snprintf(tzname, sizeof(tzname), "<+%s>-%s",
+ snprintf(zone, sizeof(zone), "<+%s>-%s",
offsetstr, offsetstr);
- return pg_tzset(tzname);
+ return pg_tzset(zone);
}
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch (2.5K, 14-v4-0012-cleanup-avoid-local-variables-shadowed-by-globals.patch)
download | inline diff:
From 4d911f497f6596a73664216d4ca59145432493c3 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Wed, 3 Dec 2025 07:40:26 +0800
Subject: [PATCH v4 12/13] cleanup: avoid local variables shadowed by globals
in ecpg.header
This commit renames local variables in ecpg.header that were shadowed by
global identifiers of the same names. The updated local names ensure the
identifiers remain distinct and unambiguous within the file.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/interfaces/ecpg/preproc/ecpg.header | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index dde69a39695..a58dda32f48 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -178,7 +178,7 @@ create_questionmarks(const char *name, bool array)
}
static char *
-adjust_outofscope_cursor_vars(struct cursor *cur)
+adjust_outofscope_cursor_vars(struct cursor *pcur)
{
/*
* Informix accepts DECLARE with variables that are out of scope when OPEN
@@ -203,7 +203,7 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
struct variable *newvar,
*newind;
- list = (insert ? cur->argsinsert : cur->argsresult);
+ list = (insert ? pcur->argsinsert : pcur->argsresult);
for (ptr = list; ptr != NULL; ptr = ptr->next)
{
@@ -434,9 +434,9 @@ adjust_outofscope_cursor_vars(struct cursor *cur)
}
if (insert)
- cur->argsinsert_oos = newlist;
+ pcur->argsinsert_oos = newlist;
else
- cur->argsresult_oos = newlist;
+ pcur->argsresult_oos = newlist;
}
return result;
@@ -490,7 +490,7 @@ static void
add_typedef(const char *name, const char *dimension, const char *length,
enum ECPGttype type_enum,
const char *type_dimension, const char *type_index,
- int initializer, int array)
+ int initial_value, int array)
{
/* add entry to list */
struct typedefs *ptr,
@@ -498,7 +498,7 @@ add_typedef(const char *name, const char *dimension, const char *length,
if ((type_enum == ECPGt_struct ||
type_enum == ECPGt_union) &&
- initializer == 1)
+ initial_value == 1)
mmerror(PARSE_ERROR, ET_ERROR, "initializer not allowed in type definition");
else if (INFORMIX_MODE && strcmp(name, "string") == 0)
mmerror(PARSE_ERROR, ET_ERROR, "type name \"string\" is reserved in Informix mode");
--
2.39.5 (Apple Git-154)
[application/octet-stream] v4-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch (30.4K, 15-v4-0011-cleanup-rename-local-conn-variables-to-avoid-shad.patch)
download | inline diff:
From 7c7f53340bec5147a7b0e896c2ee649c73c75206 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <[email protected]>
Date: Tue, 2 Dec 2025 16:03:19 +0800
Subject: [PATCH v4 11/13] cleanup: rename local conn variables to avoid
shadowing the global
This commit renames all local variables named 'conn' to 'myconn' to avoid
shadowing the global connection variable. This ensures the local and
global identifiers remain clearly distinct within each scope.
A few additional shadowing fixes in the same code areas are included as
well. These are unrelated to the conn renaming but occur in the same
files, so they are bundled here to keep the commit self-contained.
Author: Chao Li <[email protected]>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
src/bin/pg_basebackup/pg_basebackup.c | 32 ++++----
src/bin/pg_basebackup/pg_recvlogical.c | 24 +++---
src/bin/pg_basebackup/receivelog.c | 108 ++++++++++++-------------
src/bin/pg_basebackup/streamutil.c | 58 ++++++-------
4 files changed, 111 insertions(+), 111 deletions(-)
diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 0a3ca4315de..5a57c64dcd1 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -1013,16 +1013,16 @@ backup_parse_compress_options(char *option, char **algorithm, char **detail,
* chunk.
*/
static void
-ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
+ReceiveCopyData(PGconn *myconn, WriteDataCallback callback,
void *callback_data)
{
PGresult *res;
/* Get the COPY data stream. */
- res = PQgetResult(conn);
+ res = PQgetResult(myconn);
if (PQresultStatus(res) != PGRES_COPY_OUT)
pg_fatal("could not get COPY data stream: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
PQclear(res);
/* Loop over chunks until done. */
@@ -1031,7 +1031,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
int r;
char *copybuf;
- r = PQgetCopyData(conn, ©buf, 0);
+ r = PQgetCopyData(myconn, ©buf, 0);
if (r == -1)
{
/* End of chunk. */
@@ -1039,7 +1039,7 @@ ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
}
else if (r == -2)
pg_fatal("could not read COPY data: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
if (bgchild_exited)
pg_fatal("background process terminated unexpectedly");
@@ -1283,7 +1283,7 @@ CreateBackupStreamer(char *archive_name, char *spclocation,
* manifest if present - as a single COPY stream.
*/
static void
-ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
+ReceiveArchiveStream(PGconn *myconn, pg_compress_specification *compress)
{
ArchiveStreamState state;
@@ -1293,7 +1293,7 @@ ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
state.compress = compress;
/* All the real work happens in ReceiveArchiveStreamChunk. */
- ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
+ ReceiveCopyData(myconn, ReceiveArchiveStreamChunk, &state);
/* If we wrote the backup manifest to a file, close the file. */
if (state.manifest_file !=NULL)
@@ -1598,7 +1598,7 @@ ReportCopyDataParseError(size_t r, char *copybuf)
* receive the backup manifest and inject it into that tarfile.
*/
static void
-ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
+ReceiveTarFile(PGconn *myconn, char *archive_name, char *spclocation,
bool tablespacenum, pg_compress_specification *compress)
{
WriteTarState state;
@@ -1609,16 +1609,16 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
/* Pass all COPY data through to the backup streamer. */
memset(&state, 0, sizeof(state));
is_recovery_guc_supported =
- PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
+ PQserverVersion(myconn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
expect_unterminated_tarfile =
- PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
+ PQserverVersion(myconn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
state.streamer = CreateBackupStreamer(archive_name, spclocation,
&manifest_inject_streamer,
is_recovery_guc_supported,
expect_unterminated_tarfile,
compress);
state.tablespacenum = tablespacenum;
- ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
+ ReceiveCopyData(myconn, ReceiveTarCopyChunk, &state);
progress_update_filename(NULL);
/*
@@ -1633,7 +1633,7 @@ ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
/* Slurp the entire backup manifest into a buffer. */
initPQExpBuffer(&buf);
- ReceiveBackupManifestInMemory(conn, &buf);
+ ReceiveBackupManifestInMemory(myconn, &buf);
if (PQExpBufferDataBroken(buf))
pg_fatal("out of memory");
@@ -1697,7 +1697,7 @@ get_tablespace_mapping(const char *dir)
* Receive the backup manifest file and write it out to a file.
*/
static void
-ReceiveBackupManifest(PGconn *conn)
+ReceiveBackupManifest(PGconn *myconn)
{
WriteManifestState state;
@@ -1707,7 +1707,7 @@ ReceiveBackupManifest(PGconn *conn)
if (state.file == NULL)
pg_fatal("could not create file \"%s\": %m", state.filename);
- ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
+ ReceiveCopyData(myconn, ReceiveBackupManifestChunk, &state);
fclose(state.file);
}
@@ -1734,9 +1734,9 @@ ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
* Receive the backup manifest file and write it out to a file.
*/
static void
-ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
+ReceiveBackupManifestInMemory(PGconn *myconn, PQExpBuffer buf)
{
- ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
+ ReceiveCopyData(myconn, ReceiveBackupManifestInMemoryChunk, buf);
}
/*
diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 14ad1504678..7801623fec9 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -73,8 +73,8 @@ static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
static void usage(void);
static void StreamLogicalLog(void);
-static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
-static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
+static bool flushAndSendFeedback(PGconn *myconn, TimestampTz *now);
+static void prepareToTerminate(PGconn *myconn, XLogRecPtr endpos,
StreamStopReason reason,
XLogRecPtr lsn);
@@ -126,7 +126,7 @@ usage(void)
* Send a Standby Status Update message to server.
*/
static bool
-sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
+sendFeedback(PGconn *myconn, TimestampTz now, bool force, bool replyRequested)
{
static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
@@ -167,10 +167,10 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
last_written_lsn = output_written_lsn;
last_fsync_lsn = output_fsync_lsn;
- if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+ if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
{
pg_log_error("could not send feedback packet: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
return false;
}
@@ -1045,13 +1045,13 @@ main(int argc, char **argv)
* feedback.
*/
static bool
-flushAndSendFeedback(PGconn *conn, TimestampTz *now)
+flushAndSendFeedback(PGconn *myconn, TimestampTz *now)
{
/* flush data to disk, so that we send a recent flush pointer */
if (!OutputFsync(*now))
return false;
*now = feGetCurrentTimestamp();
- if (!sendFeedback(conn, *now, true, false))
+ if (!sendFeedback(myconn, *now, true, false))
return false;
return true;
@@ -1062,11 +1062,11 @@ flushAndSendFeedback(PGconn *conn, TimestampTz *now)
* retry on failure.
*/
static void
-prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
+prepareToTerminate(PGconn *myconn, XLogRecPtr end_pos, StreamStopReason reason,
XLogRecPtr lsn)
{
- (void) PQputCopyEnd(conn, NULL);
- (void) PQflush(conn);
+ (void) PQputCopyEnd(myconn, NULL);
+ (void) PQflush(myconn);
if (verbose)
{
@@ -1077,12 +1077,12 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
break;
case STREAM_STOP_KEEPALIVE:
pg_log_info("end position %X/%08X reached by keepalive",
- LSN_FORMAT_ARGS(endpos));
+ LSN_FORMAT_ARGS(end_pos));
break;
case STREAM_STOP_END_OF_WAL:
Assert(XLogRecPtrIsValid(lsn));
pg_log_info("end position %X/%08X reached by WAL record at %X/%08X",
- LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
+ LSN_FORMAT_ARGS(end_pos), LSN_FORMAT_ARGS(lsn));
break;
case STREAM_STOP_NONE:
Assert(false);
diff --git a/src/bin/pg_basebackup/receivelog.c b/src/bin/pg_basebackup/receivelog.c
index 25b13c7f55c..9ec1eee088b 100644
--- a/src/bin/pg_basebackup/receivelog.c
+++ b/src/bin/pg_basebackup/receivelog.c
@@ -32,18 +32,18 @@ static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
static bool still_sending = true; /* feedback still needs to be sent? */
-static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
+static PGresult *HandleCopyStream(PGconn *myconn, StreamCtl *stream,
XLogRecPtr *stoppos);
-static int CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
-static int CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
+static int CopyStreamPoll(PGconn *myconn, long timeout_ms, pgsocket stop_socket);
+static int CopyStreamReceive(PGconn *myconn, long timeout, pgsocket stop_socket,
char **buffer);
-static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
+static bool ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf,
int len, XLogRecPtr blockpos, TimestampTz *last_status);
-static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+static bool ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
XLogRecPtr *blockpos);
-static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+static PGresult *HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
XLogRecPtr blockpos, XLogRecPtr *stoppos);
-static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
+static bool CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos);
static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
TimestampTz last_status);
@@ -334,7 +334,7 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
* Send a Standby Status Update message to server.
*/
static bool
-sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
+sendFeedback(PGconn *myconn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
{
char replybuf[1 + 8 + 8 + 8 + 8 + 1];
int len = 0;
@@ -355,10 +355,10 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
len += 1;
- if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
+ if (PQputCopyData(myconn, replybuf, len) <= 0 || PQflush(myconn))
{
pg_log_error("could not send feedback packet: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
return false;
}
@@ -372,7 +372,7 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
* If it's not, an error message is printed to stderr, and false is returned.
*/
bool
-CheckServerVersionForStreaming(PGconn *conn)
+CheckServerVersionForStreaming(PGconn *myconn)
{
int minServerMajor,
maxServerMajor;
@@ -386,10 +386,10 @@ CheckServerVersionForStreaming(PGconn *conn)
*/
minServerMajor = 903;
maxServerMajor = PG_VERSION_NUM / 100;
- serverMajor = PQserverVersion(conn) / 100;
+ serverMajor = PQserverVersion(myconn) / 100;
if (serverMajor < minServerMajor)
{
- const char *serverver = PQparameterStatus(conn, "server_version");
+ const char *serverver = PQparameterStatus(myconn, "server_version");
pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
serverver ? serverver : "'unknown'",
@@ -398,7 +398,7 @@ CheckServerVersionForStreaming(PGconn *conn)
}
else if (serverMajor > maxServerMajor)
{
- const char *serverver = PQparameterStatus(conn, "server_version");
+ const char *serverver = PQparameterStatus(myconn, "server_version");
pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
serverver ? serverver : "'unknown'",
@@ -450,7 +450,7 @@ CheckServerVersionForStreaming(PGconn *conn)
* Note: The WAL location *must* be at a log segment start!
*/
bool
-ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
+ReceiveXlogStream(PGconn *myconn, StreamCtl *stream)
{
char query[128];
char slotcmd[128];
@@ -461,7 +461,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
* The caller should've checked the server version already, but doesn't do
* any harm to check it here too.
*/
- if (!CheckServerVersionForStreaming(conn))
+ if (!CheckServerVersionForStreaming(myconn))
return false;
/*
@@ -497,7 +497,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
/*
* Get the server system identifier and timeline, and validate them.
*/
- if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
+ if (!RunIdentifySystem(myconn, &sysidentifier, &servertli, NULL, NULL))
{
pg_free(sysidentifier);
return false;
@@ -536,7 +536,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
if (!existsTimeLineHistoryFile(stream))
{
snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
- res = PQexec(conn, query);
+ res = PQexec(myconn, query);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
/* FIXME: we might send it ok, but get an error */
@@ -576,7 +576,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
slotcmd,
LSN_FORMAT_ARGS(stream->startpos),
stream->timeline);
- res = PQexec(conn, query);
+ res = PQexec(myconn, query);
if (PQresultStatus(res) != PGRES_COPY_BOTH)
{
pg_log_error("could not send replication command \"%s\": %s",
@@ -587,7 +587,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
PQclear(res);
/* Stream the WAL */
- res = HandleCopyStream(conn, stream, &stoppos);
+ res = HandleCopyStream(myconn, stream, &stoppos);
if (res == NULL)
goto error;
@@ -636,7 +636,7 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
}
/* Read the final result, which should be CommandComplete. */
- res = PQgetResult(conn);
+ res = PQgetResult(myconn);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
pg_log_error("unexpected termination of replication stream: %s",
@@ -742,7 +742,7 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
* On any other sort of error, returns NULL.
*/
static PGresult *
-HandleCopyStream(PGconn *conn, StreamCtl *stream,
+HandleCopyStream(PGconn *myconn, StreamCtl *stream,
XLogRecPtr *stoppos)
{
char *copybuf = NULL;
@@ -760,7 +760,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
/*
* Check if we should continue streaming, or abort at this point.
*/
- if (!CheckCopyStreamStop(conn, stream, blockpos))
+ if (!CheckCopyStreamStop(myconn, stream, blockpos))
goto error;
now = feGetCurrentTimestamp();
@@ -780,7 +780,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
* Send feedback so that the server sees the latest WAL locations
* immediately.
*/
- if (!sendFeedback(conn, blockpos, now, false))
+ if (!sendFeedback(myconn, blockpos, now, false))
goto error;
last_status = now;
}
@@ -793,7 +793,7 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
stream->standby_message_timeout))
{
/* Time to send feedback! */
- if (!sendFeedback(conn, blockpos, now, false))
+ if (!sendFeedback(myconn, blockpos, now, false))
goto error;
last_status = now;
}
@@ -808,14 +808,14 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
PQfreemem(copybuf);
copybuf = NULL;
- r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, ©buf);
+ r = CopyStreamReceive(myconn, sleeptime, stream->stop_socket, ©buf);
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, ©buf);
+ r = CopyStreamReceive(myconn, 0, stream->stop_socket, ©buf);
}
}
@@ -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, ©buf, 1);
+ rawlen = PQgetCopyData(myconn, ©buf, 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, ©buf, 1);
+ rawlen = PQgetCopyData(myconn, ©buf, 1);
if (rawlen == 0)
return 0;
}
@@ -978,7 +978,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
return -2;
if (rawlen == -2)
{
- pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
+ pg_log_error("could not read COPY data: %s", PQerrorMessage(myconn));
return -1;
}
@@ -991,7 +991,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
* Process the keepalive message.
*/
static bool
-ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessKeepaliveMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
XLogRecPtr blockpos, TimestampTz *last_status)
{
int pos;
@@ -1033,7 +1033,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
}
now = feGetCurrentTimestamp();
- if (!sendFeedback(conn, blockpos, now, false))
+ if (!sendFeedback(myconn, blockpos, now, false))
return false;
*last_status = now;
}
@@ -1045,7 +1045,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
* Process WALData message.
*/
static bool
-ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
+ProcessWALDataMsg(PGconn *myconn, StreamCtl *stream, char *copybuf, int len,
XLogRecPtr *blockpos)
{
int xlogoff;
@@ -1156,10 +1156,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
{
- if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+ if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
{
pg_log_error("could not send copy-end packet: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
return false;
}
still_sending = false;
@@ -1176,10 +1176,10 @@ ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
* Handle end of the copy stream.
*/
static PGresult *
-HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
+HandleEndOfCopyStream(PGconn *myconn, StreamCtl *stream, char *copybuf,
XLogRecPtr blockpos, XLogRecPtr *stoppos)
{
- PGresult *res = PQgetResult(conn);
+ PGresult *res = PQgetResult(myconn);
/*
* The server closed its end of the copy stream. If we haven't closed
@@ -1196,14 +1196,14 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
}
if (PQresultStatus(res) == PGRES_COPY_IN)
{
- if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+ if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
{
pg_log_error("could not send copy-end packet: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
PQclear(res);
return NULL;
}
- res = PQgetResult(conn);
+ res = PQgetResult(myconn);
}
still_sending = false;
}
@@ -1215,7 +1215,7 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
* Check if we should continue streaming, or abort at this point.
*/
static bool
-CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
+CheckCopyStreamStop(PGconn *myconn, StreamCtl *stream, XLogRecPtr blockpos)
{
if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
{
@@ -1224,10 +1224,10 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
/* Potential error message is written by close_walfile */
return false;
}
- if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
+ if (PQputCopyEnd(myconn, NULL) <= 0 || PQflush(myconn))
{
pg_log_error("could not send copy-end packet: %s",
- PQerrorMessage(conn));
+ PQerrorMessage(myconn));
return false;
}
still_sending = false;
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index e5a7cb6e5b1..342ad2cbd4f 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -31,7 +31,7 @@
int WalSegSz;
-static bool RetrieveDataDirCreatePerm(PGconn *conn);
+static bool RetrieveDataDirCreatePerm(PGconn *myconn);
/* SHOW command for replication connection was introduced in version 10 */
#define MINIMUM_VERSION_FOR_SHOW_CMD 100000
@@ -273,7 +273,7 @@ GetConnection(void)
* since ControlFile is not accessible here.
*/
bool
-RetrieveWalSegSize(PGconn *conn)
+RetrieveWalSegSize(PGconn *myconn)
{
PGresult *res;
char xlog_unit[3];
@@ -281,20 +281,20 @@ RetrieveWalSegSize(PGconn *conn)
multiplier = 1;
/* check connection existence */
- Assert(conn != NULL);
+ Assert(myconn != NULL);
/* for previous versions set the default xlog seg size */
- if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
+ if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_SHOW_CMD)
{
WalSegSz = DEFAULT_XLOG_SEG_SIZE;
return true;
}
- res = PQexec(conn, "SHOW wal_segment_size");
+ res = PQexec(myconn, "SHOW wal_segment_size");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
pg_log_error("could not send replication command \"%s\": %s",
- "SHOW wal_segment_size", PQerrorMessage(conn));
+ "SHOW wal_segment_size", PQerrorMessage(myconn));
PQclear(res);
return false;
@@ -352,23 +352,23 @@ RetrieveWalSegSize(PGconn *conn)
* on the data directory.
*/
static bool
-RetrieveDataDirCreatePerm(PGconn *conn)
+RetrieveDataDirCreatePerm(PGconn *myconn)
{
PGresult *res;
int data_directory_mode;
/* check connection existence */
- Assert(conn != NULL);
+ Assert(myconn != NULL);
/* for previous versions leave the default group access */
- if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
+ if (PQserverVersion(myconn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
return true;
- res = PQexec(conn, "SHOW data_directory_mode");
+ res = PQexec(myconn, "SHOW data_directory_mode");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
pg_log_error("could not send replication command \"%s\": %s",
- "SHOW data_directory_mode", PQerrorMessage(conn));
+ "SHOW data_directory_mode", PQerrorMessage(myconn));
PQclear(res);
return false;
@@ -406,7 +406,7 @@ RetrieveDataDirCreatePerm(PGconn *conn)
* - Database name (NULL in servers prior to 9.4)
*/
bool
-RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
+RunIdentifySystem(PGconn *myconn, char **sysid, TimeLineID *starttli,
XLogRecPtr *startpos, char **db_name)
{
PGresult *res;
@@ -414,13 +414,13 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
lo;
/* Check connection existence */
- Assert(conn != NULL);
+ Assert(myconn != NULL);
- res = PQexec(conn, "IDENTIFY_SYSTEM");
+ res = PQexec(myconn, "IDENTIFY_SYSTEM");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
pg_log_error("could not send replication command \"%s\": %s",
- "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+ "IDENTIFY_SYSTEM", PQerrorMessage(myconn));
PQclear(res);
return false;
@@ -460,7 +460,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
if (db_name != NULL)
{
*db_name = NULL;
- if (PQserverVersion(conn) >= 90400)
+ if (PQserverVersion(myconn) >= 90400)
{
if (PQnfields(res) < 4)
{
@@ -487,7 +487,7 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
* Returns false on failure, and true otherwise.
*/
bool
-GetSlotInformation(PGconn *conn, const char *slot_name,
+GetSlotInformation(PGconn *myconn, const char *slot_name,
XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
{
PGresult *res;
@@ -502,13 +502,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
query = createPQExpBuffer();
appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
- res = PQexec(conn, query->data);
+ res = PQexec(myconn, query->data);
destroyPQExpBuffer(query);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
pg_log_error("could not send replication command \"%s\": %s",
- "READ_REPLICATION_SLOT", PQerrorMessage(conn));
+ "READ_REPLICATION_SLOT", PQerrorMessage(myconn));
PQclear(res);
return false;
}
@@ -581,13 +581,13 @@ GetSlotInformation(PGconn *conn, const char *slot_name,
* returns true in case of success.
*/
bool
-CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
+CreateReplicationSlot(PGconn *myconn, const char *slot_name, const char *plugin,
bool is_temporary, bool is_physical, bool reserve_wal,
bool slot_exists_ok, bool two_phase, bool failover)
{
PQExpBuffer query;
PGresult *res;
- bool use_new_option_syntax = (PQserverVersion(conn) >= 150000);
+ bool use_new_option_syntax = (PQserverVersion(myconn) >= 150000);
query = createPQExpBuffer();
@@ -617,15 +617,15 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
}
else
{
- if (failover && PQserverVersion(conn) >= 170000)
+ if (failover && PQserverVersion(myconn) >= 170000)
AppendPlainCommandOption(query, use_new_option_syntax,
"FAILOVER");
- if (two_phase && PQserverVersion(conn) >= 150000)
+ if (two_phase && PQserverVersion(myconn) >= 150000)
AppendPlainCommandOption(query, use_new_option_syntax,
"TWO_PHASE");
- if (PQserverVersion(conn) >= 100000)
+ if (PQserverVersion(myconn) >= 100000)
{
/* pg_recvlogical doesn't use an exported snapshot, so suppress */
if (use_new_option_syntax)
@@ -649,7 +649,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
}
/* Now run the query */
- res = PQexec(conn, query->data);
+ res = PQexec(myconn, query->data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
@@ -665,7 +665,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
else
{
pg_log_error("could not send replication command \"%s\": %s",
- query->data, PQerrorMessage(conn));
+ query->data, PQerrorMessage(myconn));
destroyPQExpBuffer(query);
PQclear(res);
@@ -694,7 +694,7 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
* returns true in case of success.
*/
bool
-DropReplicationSlot(PGconn *conn, const char *slot_name)
+DropReplicationSlot(PGconn *myconn, const char *slot_name)
{
PQExpBuffer query;
PGresult *res;
@@ -706,11 +706,11 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
/* Build query */
appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
slot_name);
- res = PQexec(conn, query->data);
+ res = PQexec(myconn, query->data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
pg_log_error("could not send replication command \"%s\": %s",
- query->data, PQerrorMessage(conn));
+ query->data, PQerrorMessage(myconn));
destroyPQExpBuffer(query);
PQclear(res);
--
2.39.5 (Apple Git-154)
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], [email protected]
Subject: Re: Cleanup shadows variable warnings, round 1
In-Reply-To: <CAEoWx2mgTMAvXDi0AZVMeKys0owGa5tdQUJ0gonAjsdBOYMNkg@mail.gmail.com>
* 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