Skip to content

Commit 785b8d6

Browse files
committed
Fix handling of pg_stat_statements.stat temporary file
Write the file to a temporary name and then rename() it into the permanent name, to ensure it can't end up half-written and corrupt in case of a crash during shutdown. Unlink the file after it has been read so it's removed from the data directory and not included in base backups going to replication slaves.
1 parent 2ce097e commit 785b8d6

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

contrib/pg_stat_statements/pg_stat_statements.c

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,13 @@ pgss_shmem_startup(void)
418418

419419
pfree(buffer);
420420
FreeFile(file);
421+
422+
/*
423+
* Remove the file so it's not included in backups/replication
424+
* slaves, etc. A new file will be written on next shutdown.
425+
*/
426+
unlink(PGSS_DUMP_FILE);
427+
421428
return;
422429

423430
error:
@@ -459,7 +466,7 @@ pgss_shmem_shutdown(int code, Datum arg)
459466
if (!pgss_save)
460467
return;
461468

462-
file = AllocateFile(PGSS_DUMP_FILE, PG_BINARY_W);
469+
file = AllocateFile(PGSS_DUMP_FILE ".tmp", PG_BINARY_W);
463470
if (file == NULL)
464471
goto error;
465472

@@ -485,16 +492,25 @@ pgss_shmem_shutdown(int code, Datum arg)
485492
goto error;
486493
}
487494

495+
/*
496+
* Rename file into place, so we atomically replace the old one.
497+
*/
498+
if (rename(PGSS_DUMP_FILE ".tmp", PGSS_DUMP_FILE) != 0)
499+
ereport(LOG,
500+
(errcode_for_file_access(),
501+
errmsg("could not rename pg_stat_statement file \"%s\": %m",
502+
PGSS_DUMP_FILE ".tmp")));
503+
488504
return;
489505

490506
error:
491507
ereport(LOG,
492508
(errcode_for_file_access(),
493509
errmsg("could not write pg_stat_statement file \"%s\": %m",
494-
PGSS_DUMP_FILE)));
510+
PGSS_DUMP_FILE ".tmp")));
495511
if (file)
496512
FreeFile(file);
497-
unlink(PGSS_DUMP_FILE);
513+
unlink(PGSS_DUMP_FILE ".tmp");
498514
}
499515

500516
/*

0 commit comments

Comments
 (0)