From 4ac452e2285da347c75f5960ae211e183a87b57b Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Wed, 24 Nov 2021 13:37:11 -0500 Subject: [PATCH] Doc: improve documentation about nextval()/setval(). Clarify that the results of nextval and setval are not guaranteed persistent until the calling transaction commits. Some people seem to have drawn the opposite conclusion from the statement that these functions are never rolled back, so re-word to avoid saying it quite that way. Discussion: https://postgr.es/m/CAKU4AWohO=NfM-4KiZWvdc+z3c1C9FrUBR6xnReFJ6sfy0i=Lw@mail.gmail.com --- doc/src/sgml/func.sgml | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml index 74d3087a723..0a725a67117 100644 --- a/doc/src/sgml/func.sgml +++ b/doc/src/sgml/func.sgml @@ -17645,24 +17645,37 @@ SELECT setval('myseq', 42, false); Next nextval To avoid blocking concurrent transactions that obtain numbers from - the same sequence, a nextval operation is never - rolled back; that is, once a value has been fetched it is considered - used and will not be returned again. This is true even if the - surrounding transaction later aborts, or if the calling query ends - up not using the value. For example an INSERT with + the same sequence, the value obtained by nextval + is not reclaimed for re-use if the calling transaction later aborts. + This means that transaction aborts or database crashes can result in + gaps in the sequence of assigned values. That can happen without a + transaction abort, too. For example an INSERT with an ON CONFLICT clause will compute the to-be-inserted tuple, including doing any required nextval calls, before detecting any conflict that would cause it to follow - the ON CONFLICT rule instead. Such cases will leave - unused holes in the sequence of assigned values. + the ON CONFLICT rule instead. Thus, PostgreSQL sequence objects cannot be used to obtain gapless sequences. - Likewise, any sequence state changes made by setval - are not undone if the transaction rolls back. + Likewise, sequence state changes made by setval + are immediately visible to other transactions, and are not undone if + the calling transaction rolls back. + + + + If the database cluster crashes before committing a transaction + containing a nextval + or setval call, the sequence state change might + not have made its way to persistent storage, so that it is uncertain + whether the sequence will have its original or updated state after the + cluster restarts. This is harmless for usage of the sequence within + the database, since other effects of uncommitted transactions will not + be visible either. However, if you wish to use a sequence value for + persistent outside-the-database purposes, make sure that the + nextval call has been committed before doing so.