From 933a7b90cf4813342e3dc5fe8b6ac1b1aa93c44a Mon Sep 17 00:00:00 2001 From: Colin McDonnell Date: Wed, 18 Nov 2026 10:46:37 -0800 Subject: [PATCH v1] Report each commit's WAL position to the client A client that writes on a primary and reads from a streaming standby can see its own writes there by running WAIT FOR LSN on the standby with an LSN at or after the end of its transaction's commit record. Today the only way to get one is another query after the commit, usually pg_current_wal_insert_lsn(), which also covers everyone else's WAL. Add last_commit_lsn, a read-only setting that shows the end of the commit record of the session's most recent commit, and report_commit_lsn, which makes the server send last_commit_lsn in a ParameterStatus message whenever it has changed, just before ReadyForQuery. The response to the command that commits then carries the LSN of that commit rather than the current end of WAL, with no extra statement. report_commit_lsn is off by default, so other clients see no new messages, and last_commit_lsn is not GUC_REPORT. No message format changes. The protocol already allows ParameterStatus at any time and tells frontends to ignore parameters they don't know. last_commit_lsn moves only when a commit record is written: by COMMIT of a transaction with an XID, and by COMMIT PREPARED. Read-only transactions, rollbacks, PREPARE TRANSACTION and transactions that wrote WAL without an XID leave it alone. That is why it has its own variable rather than using XactLastCommitEnd, which also advances in the last case. Parallel workers get the leader's value, so last_commit_lsn reads the same in a parallel query. --- doc/src/sgml/config.sgml | 48 +++++++ doc/src/sgml/high-availability.sgml | 10 ++ doc/src/sgml/libpq.sgml | 3 + doc/src/sgml/protocol.sgml | 3 + doc/src/sgml/ref/wait.sgml | 5 +- src/backend/access/transam/parallel.c | 5 + src/backend/access/transam/twophase.c | 2 +- src/backend/access/transam/xact.c | 24 ++++ src/backend/utils/misc/guc.c | 17 +++ src/backend/utils/misc/guc_parameters.dat | 15 +++ src/backend/utils/misc/guc_tables.c | 1 + src/include/access/xact.h | 4 + src/include/utils/guc_hooks.h | 1 + .../modules/libpq_pipeline/libpq_pipeline.c | 122 ++++++++++++++++++ src/test/recovery/meson.build | 1 + src/test/recovery/t/062_last_commit_lsn.pl | 94 ++++++++++++++ src/test/regress/expected/transactions.out | 56 ++++++++ src/test/regress/sql/transactions.sql | 26 ++++ 18 files changed, 435 insertions(+), 2 deletions(-) create mode 100644 src/test/recovery/t/062_last_commit_lsn.pl diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 886e8c4484..e2e3289054 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -10790,6 +10790,30 @@ COPY postgres_log FROM '/full/path/to/logfile.csv' WITH csv; + + report_commit_lsn (boolean) + + report_commit_lsn configuration parameter + + + + + When on, the server reports the value of + to the client whenever it has + changed, in a ParameterStatus message sent just before the server + next reports that it is ready for a query + (see ). A client can then wait for + that LSN with before + reading the committed changes on a standby server, without asking + the primary for a WAL position + (see ). In the + extended query protocol, the report comes at the next Sync, so a + pipeline that commits several times before a Sync reports only the + last commit. The default is off. + + + + session_replication_role (enum) @@ -12548,6 +12572,30 @@ dynamic_library_path = '/usr/local/lib/postgresql:$libdir' + + last_commit_lsn (string) + + last_commit_lsn configuration parameter + + + + + Reports the end of the commit record of the most recent transaction + committed in the current session, as a pg_lsn value, or + 0/00000000 if there is none. Once a standby + server has replayed the WAL up to this position, + queries there that take their snapshot afterwards see that + transaction's changes. A transaction that was not + assigned a transaction ID (see ) + writes no commit record, and leaves this unchanged, as do + transactions that roll back and PREPARE + TRANSACTION; COMMIT PREPARED sets it. + See to have it reported to + the client after each commit. + + + + max_function_args (integer) diff --git a/doc/src/sgml/high-availability.sgml b/doc/src/sgml/high-availability.sgml index 6e42e0eda4..f94340923c 100644 --- a/doc/src/sgml/high-availability.sgml +++ b/doc/src/sgml/high-availability.sgml @@ -1422,6 +1422,16 @@ postgres=# SELECT pg_current_wal_insert_lsn(); + + Alternatively, the application can use the session's + , the end of its most recent commit + record. If is on, the server + reports it to the client after each commit, before it is ready for the + next query, so no further query is needed; + libpq applications can read it with + . + + The LSN obtained from the primary is then communicated to the standby server. This can be managed at the application level or diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index b213a266cb..999bcaaca3 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2892,6 +2892,9 @@ const char *PQparameterStatus(const PGconn *conn, const char *paramName); 14; scram_iterations was not reported by releases before 16; search_path was not reported by releases before 18.) + last_commit_lsn is also reported, after each + commit, if is on; releases + before 20 do not have it. Note that server_version and server_encoding diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 541673eb28..53cf9af572 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -1548,6 +1548,9 @@ SELCT 1/0; 14; scram_iterations was not reported by releases before 16; search_path was not reported by releases before 18.) + last_commit_lsn is also reported, after each commit, + if is on; releases before 20 do + not have it. Note that server_version, server_encoding and diff --git a/doc/src/sgml/ref/wait.sgml b/doc/src/sgml/ref/wait.sgml index 2917309c0d..4c67f8dcf4 100644 --- a/doc/src/sgml/ref/wait.sgml +++ b/doc/src/sgml/ref/wait.sgml @@ -330,7 +330,10 @@ WAIT FOR LSN 'lsn' primary_flush mode waits for WAL to be flushed on a primary server. In all cases, the LSN of the last modification should be stored on the client application side or the - connection pooler side. + connection pooler side. The session's + is the end of its most recent COMMIT record, and with + on, the server sends it to the + client after each commit. diff --git a/src/backend/access/transam/parallel.c b/src/backend/access/transam/parallel.c index b51df2a460..e67ceb595d 100644 --- a/src/backend/access/transam/parallel.c +++ b/src/backend/access/transam/parallel.c @@ -98,6 +98,7 @@ typedef struct FixedParallelState ProcNumber parallel_leader_proc_number; TimestampTz xact_ts; TimestampTz stmt_ts; + XLogRecPtr last_commit_record_end; SerializableXactHandle serializable_xact_handle; /* Maximum XactLastRecEnd of any worker. */ @@ -353,6 +354,7 @@ InitializeParallelDSM(ParallelContext *pcxt) fps->parallel_leader_proc_number = MyProcNumber; fps->xact_ts = GetCurrentTransactionStartTimestamp(); fps->stmt_ts = GetCurrentStatementStartTimestamp(); + fps->last_commit_record_end = XactLastCommitRecordEnd; fps->serializable_xact_handle = ShareSerializableXact(); pg_atomic_init_u64(&fps->last_xlog_end, InvalidXLogRecPtr); shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps); @@ -1417,6 +1419,9 @@ ParallelWorkerMain(Datum main_arg) */ SetParallelStartTimestamps(fps->xact_ts, fps->stmt_ts); + /* Show the leader's last_commit_lsn. */ + XactLastCommitRecordEnd = fps->last_commit_record_end; + /* * Identify the entry point to be called. In theory this could result in * loading an additional library, though most likely the entry point is in diff --git a/src/backend/access/transam/twophase.c b/src/backend/access/transam/twophase.c index d89afb0932..87ea9564f6 100644 --- a/src/backend/access/transam/twophase.c +++ b/src/backend/access/transam/twophase.c @@ -2416,7 +2416,7 @@ RecordTransactionCommitPrepared(TransactionId xid, initfileinval, MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, xid, gid); - + XactLastCommitRecordEnd = recptr; if (replorigin) /* Move LSNs forward for this replication origin */ diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index d8d91bed42..4e1d5e1a55 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -65,6 +65,7 @@ #include "utils/builtins.h" #include "utils/combocid.h" #include "utils/guc.h" +#include "utils/guc_hooks.h" #include "utils/injection_point.h" #include "utils/inval.h" #include "utils/memutils.h" @@ -89,6 +90,15 @@ bool XactDeferrable; int synchronous_commit = SYNCHRONOUS_COMMIT_ON; +bool report_commit_lsn = false; + +/* + * End of the commit record of the most recent transaction this session + * committed, shown as last_commit_lsn. Unlike XactLastCommitEnd, this + * doesn't advance for transactions that wrote WAL but no commit record. + */ +XLogRecPtr XactLastCommitRecordEnd = InvalidXLogRecPtr; + /* * CheckXidAlive is a xid value pointing to a possibly ongoing (sub) * transaction. Currently, it is used in logical decoding. It's possible @@ -1492,6 +1502,7 @@ RecordTransactionCommit(void) RelcacheInitFileInval, MyXactFlags, InvalidTransactionId, NULL /* plain commit */ ); + XactLastCommitRecordEnd = XactLastRecEnd; if (replorigin) /* Move LSNs forward for this replication origin */ @@ -1623,6 +1634,19 @@ cleanup: return latestXid; } +/* + * GUC show_hook for last_commit_lsn + */ +const char * +show_last_commit_lsn(void) +{ + static char buf[32]; + + snprintf(buf, sizeof(buf), "%X/%08X", + LSN_FORMAT_ARGS(XactLastCommitRecordEnd)); + return buf; +} + /* * AtCCI_LocalCache diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c index 21c9ccec1e..ced29d1d5b 100644 --- a/src/backend/utils/misc/guc.c +++ b/src/backend/utils/misc/guc.c @@ -2518,6 +2518,23 @@ ReportChangedGUCOptions(void) SetConfigOption("in_hot_standby", "false", PGC_INTERNAL, PGC_S_OVERRIDE); + /* + * last_commit_lsn isn't GUC_REPORT, since only clients that ask for it + * with report_commit_lsn want a report after each commit. Its value + * changes without going through the GUC machinery, so check it here. + * ReportGUCOption sends nothing if it hasn't changed since the last + * report. + */ + if (report_commit_lsn) + { + static struct config_generic *last_commit_lsn_conf = NULL; + + if (last_commit_lsn_conf == NULL) + last_commit_lsn_conf = find_option("last_commit_lsn", + false, false, ERROR); + ReportGUCOption(last_commit_lsn_conf); + } + /* Transmit new values of interesting variables */ slist_foreach_modify(iter, &guc_report_list) { diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat index 184fcf4908..b08ff6ae62 100644 --- a/src/backend/utils/misc/guc_parameters.dat +++ b/src/backend/utils/misc/guc_parameters.dat @@ -1566,6 +1566,14 @@ boot_val => 'PG_KRB_SRVTAB', }, +{ name => 'last_commit_lsn', type => 'string', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS', + short_desc => 'Shows the end of the commit record of the session\'s most recent commit.', + flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE', + variable => 'last_commit_lsn_string', + boot_val => '"0/00000000"', + show_hook => 'show_last_commit_lsn', +}, + { name => 'lc_messages', type => 'string', context => 'PGC_SUSET', group => 'CLIENT_CONN_LOCALE', short_desc => 'Sets the language in which messages are displayed.', long_desc => 'An empty string means use the operating system setting.', @@ -2561,6 +2569,13 @@ boot_val => 'true', }, +{ name => 'report_commit_lsn', type => 'bool', context => 'PGC_USERSET', group => 'CLIENT_CONN_STATEMENT', + short_desc => 'Reports last_commit_lsn to the client after each commit.', + flags => 'GUC_NOT_IN_SAMPLE', + variable => 'report_commit_lsn', + boot_val => 'false', +}, + { name => 'reserved_connections', type => 'int', context => 'PGC_POSTMASTER', group => 'CONN_AUTH_SETTINGS', short_desc => 'Sets the number of connection slots reserved for roles with privileges of pg_use_reserved_connections.', variable => 'ReservedConnections', diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c index a05fc356fc..c7a86be3ff 100644 --- a/src/backend/utils/misc/guc_tables.c +++ b/src/backend/utils/misc/guc_tables.c @@ -630,6 +630,7 @@ static char *client_encoding_string; static char *datestyle_string; static char *server_encoding_string; static char *server_version_string; +static char *last_commit_lsn_string; static int server_version_num; static char *debug_io_direct_string; static char *restrict_nonsystem_relation_kind_string; diff --git a/src/include/access/xact.h b/src/include/access/xact.h index a8cbdf247c..7cffbfe26d 100644 --- a/src/include/access/xact.h +++ b/src/include/access/xact.h @@ -83,6 +83,10 @@ typedef enum /* Synchronous commit level */ extern PGDLLIMPORT int synchronous_commit; +/* End of this session's last commit record, and whether to report it */ +extern PGDLLIMPORT bool report_commit_lsn; +extern PGDLLIMPORT XLogRecPtr XactLastCommitRecordEnd; + /* used during logical streaming of a transaction */ extern PGDLLIMPORT TransactionId CheckXidAlive; extern PGDLLIMPORT bool bsysscan; diff --git a/src/include/utils/guc_hooks.h b/src/include/utils/guc_hooks.h index 8e3c067f76..731e786659 100644 --- a/src/include/utils/guc_hooks.h +++ b/src/include/utils/guc_hooks.h @@ -65,6 +65,7 @@ extern bool check_huge_page_size(int *newval, void **extra, GucSource source); extern void assign_io_method(int newval, void *extra); extern bool check_io_max_concurrency(int *newval, void **extra, GucSource source); extern const char *show_in_hot_standby(void); +extern const char *show_last_commit_lsn(void); extern bool check_locale_messages(char **newval, void **extra, GucSource source); extern void assign_locale_messages(const char *newval, void *extra); extern bool check_locale_monetary(char **newval, void **extra, GucSource source); diff --git a/src/test/modules/libpq_pipeline/libpq_pipeline.c b/src/test/modules/libpq_pipeline/libpq_pipeline.c index 66125d16ea..b823a9444a 100644 --- a/src/test/modules/libpq_pipeline/libpq_pipeline.c +++ b/src/test/modules/libpq_pipeline/libpq_pipeline.c @@ -1489,6 +1489,125 @@ test_protocol_version(PGconn *conn) PQconninfoFree(opts); } +/* + * Run a command that returns no rows, and fail unless it succeeds. + */ +static void +exec_command_ok(PGconn *conn, const char *sql) +{ + PGresult *res = PQexec(conn, sql); + + if (PQresultStatus(res) != PGRES_COMMAND_OK) + pg_fatal("\"%s\" failed: %s", sql, PQerrorMessage(conn)); + PQclear(res); +} + +/* + * Return the last_commit_lsn reported to us, failing if none has been, and + * check that it matches what the server shows. + */ +static char * +reported_commit_lsn(PGconn *conn) +{ + const char *reported = PQparameterStatus(conn, "last_commit_lsn"); + PGresult *res; + + if (reported == NULL) + pg_fatal("last_commit_lsn was not reported"); + + res = PQexec(conn, "SHOW last_commit_lsn"); + if (PQresultStatus(res) != PGRES_TUPLES_OK) + pg_fatal("SHOW last_commit_lsn failed: %s", PQerrorMessage(conn)); + if (strcmp(PQgetvalue(res, 0, 0), reported) != 0) + pg_fatal("last_commit_lsn reported as %s, but shown as %s", + reported, PQgetvalue(res, 0, 0)); + PQclear(res); + + return pg_strdup(reported); +} + +/* + * Test that last_commit_lsn is reported once report_commit_lsn is on, after + * each commit that wrote a commit record, and not otherwise. + */ +static void +test_report_commit_lsn(PGconn *conn) +{ + PGresult *res; + char *lsn; + char *prev; + + exec_command_ok(conn, "CREATE TABLE commit_lsn_tbl (a int)"); + if (PQparameterStatus(conn, "last_commit_lsn") != NULL) + pg_fatal("last_commit_lsn reported without report_commit_lsn"); + + /* Turning it on reports the value, which hasn't been reported yet */ + exec_command_ok(conn, "SET report_commit_lsn = on"); + prev = reported_commit_lsn(conn); + if (strcmp(prev, "0/00000000") == 0) + pg_fatal("last_commit_lsn not set by CREATE TABLE"); + + /* An autocommit INSERT reports a new value */ + exec_command_ok(conn, "INSERT INTO commit_lsn_tbl VALUES (1)"); + lsn = reported_commit_lsn(conn); + if (strcmp(lsn, prev) == 0) + pg_fatal("last_commit_lsn not advanced by INSERT"); + pg_free(prev); + prev = lsn; + + /* A rolled back transaction doesn't */ + exec_command_ok(conn, "BEGIN"); + exec_command_ok(conn, "INSERT INTO commit_lsn_tbl VALUES (2)"); + exec_command_ok(conn, "ROLLBACK"); + lsn = reported_commit_lsn(conn); + if (strcmp(lsn, prev) != 0) + pg_fatal("last_commit_lsn advanced by ROLLBACK, from %s to %s", + prev, lsn); + pg_free(lsn); + + /* + * In a pipeline, the value is reported at the Sync, before the + * ReadyForQuery, and so it's known once the pipeline's results are. + */ + if (PQenterPipelineMode(conn) != 1) + pg_fatal("failed to enter pipeline mode: %s", PQerrorMessage(conn)); + if (PQsendQueryParams(conn, "BEGIN", 0, NULL, NULL, NULL, NULL, 0) != 1 || + PQsendQueryParams(conn, "INSERT INTO commit_lsn_tbl VALUES (3)", + 0, NULL, NULL, NULL, NULL, 0) != 1 || + PQsendQueryParams(conn, "COMMIT", 0, NULL, NULL, NULL, NULL, 0) != 1 || + PQsendQueryParams(conn, "SELECT current_setting('last_commit_lsn')", + 0, NULL, NULL, NULL, NULL, 0) != 1) + pg_fatal("failed to send query: %s", PQerrorMessage(conn)); + if (PQpipelineSync(conn) != 1) + pg_fatal("pipeline sync failed: %s", PQerrorMessage(conn)); + + consume_result_status(conn, PGRES_COMMAND_OK); + consume_null_result(conn); + consume_result_status(conn, PGRES_COMMAND_OK); + consume_null_result(conn); + consume_result_status(conn, PGRES_COMMAND_OK); + consume_null_result(conn); + res = confirm_result_status(conn, PGRES_TUPLES_OK); + lsn = pg_strdup(PQgetvalue(res, 0, 0)); + PQclear(res); + consume_null_result(conn); + consume_result_status(conn, PGRES_PIPELINE_SYNC); + + if (strcmp(PQparameterStatus(conn, "last_commit_lsn"), lsn) != 0) + pg_fatal("last_commit_lsn reported as %s after the pipeline, expected %s", + PQparameterStatus(conn, "last_commit_lsn"), lsn); + if (strcmp(lsn, prev) == 0) + pg_fatal("last_commit_lsn not advanced by the pipeline's COMMIT"); + if (PQexitPipelineMode(conn) != 1) + pg_fatal("failed to exit pipeline mode: %s", PQerrorMessage(conn)); + pg_free(prev); + pg_free(lsn); + + exec_command_ok(conn, "DROP TABLE commit_lsn_tbl"); + + fprintf(stderr, "ok\n"); +} + /* Notice processor: print notices, and count how many we got */ static void notice_processor(void *arg, const char *message) @@ -2172,6 +2291,7 @@ print_test_list(void) printf("pipelined_insert\n"); printf("prepared\n"); printf("protocol_version\n"); + printf("report_commit_lsn\n"); printf("simple_pipeline\n"); printf("singlerow\n"); printf("transaction\n"); @@ -2288,6 +2408,8 @@ main(int argc, char **argv) test_prepared(conn); else if (strcmp(testname, "protocol_version") == 0) test_protocol_version(conn); + else if (strcmp(testname, "report_commit_lsn") == 0) + test_report_commit_lsn(conn); else if (strcmp(testname, "simple_pipeline") == 0) test_simple_pipeline(conn); else if (strcmp(testname, "singlerow") == 0) diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index cb3df6ed89..c82d420041 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -70,6 +70,7 @@ tests += { 't/059_remote_apply_status_interval.pl', 't/060_multixact_crashed_updater.pl', 't/061_recovery_target_prefetch.pl', + 't/062_last_commit_lsn.pl', ], }, } diff --git a/src/test/recovery/t/062_last_commit_lsn.pl b/src/test/recovery/t/062_last_commit_lsn.pl new file mode 100644 index 0000000000..8ce48e6762 --- /dev/null +++ b/src/test/recovery/t/062_last_commit_lsn.pl @@ -0,0 +1,94 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Check that a standby that has replayed up to the last_commit_lsn a session +# was shown shows that session's commit. + +use strict; +use warnings FATAL => 'all'; + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node_primary = PostgreSQL::Test::Cluster->new('primary'); +$node_primary->init(allows_streaming => 1); +$node_primary->append_conf('postgresql.conf', + 'max_prepared_transactions = 2'); +$node_primary->start; +$node_primary->safe_psql( + 'postgres', q[ + CREATE TABLE commit_lsn_test (a int); + CREATE PROCEDURE two_commits() LANGUAGE plpgsql AS $$ + BEGIN + INSERT INTO commit_lsn_test VALUES (3); + COMMIT; + INSERT INTO commit_lsn_test VALUES (4); + COMMIT; + END $$; +]); +$node_primary->backup('backup'); + +# A standby that replays each commit a second late, so that the waits below +# have something to wait for. +my $node_standby = PostgreSQL::Test::Cluster->new('standby'); +$node_standby->init_from_backup($node_primary, 'backup', has_streaming => 1); +$node_standby->append_conf( + 'postgresql.conf', qq[ + max_prepared_transactions = 2 + recovery_min_apply_delay = '1s' +]); +$node_standby->start; + +my $timeout = $PostgreSQL::Test::Utils::timeout_default; + +foreach my $case ( + [ 'autocommit INSERT', 'INSERT INTO commit_lsn_test VALUES (1);', 1 ], + [ + 'explicit transaction', + 'BEGIN; INSERT INTO commit_lsn_test VALUES (2); COMMIT;', 2 + ], + [ 'procedure that commits twice', 'CALL two_commits();', 4 ], + [ + 'COMMIT PREPARED', + "BEGIN; INSERT INTO commit_lsn_test VALUES (5); + PREPARE TRANSACTION 'p'; COMMIT PREPARED 'p';", 5 + ]) +{ + my ($desc, $sql, $value) = @$case; + + my $lsn = + $node_primary->safe_psql('postgres', "$sql SHOW last_commit_lsn;"); + my $output = $node_standby->safe_psql( + 'postgres', qq[ + WAIT FOR LSN '$lsn' WITH (timeout '${timeout}s'); + SELECT count(*) FROM commit_lsn_test WHERE a = $value; + ]); + is($output, "success\n1", "$desc is visible on the standby at $lsn"); +} + +# Transactions that write no commit record leave the value alone. +my @lsns = split /\n/, $node_primary->safe_psql( + 'postgres', q[ + INSERT INTO commit_lsn_test VALUES (6); + SHOW last_commit_lsn; + BEGIN; INSERT INTO commit_lsn_test VALUES (7); ROLLBACK; + SHOW last_commit_lsn; + BEGIN; INSERT INTO commit_lsn_test VALUES (8); PREPARE TRANSACTION 'q'; + SHOW last_commit_lsn; + ROLLBACK PREPARED 'q'; + SHOW last_commit_lsn; +]); +is_deeply( + [ @lsns[ 1 .. 3 ] ], + [ ($lsns[0]) x 3 ], + 'ROLLBACK, PREPARE TRANSACTION and ROLLBACK PREPARED leave it alone'); + +is( $node_primary->safe_psql( + 'postgres', q[ + BEGIN; INSERT INTO commit_lsn_test VALUES (9); ROLLBACK; + SHOW last_commit_lsn; + ]), + '0/00000000', + 'a session that has committed nothing shows 0/00000000'); + +done_testing(); diff --git a/src/test/regress/expected/transactions.out b/src/test/regress/expected/transactions.out index 3b2fc5cc93..088504a5db 100644 --- a/src/test/regress/expected/transactions.out +++ b/src/test/regress/expected/transactions.out @@ -1264,6 +1264,62 @@ SELECT * FROM trans_abc ORDER BY 1; (3 rows) DROP TABLE trans_abc; +-- last_commit_lsn: the end of the commit record of this session's last commit +CREATE TABLE trans_lsn (a int); +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +SELECT :'lsn'::pg_lsn > '0/0' AS set_by_create, + :'lsn'::pg_lsn <= pg_current_wal_insert_lsn() AS not_ahead; + set_by_create | not_ahead +---------------+----------- + t | t +(1 row) + +INSERT INTO trans_lsn VALUES (1); +SELECT current_setting('last_commit_lsn')::pg_lsn > :'lsn' AS advanced; + advanced +---------- + t +(1 row) + +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +-- unchanged by transactions that write no commit record +SELECT count(*) FROM trans_lsn; + count +------- + 1 +(1 row) + +BEGIN; +INSERT INTO trans_lsn VALUES (2); +ROLLBACK; +BEGIN; +INSERT INTO trans_lsn VALUES (3); +SELECT current_setting('last_commit_lsn')::pg_lsn = :'lsn' AS unchanged; + unchanged +----------- + t +(1 row) + +COMMIT; +SELECT current_setting('last_commit_lsn')::pg_lsn > :'lsn' AS advanced; + advanced +---------- + t +(1 row) + +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +-- parallel workers show the leader's value +SET debug_parallel_query = on; +SELECT current_setting('last_commit_lsn')::pg_lsn = :'lsn' AS same_in_worker; + same_in_worker +---------------- + t +(1 row) + +RESET debug_parallel_query; +SET last_commit_lsn = '0/0'; -- error +ERROR: parameter "last_commit_lsn" cannot be changed +DROP TABLE trans_lsn; -- TRANSACTION SNAPSHOT -- Incorrect identifier. BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; diff --git a/src/test/regress/sql/transactions.sql b/src/test/regress/sql/transactions.sql index f43d6122f8..cc171cccd4 100644 --- a/src/test/regress/sql/transactions.sql +++ b/src/test/regress/sql/transactions.sql @@ -658,6 +658,32 @@ SELECT * FROM trans_abc ORDER BY 1; DROP TABLE trans_abc; +-- last_commit_lsn: the end of the commit record of this session's last commit +CREATE TABLE trans_lsn (a int); +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +SELECT :'lsn'::pg_lsn > '0/0' AS set_by_create, + :'lsn'::pg_lsn <= pg_current_wal_insert_lsn() AS not_ahead; +INSERT INTO trans_lsn VALUES (1); +SELECT current_setting('last_commit_lsn')::pg_lsn > :'lsn' AS advanced; +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +-- unchanged by transactions that write no commit record +SELECT count(*) FROM trans_lsn; +BEGIN; +INSERT INTO trans_lsn VALUES (2); +ROLLBACK; +BEGIN; +INSERT INTO trans_lsn VALUES (3); +SELECT current_setting('last_commit_lsn')::pg_lsn = :'lsn' AS unchanged; +COMMIT; +SELECT current_setting('last_commit_lsn')::pg_lsn > :'lsn' AS advanced; +SELECT current_setting('last_commit_lsn')::pg_lsn AS lsn \gset +-- parallel workers show the leader's value +SET debug_parallel_query = on; +SELECT current_setting('last_commit_lsn')::pg_lsn = :'lsn' AS same_in_worker; +RESET debug_parallel_query; +SET last_commit_lsn = '0/0'; -- error +DROP TABLE trans_lsn; + -- TRANSACTION SNAPSHOT -- Incorrect identifier. BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- 2.54.0 (Apple Git-157)